[英]Assign db query value to t-sql variable in dynamic query
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.
动态查询数据库以获取表的计数,将其存储在t-sql变量中,然后根据该变量做出一些决定。
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.
这是一些错误,因为我认为没有一种简单的方法可以将tsql动态查询的结果分配给变量。
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
PRINT 'B'
END
GO
Could someone tell me if there is a simpler way of achieving this using T-SQL ? 有人能告诉我是否有更简单的方法使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.