SQL Server – How to Check If Value Exists in Table

sql serversql-server-2008-r2t-sql

I am needing a way to run an If/Else statement in SQL Server. This is what I am needing done, if my Exec sp_executesql @SQL statement returns a value (meaning it exists in the table) I want to set the value returned to a variable. If it does not return a value, then I want to print a message saying it does not exist.

With the sample DDL Below, I would want to assign the value of 3 to the variable @placeholder since 3 would be the value returned. How would that syntax be constructed?

Create Table #Test1 (id int,name varchar(100))
Insert Into #Test1 Values (1, 'Blue'), (2, 'Red'), (3, 'Pink'), (4, 'Orange')

Declare @Color varchar(100), @sql nvarchar(max), @placeholder varchar(100)
Set @Color = 'Pink'

Set @Sql = 'Select id from #Test1 WHERE name IN ('''+@Color+N''')'

Exec sp_executesql @SQL

Drop Table #Test1

Best Answer

Your example looks quite simple and does not need sp_executesql statement (as long as your query returns only one row)...

You can set your variable in your select :

Create Table #Test1 (id int,name varchar(100))
Insert Into #Test1 Values (1, 'Blue'), (2, 'Red'), (3, 'Pink'), (4, 'Orange')

Declare @Color varchar(100), @returned_id varchar(100)
Set @Color = 'Pink'

Select @returned_id  = id 
from #Test1 
WHERE name = @Color

if @returned_id is null
    print 'Error - no rows returned for ' + @Color
else 
    print @returned_id

Drop Table #Test1