我想在设置RECEIPTIDS
变量时编写一个IN语句,以便我可以将该格式的多个值传递给我的查询。我尝试过以下方法:
DECLARE @RECEIPTIDS VARCHAR(2000)
SET @RECEIPTIDS = ('R00013','R00028')
然而,我收到错误:
','附近的语法不正确。
答案 0 :(得分:3)
DECLARE @RECEIPTIDS TABLE(val VARCHAR(100))
Insert into @RECEIPTIDS values ('R00013'), ('R00028')
您可以在IN中使用它
where field IN (Select val from @RECEIPTIDS)
答案 1 :(得分:3)
使用临时数组或临时列表
DECLARE @ListofIDs TABLE(IDs VARCHAR(100))
INSERT INTO @ListofIDs VALUES('a'),('10'),('20'),('c'),('30'),('d')
SELECT IDs FROM @ListofIDs;
答案 2 :(得分:3)
你需要额外的单个qoutes。
create table MyTable
(
ID varchar(50)
)
insert into MyTable values('R00013')
insert into MyTable values('R00028')
insert into MyTable values('R00015')
DECLARE @RECEIPTIDS VARCHAR(2000)
SET @RECEIPTIDS = ('''R00013'',''R00028''')
DECLARE @QUERY VARCHAR(100)
SET @QUERY='SELECT *
from MyTable
where ID IN ('+@RECEIPTIDS+')'
EXEC (@QUERY)
已编辑:将其与动态查询结合使用。
答案 3 :(得分:0)
对我来说也不行,但这样做了:
DECLARE @RECEIPTIDS TABLE(val VARCHAR(100))
Insert into @RECEIPTIDS values ('R00013'), ('R00028')
where field IN (Select val from @RECEIPTIDS)