在IN里面的SELECT查询中使用变量比较

时间:2014-03-10 17:56:28

标签: sql-server sql-server-2008 tsql variables

这是一个简单的例子:

为什么这样做:

DECLARE @v as varchar(75)
SET @v = 'xxx-xxxx'
SELECT * FROM tbl_skus WHERE SKU = @v

但这不起作用:

DECLARE @v as varchar(75)
SET @v = 'xxx-xxxx,yyy-yyyy'
SELECT * FROM tbl_skus WHERE SKU IN ( @v )

SKU的'xxx-xxxx'和'yyy-yyyy'都在表格中。第一个查询拉出1个结果,第二个查询拉0个结果;没有错误。

3 个答案:

答案 0 :(得分:3)

因为您的查询正在查找文字'xxx-xxxx,yyy-yyyy',这意味着它只是一个字符串,其中包含逗号,而不是由逗号分隔的2个字符串。 您的查询转换为:

SELECT * FROM tbl_skus WHERE SKU IN ('xxx-xxxx,yyy-yyyy')

为了让它按你的意愿工作,它应该是:

SELECT * FROM tbl_skus WHERE SKU IN ('xxx-xxxx','yyy-yyyy')

答案 1 :(得分:1)

您无法为单个变量分配两个值。你必须做这样的事情:

DECLARE @v as varchar(75) DECLARE @a as varchar(75)

SET @v ='xxx-xxxx' SET @a ='yyy-yyyy'

SELECT * FROM tbl_skus
SKU IN(@ v,@ a)

答案 2 :(得分:0)

你应该使用这样的光标(例如):

DECLARE @MyCursor CURSOR
SET @MyCursor = CURSOR FAST_FORWARD
FOR
SELECT Table_Training_Detalis.DateExpires,Table_Training_Detalis.Worker_ID
FROM   Table_Courses 
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @ColExpir,@ColWorkid
WHILE @@FETCH_STATUS = 0
BEGIN
update Table_Workers set WHIMIS= @ColExpir where Worker_ID=@ColWorkid

FETCH NEXT FROM @MyCursor
INTO @ColExpir,@ColWorkid
END
CLOSE @MyCursor
DEALLOCATE @MyCursor