存储过程计数

时间:2014-09-03 20:56:16

标签: sql-server stored-procedures cursor

我正在尝试打印出动态计数,但它告诉我  @totalCAUUpdates需要一个标量值。有什么想法吗?

declare @totalCAUUpdates as int = 0;
   declare @realTableName as varchar(100) = '[_TEMP_SubscriptionTransactionsForMosoPay09022014]'
   declare @updateSQL as varchar(1000) = 'select @totalCAUUpdates = count(*) from ' + @realTableName + ' where len(accountNumberUpdated) > 0 OR len(accountAccessoryUpdated) > 0;';
   raiserror (@updateSQL, 0,1) with nowait;
   EXEC (@updateSQL);

2 个答案:

答案 0 :(得分:1)

您的批处理正在另一个会话中执行,其中@totalCAUUpdates不可见。 你需要使用sp_ExecuteSQL ..这个proc允许你传入在调用会话中声明的值,并在被调用的会话中使用它们与声明的变量

答案 1 :(得分:1)

DECLARE @totalCAUUpdates INT= 0;
DECLARE @updateSQL NVARCHAR(MAX); 
DECLARE @realTableName SYSNAME;

SET @realTableName  = '_TEMP_SubscriptionTransactionsForMosoPay09022014';

SET @updateSQL = N'select @totalCAUUpdates = count(*) from ' + QUOTENAME(@realTableName) 
              + N' where len(accountNumberUpdated) > 0 OR len(accountAccessoryUpdated) > 0;';

EXECUTE sp_executesql @updateSQL
                    ,N'@totalCAUUpdates INT OUTPUT'
                    ,@totalCAUUpdates OUTPUT