Tuesday 12 July 2011

IF statement in SQL Stored Procedure

A nifty little SQL code here, that checks if a value exists in a SQL table, and if it finds the value doesn't exist will insert the value....

First declare and set the variable
DECLARE @patientID VARCHAR(30)
SET @patientID = 'xxxxxxx'

next write the if statement to check if the value already exists in the table
if exists(Select * From episodes
Where patient_id=@patientID)





If it exists return and end the function
begin
return
end





Else insert the value into the table
else
begin
INSERT INTO episodes(patient_id)
values(@patientID)



End the statement

end
Go

And thats it, of course if you wish you can write this as a stored procedure. Good Luck.

No comments:

Post a Comment