gpt4 book ai didi

sql - 使用表变量的动态sql -TSQL

转载 作者:行者123 更新时间:2023-12-01 16:17:35 25 4
gpt4 key购买 nike

我的问题是在 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')

关于sql - 使用表变量的动态sql -TSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16654018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com