gpt4 book ai didi

sql-server - 使用 sp_executesql 执行带有参数的存储过程

转载 作者:行者123 更新时间:2023-12-02 22:45:59 31 4
gpt4 key购买 nike

我有一个带有参数的简单存储过程

CREATE Procedure GetSupplierForTesting
(@SupplierId INT)
AS
SELECT SuppLabel
FROM Supplier
WHERE Supplier.SupplierId = @SupplierId

我可以在另一个存储过程中使用 exec 命令调用它,如下所示

exec GetSupplierForTesting @SupplierId = 10

我发现一篇文章解释了 sp_executesql 如何比 exec 更快。我的问题是我不知道如何使用 sp_executesql 调用具有参数的存储过程。我已经尝试过这段代码

DECLARE @SupplierId INT = 10;
EXEC sp_executesql N'GetSupplierForTesting', N'@SupplierId INT', @SupplierId

但我收到错误:

Procedure or function 'GetSupplierForTesting' expects parameter '@SupplierId', which was not supplied

最佳答案

您需要的语法是

DECLARE @SupplierId INT = 10;

EXEC sys.sp_executesql N'GetSupplierForTesting @SupplierId=@SupplierId',
N'@SupplierId INT',
@SupplierId=@SupplierId

但是不要这样做。这是完全没有意义的。使用 sp_executesql 基本上包装相同的 exec 语句并在不同的范围内执行它,不会带来神奇的性能提升。

只需使用

exec dbo.GetSupplierForTesting @SupplierId = 10

关于sql-server - 使用 sp_executesql 执行带有参数的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38594363/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com