开发者

Assign db query value to t-sql variable in dynamic query

开发者 https://www.devze.com 2023-04-09 01:53 出处:网络
I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that.

I have this requirement to be implemented in a stored procedure. Dynamically query the database to get the count of a table, store it in a t-sql variable and then take some decisions based on that.

This is the stored procedure that i am working on . This is throwing some errors as i don't think there is a simple way of assigning the result of a tsql dynamic query to a variable.

CREATE PROCEDURE test
AS
BEGIN
 DECLARE @sql VARCHAR(255)
 DECLARE @cnt int
 SET @sql = 'SELECT COUNT(1) FROM myTable'
 SET @cnt = EXEC(@sql)
 IF (@cnt > 0)
     PRINT 'A'
 ELSE
     PRIN开发者_StackOverflowT 'B'
END
GO

Could someone tell me if there is a simpler way of achieving this using T-SQL ?

Thanks.


alternative:

declare @tablename varchar(512) = 'sometable'
declare @sql nvarchar(512) = 'set @count = (select count(*) from ' + @tablename + ')'
declare @count int

execute sp_executesql @sql, N'@count int output', @count=@count output

select case when @count > 0 then 'A' else 'B' end 


Try this:

 SET @sql = 'SELECT @cnt = COUNT(1) FROM myTable'
 EXEC(@sql)
0

精彩评论

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

关注公众号