在声明部分分配多个值
Assign multiple values in declaration part
我需要通过提供多个声明值来实现结果。怎么做到的?
DECLARE @ID INT
SET @ID = 1 --instead I need to provide multiple values like @ID = 1,2,3
SELECT C.Name, C.EmployeeID
FROM Cases c
WHERE C.EmployeeID = @ID
Table
Name | ID
-------+---------
A 1
B 2
C 3
D 4
E 5
F 6
结果应该是:
A 1
B 2
C 3
一种方法是使用 table 变量:
DECLARE @IDs TABLE(ID INT);
INSERT INTO @IDs VALUES(1),(2),(3);
SELECT C.Name, C.EmployeeID
FROM dbo.Cases AS c
WHERE C.EmployeeID IN(SELECT ID FROM @IDs);
一个非常简单的方法是使用 XML 数据类型。
DECLARE @ids xml = '<ids><id>1</id><id>2</id><id>3</id></ids>';
SELECT
C.[Name],
C.EmployeeID
FROM Cases c
WHERE C.EmployeeID IN (
SELECT x.f.value( '.', 'int' ) FROM @ids.nodes ( '//ids/id' ) x( f )
);
我需要通过提供多个声明值来实现结果。怎么做到的?
DECLARE @ID INT
SET @ID = 1 --instead I need to provide multiple values like @ID = 1,2,3
SELECT C.Name, C.EmployeeID
FROM Cases c
WHERE C.EmployeeID = @ID
Table
Name | ID
-------+---------
A 1
B 2
C 3
D 4
E 5
F 6
结果应该是:
A 1
B 2
C 3
一种方法是使用 table 变量:
DECLARE @IDs TABLE(ID INT);
INSERT INTO @IDs VALUES(1),(2),(3);
SELECT C.Name, C.EmployeeID
FROM dbo.Cases AS c
WHERE C.EmployeeID IN(SELECT ID FROM @IDs);
一个非常简单的方法是使用 XML 数据类型。
DECLARE @ids xml = '<ids><id>1</id><id>2</id><id>3</id></ids>';
SELECT
C.[Name],
C.EmployeeID
FROM Cases c
WHERE C.EmployeeID IN (
SELECT x.f.value( '.', 'int' ) FROM @ids.nodes ( '//ids/id' ) x( f )
);