开发者

set a variable with a return value of a query

开发者 https://www.devze.com 2023-03-03 06:33 出处:网络
Hi I have something like this in my store procedure, 开发者_JAVA技巧 SET @SQl = \'Some query\' --this query return only a cell the type int

Hi I have something like this in my store procedure,

开发者_JAVA技巧
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???

Thanks for your help


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

Much better to use sp_executesql and OUTPUT parameters

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 
0

精彩评论

暂无评论...
验证码 换一张
取 消