声明带有撇号的字符串将在“IN”语句

时间:2015-07-01 03:04:51

标签: sql sql-server sql-server-2008

我需要某人的专业知识来声明其中包含撇号(')的字符串,以便在WHERE IN语句中使用。下面是我当前代码的示例,它不返回任何内容:

DECLARE @Cons_Val VARCHAR(50) = '''Tot Mens'', ''Tot Womens'', ''Tot Kids'''

SELECT table1.column1 AS 'Country'
    , table1.column2 AS 'Consumer'
FROM table1
WHERE table1.column2 IN (@Cons_Val)

提前谢谢! :)

1 个答案:

答案 0 :(得分:1)

如果要使用IN语句进行变量化,则必须使用动态SQL。

DECLARE @Cons_Val VARCHAR(50) = '''Tot Mens'', ''Tot Womens'', ''Tot Kids'''

declare @sql varchar(1000) = 'SELECT table1.column1 AS Country
    , table1.column2 AS Consumer
FROM table1
WHERE table1.column2 IN (' + @Cons_Val + ')'

print @sql
exec (@sql)