Raghurocks
Raghurocks

Reputation: 925

IN statement in SQL Server

Query 1:

DECLARE @strSQL NVARCHAR(MAX) = ''
DECLARE @MultiIDs NVARCHAR(50) = '7,8'
SET @strSQL = 'SELECT TOP 1 [User].PracticeID FROM [User] WHERE [UserId] IN (' + @MultiIDs + ')'    
EXEC(@strSQL)

Query2 :

DECLARE @MultiIDs NVARCHAR(550) = '7,8'
SELECT TOP 1 [User].PracticeID FROM [User] WHERE [UserId] IN (@MultiIDs)    

Why Query1 will work not Query2?

any explanation is greatly appreciated. Thanks

Upvotes: 0

Views: 82

Answers (1)

juergen d
juergen d

Reputation: 204746

Because query 2 results in

WHERE [UserId] IN ('7,8') 

which is one string (containing 2 values) and not separate values.

Query 1 is completely a string and will be translated into

WHERE [UserId] IN (7,8) 

(notice the quotes)

Upvotes: 4

Related Questions