简体   繁体   中英

Insert list of values into a SQL Server table with stored procedure

How can I pass a list of column data into a stored procedure?

My stored procedure is

ALTER PROCEDURE [dbo].[Register]
    @Id        int,
    @Name nvarchar(50)
AS
BEGIN
    BEGIN TRY
        INSERT INTO dbo.Group (Id, Name) 
        VALUES(@Id, @Name)

        SELECT 0
    END TRY
    BEGIN CATCH
        SELECT -1
    END CATCH
END
GO

I want pass like this data for insert into this table

@Id = 1,2,3,4,5 
@Name = 'test1,test2,test3,test4,test5'

and result like this

Id   Name
1    test1
2    test2
3    test3
4    test4
5    test5

A "list" or "array" in SQL Server is ..... a table . So if you're on SQL Server 2008 or newer (you didn't specify), then use the table-valued parameter feature of SQL Server to pass a table of value to your stored procedure

-- Create a table type to match your input parameters
CREATE TYPE IdNameTable AS TABLE 
( ID INT, Name NVARCHAR(50) );
GO

-- change your stored procedure to accept such a table type parameter
ALTER PROCEDURE [dbo].[Register]
    @Values IdNameTable READONLY
AS
BEGIN
    BEGIN TRY
        INSERT INTO dbo.Group (Id, Name) 
          -- get the values from the table type parameter
          SELECT 
             Id, Name
          FROM
             @Values

        SELECT 0
    END TRY
    BEGIN CATCH
        SELECT -1
    END CATCH
END
GO

See the extensive and freely available SQL Server Books Online documentation for more details on the table-valued parameter feature and how to use it

If you want to use this from T-SQL, use this code:

-- declare a variable of that table type
DECLARE @InputTable IdNameTable

-- insert values into that table variable
INSERT INTO @InputTable(ID, Name) 
VALUES (1, 'Test 1'), (2, 'Test 2')

-- execute your stored procedure with this table as input parameter
EXECUTE [dbo].[Register] @InputTable

If you want to use this from C# or VB.NET, see Michael Edenfield's link in comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM