Discussion Locked

SQL Variables and 'IN' statements.

0 helpful
5 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Is it possible to use a variable with an 'IN' statement in an SQL procedure ie.

@variable is a text string = 'test1','test2'

SELECT column1_name
FROM table_name
WHERE column2_name IN @variable

5 replies

by jay_patrick

try something like this......

declare @V varchar(50)

select @V = " 'Blake','Tammy' "
exec(" select * from profiles where first in (" + @V + ")")

by steved

This syntax works for me:

DECLARE @V nvarchar(50), @sql nvarchar(200)
SET @V = 'N''test1'', N''test2'''
SET @sql = N'select * from table_name where column_name in (' + @V + N')'
EXEC sp_executesql @sql

Note: All those N's are required because sp_executesql accepts parameters of nvarchar type only.

I hope this helps.

Steve Diamond

This discussion is closed to new replies.