2012-10-10 72 views
3

這是我到目前爲止。我想將查詢結果存儲到一個int變量中,但到目前爲止我得到了空值。執行後,@query和@countrow都是null。任何建議都會很棒。獲取SQL結果到變量中

SET @query = N'select @countrow=count(*) from ' + @tablename 
EXECUTE sp_executesql @query 
+0

如果'@ query'爲空,則'@ tablename'必須爲空 – podiluska

回答

3
DECLARE @i INT, @sql NVARCHAR(512), @tablename varchar(200) = 'tbl' 

SET @sql = N'SELECT @i = COUNT(*) FROM ' + @tablename 

EXEC sp_executesql 
    @query = @sql, 
    @params = N'@i INT OUTPUT', 
    @i = @i OUTPUT 

PRINT @i 

看看SQL Fiddle

2

您需要使用OUTPUT關鍵字,與此類似:

declare @query nvarchar(max) 
declare @countrow int 
declare @tablename varchar(50) 

SET @query = N'select @cnt=count(*) from ' + @tablename 
EXECUTE sp_executesql @query, N'@cnt int OUTPUT', @[email protected] OUTPUT 

select @countrow as countrow -- to get the result