动态sql使用表变量-TSQL

时间:2013-05-20 16:30:23

标签: sql sql-server tsql

我的问题是在exec中使用表变量。

declare @sort_col nvarchar(1000) = 'itm_id'
declare @sort_dir nvarchar(4) = 'desc'
declare @filters nvarchar(1000) = ' and itm_name like ''%aa%'''

declare @temp table
(
 itm_id int
)

insert into @temp
EXEC('select itm_id from Tblitm where itm_name not like ''%aa%''')

EXEC('select * from (select (ROW_NUMBER() OVER (ORDER BY '+@sort_col+' '+@sort_dir+')) row_num, * FROM (select itm_id, itm_name, 
dbo.fnItmsHistory(itm_id) itm_history
         from dbo.Tblitm as itm
         left outer join '+@temp+' as temp on itm.itm_id = temp.itm_id
         where itm_id=itm_id and temp.itm_id = null '+@filters+') as x) as tmp')

它说必须声明标量变量“@temp”当临时表声明我尝试使用原始临时表并且它工作,但我在尝试更新我的实体模型时遇到问题。所以有任何解决方案来解决这个问题?

注意: 我必须使用exec,因为在过滤器中我存储了where子句的字符串。

2 个答案:

答案 0 :(得分:1)

尝试在动态语句中移动表变量。

EXEC('
declare @temp table
(
 itm_id int
)
insert into @temp
select itm_id from Tblitm where itm_name not like ''%aa%''
select * from (select (ROW_NUMBER() OVER (ORDER BY '+@sort_col+' '+@sort_dir+')) row_num, * FROM (select itm_id, itm_name, 
dbo.fnItmsHistory(itm_id) itm_history
         from dbo.Tblitm as itm
         left outer join @temp as temp on itm.itm_id = temp.itm_id
         where itm_id=itm_id and temp.itm_id = null '+@filters+') as x) as tmp')

答案 1 :(得分:0)

对于解决方案,我必须使用临时表,然后在我的存储过程的开始,我使用来自EF can't infer return schema from Stored Procedure selecting from a #temp table anwser的if条件。

我认为这是这种情况的最佳解决方案。