SQL Server > Loops and Conditions

Use IF condition in SQL Server

How to use IF condition in SQL Server?

If condition works in SQL server in the same way it works in other programming language. In SQL Server, instead of opening and closing curly braces to specify the blocks for IF, ELSE or ELSE IF condition, we use BEGIN and END instead of "{" and "}".

DECLARE @pdId int
SET @pdId = 11 -- change here
IF (EXISTS(SELECT PersonalDetailsId FROM PersonalDetails WHERE PersonalDetailsId =
               SELECT * FROM PersonalDetails WHERE PersonalDetailsId = @pdId
               SELECT 'No record found.' as Results

Look at above SQL code, we have first declared @pdId variable and setting its value as 11.

In the next like we are checking for using EXISTS in-built function with parameter as the record from PersonalDetails whose PersonalDetailsId as @pdId. If the record is found, EXISTS returns true and the first IF block executes and gives all columns from PersonalDetails otherwise ‘No record found’ message is show.

Records found

Records not found

 Views: 1384 | Post Order: 101

Write for us