我有一个字符串列表,我想迭代并在sql中设置为变量,我想迭代这些字符串的列表[“one”,“two”,“three”,“four”]和然后将每个字符串设置为查询的变量。我尝试过以下方法:
Declare @Ids Table (id integer primary Key not null)
Insert @Ids(id) values(81570517139)
Insert @Ids(id) values(81676666808)
Insert @Ids(id) values(81496685880)
Insert @Ids(id) values(81596620831)
Insert @Ids(id) values(81254409851)
Insert @Ids(id) values(81641592011)
Insert @Ids(id) values(81690996037)
Insert @Ids(id) values(81121685039)
Insert @Ids(id) values(81527008494)
Insert @Ids(id) values(81174933036)
Insert @Ids(id) values(81081564187)
Declare @Id Integer
While exists (Select * From @Ids)
Begin
select fileName
from MarketMessage as a LEFT JOIN MessageType310 as b ON a.MarketMessageID = b.MarketMessageID
where b.MPRN = @id
End
但是我得到'将表达式转换为数据类型int
的算术溢出错误答案 0 :(得分:2)
Declare @Id Integer
While exists (Select * From @Ids)
Begin
select fileName
from MarketMessage as a LEFT JOIN MessageType310 as b ON a.MarketMessageID = b.MarketMessageID
where b.MPRN = @id
End
此查询是无限的,因为表中始终存在行。
你要做的是被称为游标,当你有其他选择时,你应该避免SQL中的游标。在这种情况下,OUTER APPLY将起作用。
首先,将excel文件导入数据库表。 见http://searchsqlserver.techtarget.com/feature/The-SQL-Server-Import-and-Export-Wizard-how-to-guide
然后您可以使用OUTER APPLY关键字:
DECLARE @excel_list TABLE ( filter NVARCHAR(MAX) )
INSERT INTO @excel_list
VALUES ( 'one' ),
( 'two' ),
( 'three' )
SELECT *
FROM @excel_list AS excel
OUTER APPLY ( SELECT fileName
FROM MarketMessage AS a
LEFT JOIN MessageType310 AS b ON a.MarketMessageID = b.MarketMessageID
WHERE b.MPRN = excel.filter
) o
将@excel_list更改为导入的表格。这将返回excel表中的所有行以及右应用侧的行,其中将存在匹配或NULL,其中将不匹配。在APPLY查询中,您可以返回标量值和表格。