i need an sp to select or update my tables and for

2019-09-07 20:52发布

desperately need an sp to pass mutiple values for the single variable like @list is a variable and the values I'm putting for it are '1,3,4,5,66' and I need information from the table realated to these id's:

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) 

I'm using this in my sp but I'm getting difficulty for passing this for the mutiple values.

1条回答
SAY GOODBYE
2楼-- · 2019-09-07 21:22

Have you thought about using table variables to pass data to a stored procedure. Example:

Setup

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

Now you can insert rows into a temporary table variable of type EmpIdValuesType and pass the variable to the stored procedure:

Calling the Stored Procedure

DECLARE @empIds AS EmpIdValuesType

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

Exec usp_GetEmployees @empIds;

And here are the results: SQL Results

SQLFiddle

查看更多
登录 后发表回答