0

迫切需要一个 sp 来为单个变量传递多个值,例如@list一个变量,我为它输入的值是 ' 1,3,4,5,66',我需要从表中与这些 id 相关的信息:

SELECT T.C.value('.', 'NVARCHAR(100)') AS [id]
    INTO #tblPersons
    FROM (SELECT CAST ('<Name>' + REPLACE(@empid, ',', '</Name><Name>') + '</Name>' AS XML) AS [Names]) AS A
    cross APPLY Names.nodes('/Name') as T(C) 

我在我的 sp 中使用它,但我很难将它传递给多个值。

4

1 回答 1

1

您是否考虑过使用表变量将数据传递给存储过程。例子:

设置

CREATE TYPE EmpIdValuesType AS TABLE
  (                     
        [EmpID] [int]NOT NULL
  )

CREATE TABLE Employee
(
  EmpID INT,
  Name varchar(20)
 )

INSERT INTO Employee 
Values
 (1, 'test1'),
 (2, 'test2'),
 (3, 'test3'),
 (4, 'test4'),
 (5, 'test5'),
 (6, 'test6'),
 (7, 'test7');

Create Procedure usp_GetEmployees
(
  @TableVariable EmpIdValuesType READONLY
)
AS
  SELECT *
  FROM Employee
  INNER JOIN @TableVAriable TV
    ON Employee.EmpId = TV.EmpId

现在您可以将行插入到 EmpIdValuesType 类型的临时表变量中,并将该变量传递给存储过程:

调用存储过程

DECLARE @empIds AS EmpIdValuesType

INSERT INTO @empIds(EmpID) Values (1), (2), (5)

Exec usp_GetEmployees @empIds;

结果如下: SQL 结果

SQLFiddle

于 2012-11-06T21:47:08.183 回答