如何在int上声明列表

时间:2018-07-23 12:06:35

标签: sql sql-server

在MS SQL中,我需要声明一个int列表以在IN子句中使用它。 像这样:

DECLARE @DATE AS DATE = '01.01.2018'
SELECT * FROM tank_state WHERE dt = @DATE AND tankId IN (14,15)

这项工作正常。很好。

在这里DECLARE

DECLARE @DATE AS DATE = '01.01.2018'
DECLARE @listOfIDs int = 14,15
SELECT * FROM tank_state WHERE dt = @DATE AND tankId IN (@listOfIDs)

但是我得到了错误:

Error: Incorrect syntax near '15'.
SQLState:  42000
ErrorCode: 102
Error: Must declare the scalar variable "@listOfIDs".
SQLState:  S1000
ErrorCode: 137

2 个答案:

答案 0 :(得分:5)

那是不正确的语法。您不能将两个int放入变量中,并且14,15将无法转换为int。

一种选择是将这些值放入表中

DECLARE @ints TABLE (val INT)
INSERT INTO @ints (val)
VALUES 
(14),
(15)

SELECT * FROM tank_state WHERE dt = @DATE AND tankId IN (SELECT val FROM @ints)

答案 1 :(得分:1)

一种方法是使用动态SQL:

DECLARE @DATE DATE = '2018-01-01';
DECLARE @listOfIDs varchar(max) = '14,15';

DECLARE @sql NVARCHAR(MAX) = '
SELECT *
FROM tank_state
WHERE dt = @DATE AND tankId IN (@listOfIDs)';

SET @sql = REPLACE(@sql, '@listOfIds', @listOfIds);

exec sp_executesql @sql, N'@date date', @date = date;

但是,更受欢迎的方法是使用string_split()之类的函数拆分列表(在SQL Server 2016及更高版本中可用)

SELECT *
FROM tank_state
WHERE dt = @DATE AND tankId IN (SELECT * FROM string_split(@listOfIDs, ','))';