设置一个带有查询返回值的变量 [英] set a variable with a return value of a query
本文介绍了设置一个带有查询返回值的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的存储过程中有这样的东西,
Hi I have something like this in my store procedure,
SET @SQl = 'Some query' --this query return only a cell the type int
SET @VAR = exec(@SQL) --the varaible @var it's local and the type int
如何获取查询的返回值并设置为变量,有可能吗??或者我在做什么错了???
How can i get the return value of the query and set to the variable, it's possible?? or what I'm doing it's wrong???
感谢您的帮助
推荐答案
如果查询返回标量结果集你需要做的
If the query returns a scalar result set you need to do
DECLARE @VAR INT
DECLARE @Result TABLE
(
C INT
)
DECLARE @SQl NVARCHAR(MAX)
SET @SQl = 'SELECT 1'
INSERT INTO @Result
EXEC(@SQl)
SELECT @VAR = C FROM @Result
使用sp_executesql
和OUTPUT
参数会更好
DECLARE @VAR INT
DECLARE @SQl NVARCHAR(MAX)
SET @SQl = 'SELECT @out = 1'
EXEC sp_executesql @SQl, N'@out int output', @out = @VAR OUTPUT
SELECT @VAR
这篇关于设置一个带有查询返回值的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文