Link to home
Start Free TrialLog in
Avatar of Jeff S
Jeff SFlag for United States of America

asked on

Insert Record if no records found - SQL

I need to insert a record if no records exist. In my example below, It returned no records; therefore I need it to return the current date for the created, for CreatedBy it can be  'N/A' and Description equal to 'No Correspondence Notes'.

DECLARE @PATIENTVISITID INT = 695

SELECT
	  pc.Created
	, ISNULL ( NULLIF ( REPLACE ( pc.CreatedBy , CHAR ( 0 ) , '' ) , '' ) , 'System' ) AS CreatedBy 
	, CASE
		 WHEN pc.Description = '**long**' THEN pc.DescriptionLong
		 ELSE pc.Description
	  END AS Description
FROM PatientCorrespondence pc
WHERE pc.PatientVisitID = @PATIENTVISITID;

Open in new window

Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

Is PatientVisitID PK? If so, then we need to add two more new lines to suppress identity effect.

Try:
DECLARE @PATIENTVISITID INT
As
Begin
DECLARE @Created dateTime = GEtDate();
DECLARE @CreatedBy varchar(50)= 'N/A';
DECLARE @Description varchar(50) ='No Correspondence Notes';
  
SELECT
	  pc.Created
	, ISNULL ( NULLIF ( REPLACE ( pc.CreatedBy , CHAR ( 0 ) , '' ) , '' ) , 'System' ) AS CreatedBy 
	, CASE
		 WHEN pc.Description = '**long**' THEN pc.DescriptionLong
		 ELSE pc.Description
	  END AS Description
FROM PatientCorrespondence pc
WHERE pc.PatientVisitID = @PATIENTVISITID;
)

if @@ROWCOUNT = 0
Begin

 Insert Into PatientCorrespondence (Created, CreatedBy, [Description], PatientVisitID) Values
                        (@Created, @CreatedBy, @Description, @PATIENTVISITID); 
End
End

Open in new window

Avatar of Jeff S

ASKER

Yes, PatientVisitId is the PK.
ASKER CERTIFIED SOLUTION
Avatar of Mike Eghtebas
Mike Eghtebas
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jeff S

ASKER

Many thanks!