将 table 的结果作为参数插入存储过程

Insert results of a table into stored procedure as parameters

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

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

exp usp_InsertTableA
select ID, Name from #tempTable

在 SQL 服务器中是否可以使用 table 的值执行此操作并将其发送到存储过程中?

  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

您可以对存储过程使用table类型参数。

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

然后你的存储过程将是:

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?

不,不是你那里的存储过程。有丑陋的 hacks 可以让它发生,但这不是你应该如何在 T-SQL 中做事。您在 SQL 服务器中所做的一切都应该经过优化以处理一组行,而不是单行/逐行

实际上这意味着,如果您有一个产生 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