将用户定义的表参数传递给动态sql,sp_executesql

roc*_*in' 6 sql parameters 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
Run Code Online (Sandbox Code Playgroud)

它说:必须声明表变量"@IdTable"

我不能让这个工作,并且无法得到coalesce(对于bigints)的解决方法,因为结果将超过8000个字符.

And*_*mar 8

尝试设置@ParamDefs为:

EXEC sp_executesql @str , N'@IdTable ListBigintType readonly', @IdTable = @IDLIST
Run Code Online (Sandbox Code Playgroud)

这是一个完整的工作示例:

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
Run Code Online (Sandbox Code Playgroud)