How to pass an array into a SQL Server stored procedure

前端 未结 11 2428
轻奢々
轻奢々 2020-11-21 23:28

How to pass an array into a SQL Server stored procedure?

For example, I have a list of employees. I want to use this list as a table and join it with another table.

11条回答
  •  忘了有多久
    2020-11-21 23:45

    I've been searching through all the examples and answers of how to pass any array to sql server without the hassle of creating new Table type,till i found this linK, below is how I applied it to my project:

    --The following code is going to get an Array as Parameter and insert the values of that --array into another table

    Create Procedure Proc1 
    
    
    @UserId int, //just an Id param
    @s nvarchar(max)  //this is the array your going to pass from C# code to your Sproc
    
    AS
    
        declare @xml xml
    
        set @xml = N'' + replace(@s,',','') + ''
    
        Insert into UserRole (UserID,RoleID)
        select 
           @UserId [UserId], t.value('.','varchar(max)') as [RoleId]
    
    
        from @xml.nodes('//root/r') as a(t)
    END 
    

    Hope you enjoy it

提交回复
热议问题