简体   繁体   中英

Insert results of a table into stored procedure as parameters

I have a stored procedure which inserts values into a table. Let's say its name is usp_InsertTableA with parameters @ID int and Name varchar(100) .

I have a requirement to call this stored procedure multiple times from another stored procedure. I am thinking to call this stored procedure something like below

exp usp_InsertTableA
select ID, Name from #tempTable

Is this possible in SQL Server to execute this with the value of the table and send it into a stored procedure?

You can use table type parameters to stored procedure. 在此处输入图片说明

CREATE TYPE [dbo].[udt_MyCustomTable] AS TABLE(
    [id] [int] NOT NULL,
    [name] [nvarchar](100) NOT NULL
)
GO

And then you stored procedure would be:

CREATE PROC [dbo].[usp_InsertTableA]
 (
    @myCustomTable udt_MyCustomTable READONLY
 )
 AS
BEGIN
  -- Your code goes in here
END

Is this possible in SQL Server to execute this with the value of the table and send it into a stored procedure?

No, not with the stored procedure you have there. There are ugly hacks that could make it happen, but it's not how you're supposed to do things in T-SQL. Everything you do in SQL Server is supposed to be optimized to work on a set of rows, not a single row / row by row

In practice what this means is, if you have a query like this that produces 100 rows:

select ID, Name from #tempTable

You would pass those 100 rows to your insert procedure and insert them in one operation:

--expanding on sam's advice

--create a type 
CREATE TYPE [dbo].[udt_MyCustomTable] AS TABLE(
    [id] [int] NOT NULL,
    [name] [nvarchar](100) NOT NULL
)


--your insert procedure 
CREATE PROC [dbo].[usp_InsertTableA]
 (
    @myCustomTable udt_MyCustomTable READONLY
 )
 AS
BEGIN
  INSERT INTO TableA(idcolumn, namecolumn)
  SELECT is, name FROM @myCustomTable
END

Now in your main sp that wants to insert 100 rows:

@DECLARE tmpVar udt_MyCustomTable;

--put 100 rows into table variable
INSERT INTO tmpVar(id,name)
select ID, Name from #tempTable

--pass 100 rows in variable to SP to insert all at once
EXECUTE usp_InsertTableA tmpVar
  DECLARE @ID INT, @Name VARCHAR(255)
  SELECT @ID = ID, @Name=Name FROM #tempTable -- assumes one record in the table.
  EXEC dbo.usp_insertdata @id, @Name

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