通过执行命令从另一个存储过程调用一个存储过程
在我的存储过程中,我必须传递一个可能每次都会更改的表和列名称。所以我构建命令并执行它。我想要另一个变量@curr_id 中的输出。第二个存储过程将使用 @curr_id 作为输入来调用此存储过程。
我的问题是填充@curr_id vriable。它返回为零。如果我删除 curr_id 变量然后它就可以工作(参见注释行)
有人可以吗?告诉我 - 如何填充@curr_id并作为输出返回? - 如何从第二个存储过程调用第一个存储过程?
ALTER PROCEDURE [dbo].[sp_astm_getcurrid]
@ColName as nvarchar(250),
@TblName as nvarchar(250),
@curr_id nvarchar(max) OUTPUT
AS
BEGIN
DECLARE @cmd nvarchar(max)
SET @cmd =N'SET '+@curr_id+'= SELECT MAX('+@ColName+') FROM '+@TblName;
--SET @cmd =N'SELECT MAX('+@ColName+') FROM '+@TblName;
EXEC (@cmd)
END
In my stored procedure I have to pass a table and column name which may change everytime. So I build command and execute it. I want the output in another variable @curr_id. This store procedure will be called by second stored procedure by using @curr_id as input.
My problem is populating the @curr_id vriable. It is returned as zero. If I remove the
curr_id variable then it works(see commented line)
Can someone pl. tell me
- how to get @curr_id populated and returned as OUTPUT?
- how to call the first stored proc from a second stored proc?
ALTER PROCEDURE [dbo].[sp_astm_getcurrid]
@ColName as nvarchar(250),
@TblName as nvarchar(250),
@curr_id nvarchar(max) OUTPUT
AS
BEGIN
DECLARE @cmd nvarchar(max)
SET @cmd =N'SET '+@curr_id+'= SELECT MAX('+@ColName+') FROM '+@TblName;
--SET @cmd =N'SELECT MAX('+@ColName+') FROM '+@TblName;
EXEC (@cmd)
END
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于 EXEC 在不同的上下文中运行,因此它不知道您的 @curr_id 变量。相反,您可以将动态 SQL 的输出放入表变量中,然后使用它来设置 @curr_id。
另外,永远不要用 sp_ 启动存储过程名称。
然后,从另一个过程中调用此过程的示例可能如下所示。重要的关键是在调用以及上面过程的声明中使用 OUTPUT 关键字。
Because EXEC runs in a different context, it is not aware of your @curr_id variable. Instead, you can place the output of your dynamic SQL into a table variable, and then use that to set @curr_id.
Also, never start a stored procedure name with sp_.
Then, an example of calling this procedure from within another could be something like this. The important key is to use the OUTPUT keyword here in the call as well as in the declaration of the procedure above.
您可以在 sp_executesqlOUTPUT 参数>:
如果不提一下,我就太失职了,在这种情况下,使用 EXEC(@cmd) 或 sp_executesql(@cmd) 会让您容易受到 SQL 注入 攻击。
我建议在存储过程的开头添加类似以下内容:
You can use the
OUTPUT
parameter in sp_executesql:I would be remiss not to mention that, in this case, using EXEC(@cmd) or sp_executesql(@cmd) leaves you vulnerable to SQL injection attacks.
I recommend adding something like the following to the beginning of the stored procedure: