首页 > 解决方案 > 将表的结果作为参数插入存储过程

问题描述

我有一个将值插入表的存储过程。假设它的名称usp_InsertTableA带有参数@ID intName varchar(100).

我需要从另一个存储过程中多次调用此存储过程。我正在考虑将此存储过程称为如下

exp usp_InsertTableA
select ID, Name from #tempTable

这是否可以在 SQL Server 中使用表的值执行并将其发送到存储过程中?

标签: sqlsql-serversql-server-2017

解决方案


这是否可以在 SQL Server 中使用表的值执行并将其发送到存储过程中?

不,不是您拥有的存储过程。有一些丑陋的黑客可以让它发生,但这不是你应该在 T-SQL 中做事的方式。您在 SQL Server 中所做的一切都应该经过优化以处理一组行,而不是单行/逐行

实际上,这意味着,如果您有这样的查询,它会产生 100 行:

select ID, Name from #tempTable

您可以将这 100 行传递给您的插入过程,并在一次操作中插入它们:

--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

现在在您想要插入 100 行的主 sp 中:

@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

推荐阅读