2014-06-28 22 views
0

我兩個動態變量...增加兩個動態變量,並將其存儲在INT型列

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幫助

回答

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; 
相關問題