sql - 将表的结果作为参数插入存储过程
问题描述
我有一个将值插入表的存储过程。假设它的名称usp_InsertTableA
带有参数@ID int
和Name varchar(100)
.
我需要从另一个存储过程中多次调用此存储过程。我正在考虑将此存储过程称为如下
exp usp_InsertTableA
select ID, Name from #tempTable
这是否可以在 SQL Server 中使用表的值执行并将其发送到存储过程中?
解决方案
这是否可以在 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
推荐阅读
- ansible - Ansible 在异步模式下复制大文件
- javascript - 如何更改 google Dialogflow Messenger 的样式
- python - 无法托管 python 服务器
- flutter - 颤振垂直ScrollSingleChildView不起作用
- c - 用随机像素填充网格
- laravel - Laravel 7 Passport "参数 2 传递给 Laravel\\Passport\\Guards\\TokenGuard::__construct()
- javascript - 在遍历 Angular 中 subscribe 给出的数据时使用变量
- c# - 如何在方法调用时找到方法参数的类型?
- linux - 如何在从一个存储库 git pull 的同时 git push 到两个存储库
- docker - Docker 容器更新 --memory 没有按预期工作