添加两个动态变量并将其存储在INT类型列中

时间:2014-06-28 12:44:17

标签: sql sql-server

我有两个动态变量......

 declare @count nvarchar(max)
 declare @totalCount int
 set @count = ' ( SELECT COUNT(*) FROM '+ @Table +' where [Name] = '''+ CAST(@Name as           nvarchar(max)) +''' ) ' 
 set @totalCount = CAST(CAST(@count as nvarchar(max)) + CAST(@Qty as nvarchar(max)) as INT);

我收到错误

  conversion failed when converting the nvarchar value to datatype int....

然后我需要将@totalCount存储在INT类型的[TotalCount]列中... PLease help

1 个答案:

答案 0 :(得分:1)

变量表名称需要使用动态SQL。下面的示例使用参数化查询输出参数将计算值分配给@totalCount变量。

DECLARE
      @totalCount int
    , @Qty int = 5
    , @Sql nvarchar(MAX)
    , @Table sysname = 'Table'
    , @Name nvarchar(MAX) = N'Name';

SET @Sql = N'SELECT @totalCount = COUNT(*) + @Qty 
        FROM ' + QUOTENAME(@Table) + ' where [Name] = @Name;';

EXEC sp_executesql
      @Sql
    , N'@Name nvarchar(MAX), @Qty int, @totalCount int OUTPUT'
    , @Name = @Name
    , @Qty = @Qty
    , @totalCount = @totalCount OUT;