遍历 sql 中的字符串列表并分配为变量

Iterate through a list of string in sql and assign as a variable

我有一个字符串列表,我想迭代并设置为 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 的算术溢出错误

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

这个查询是无限的,因为 table 中总是有行。

您尝试做的事情称为游标,如果可能有其他选择,您应该避免在 SQL 中使用游标。在这种情况下,OUTER APPLY 将起作用。

首先,将您的 excel 文件导入数据库 table。 参见 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更改为导入的table。这将 return 您来自 excel table 的所有行以及来自右侧的行,其中将有匹配项或 NULL 将没有匹配项。在 APPLY 查询中,您可以 return 标量值以及 table。