2011-11-03 60 views
5

我需要通過我的「用戶定義的表類型」參數設置爲動態sql,sp_executesql的幫助。傳遞用戶定義的表參數動態sql,sp_executesql的

這裏是我的示例代碼:

DECLARE @str as nvarchar(Max) 
DECLARE @IDLIST AS ListBigintType /* this is my table type, with ItemId column (bigint)*/ 

INSERT INTO @IDLIST 

SELECT DISTINCT bigintid FROM tableWithBigInts WITH(NOLOCK) 


set @str ='select * from SomeTable where ID in (select ItemId from @IdTable) ' 

EXEC sp_executesql @str , @ParamDefs, @IdTable = @IDLIST 

它說:必須聲明表變量「@IdTable」

我不能得到這個工作,並不能得到與聚結的解決方法(對於bigint),因爲結果將超過8000個字符。

回答

7

嘗試設置@ParamDefs到:

EXEC sp_executesql @str , N'@IdTable ListBigintType readonly', @IdTable = @IDLIST 

這裏是一個完整的工作示例:

create type ListBigintType as table (ItemId bigint) 
go 
declare @t as ListBigintType 
insert @t select 6*7 

exec sp_executesql 
    N'select ItemId from @IdTable', 
    N'@IdTable ListBigintType readonly', @t 
+0

對不起,我忘了寫,當我在這裏寫的問題。查詢已經有了。但它給出了同樣的錯誤。 –

+0

增加了一個工作示例。從「select name,sys.databases'中的compatibility_level」檢查數據庫的兼容性級別?對於SQL Server 2005+,它應該設置爲90或更高。 – Andomar

+0

我發佈的示例在我的安裝中運行良好,所以我確信您可以使用'sp_executesql' – Andomar