2012-05-16 28 views
2

我想填充一個具有值的sql變量。它的工作原理時的代碼是這樣的:用選擇語句填充sql變量的作品,但如果我把同樣的語句放在變量中,並嘗試exec()它不起作用

declare @num_records int 
set @num_records = (select distinct count(*) as num_recs 
    from dbo.tbllookup ) 
print @num_records 

例如目的,我做了我的查詢簡單,但它是一個複雜的查詢,我希望把它放在變量,我不得不重複使用查詢其他地方的一部分。所以我嘗試過,但它不起作用。錯誤說「關鍵字'exec'附近的語法不正確。」

declare @num_records int 
declare @sqlstr varchar(200) 
set @sqlstr = '(select distinct count(*) as num_recs 
    from dbo.tbllookup )' 
set @num_records = exec(@sqlstr) 
print @num_records 

我是一個sql查詢新手。所以只是想了解這個概念,並想知道我在這裏做錯了什麼。

謝謝。

回答

1

正如你所發現的,你不能以這種方式填充一個變量。您必須使用sp_executesql來執行此操作。

Declare @Sql nvarchar(max); 
Declare @CountResult int; 

Set @Sql = 'Select @Count = Count(*) From SomeTable'; 
exec sp_executesql @Sql, N'@Count int OUTPUT', @CountResult OUTPUT 

Select @CountResult 

sp_executesql (Transact-SQL)