SQL Set / Declare Variable

时间:2015-04-24 18:57:55

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

我设置了

declare @area as varchar(500)

set @area = '''Area1'',''Area2'''

我尝试将其放入WHERE子句中,但它没有检测到area。我猜是set @area =有什么问题?

这就是我试图将其引入的内容:

where area in (@area)

请帮助,谢谢。

5 个答案:

答案 0 :(得分:1)

由于您已获得要比较的元素列表,请使用table variable累积比较数据,例如:

DECLARE @area as TABLE(Name VARCHAR(50));
INSERT INTO @area(Name) VALUES ('Area1'), ('Area2');

然后你可以使用它:

SELECT * 
FROM MyTable
WHERE MyCol in (SELECT Name FROM @Area);

或者更好,通过直接连接(将取消失败的连接):

SELECT * 
FROM MyTable INNER JOIN @Area
ON MyTable.MyCol = @Area.Name;

答案 1 :(得分:0)

它应该是一个set而不是varchar变量:

where area in (select a from(values('Area1'),('Area2')) t(a))

答案 2 :(得分:0)

尝试类似

的内容
declare @area as varchar(500)

set @area = 'Area1,Area2'

SELECT * 
FROM TableName
where area in (
              SELECT Split.a.value('.', 'VARCHAR(100)') AS Area
              FROM (SELECT  CAST ('<M>' + REPLACE(@area, ',', '</M><M>') 
                + '</M>' AS XML) AS String ) AS A
               CROSS APPLY String.nodes ('/M') AS Split(a)
               )

答案 3 :(得分:0)

尝试使用动态sql,如 -

declare @area as varchar(500)
set @area = 'Area1,Area2'
DECLARE @sql varchar(500)
set @sql='SELECT *
FROM [dbo].[tbl] AS t
WHERE area in ('+@area+')'
exec (@sql)

declare @area as varchar(500)
set @area = '''Area1'',''Area2'''
DECLARE @sql varchar(500)
set @sql='SELECT *
FROM [dbo].[tbl] AS t
WHERE area in ('+@area+')'
PRINT @sql
exec (@sql)

答案 4 :(得分:0)

您的代码结果

查询

declare @area as varchar(500)
set @area = '''Area1'',''Area2'''

输入

print 'where area in (' + @area + ')'

结果

where area in ('Area1','Area2')