[英]Dynamic sql using table variable -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子句的字符串。
嘗試在動態語句中移動表變量。
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')
對於解決方案,我必須使用臨時表,然后在我的存儲過程的開始,我使用來自EF的if條件無法從存儲過程中選擇從#temp表 anwser中選擇返回模式 。
我認為這是這種情況的最佳解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.