【发布时间】:2017-06-28 14:09:30
【问题描述】:
我想在不使用变量的情况下在 sql server 2012 上执行此查询:
DECLARE @query VARCHAR(4000)
set @query= concat('select * from customer where id in (',
(select id from customer where comid=1 and code='30.00.0000'),
') order by code')
execute @query
所以我尝试了这个:
sp_executesql N'
select concat(''select * from customer where id in ('',
(select id from customer where comid=1 and code=''30.00.0000''),
'') order by code'')'
没有任何效果,因为它生成查询而不是返回值。
以上版本被裁剪。这是整个脚本:
DECLARE @query VARCHAR(4000)`
DECLARE @years VARCHAR(2000)`
SELECT @years = STUFF((
SELECT DISTINCT
'],[' + ltrim(str(etos))
FROM
(
select c.code , year(f.ftrdate) as etos , sum((it.outputvalmode-it.inputvalmode)*st.netlinevalue) as katharh
from fintrade f left join itemtrans it on it.ftrid=f.id
left join material m on m.id=it.iteid
left join storetradelines st on it.stlid=st.id
left join customer c on c.id=f.cusid
where m.code like '73.00.901%' and m.comid=1
group by c.code , year(f.ftrdate)
)a
ORDER BY '],[' + ltrim(str(etos))
FOR XML PATH('')), 1, 2, '') + ']'
SET @query =
'SELECT * FROM
(
select c.code , year(f.ftrdate) as etos , sum((it.outputvalmode-it.inputvalmode)*st.netlinevalue) as katharh
from fintrade f left join itemtrans it on it.ftrid=f.id
left join material m on m.id=it.iteid
left join storetradelines st on it.stlid=st.id
left join customer c on c.id=f.cusid
where m.code like ''73.00.901%'' and m.comid=1
group by c.code , year(f.ftrdate)
) AS t
PIVOT (MAX(katharh) FOR etos IN (' + @years + ')) AS pvt'`
print (@query)
execute (@query)
【问题讨论】:
-
这里为什么首先需要使用动态sql呢?从您发布的内容来看,不需要动态 sql。
-
你也不需要子查询。你只需要
select * from customer where comid=1 and code='30.00.0000' order by code -
它只是我脚本的一部分,只是为了得到回答。我的主要脚本也是大型动态的。
-
所以也许你的整个脚本可以改进。你已经问过XY Problem 否则,
sp_executesql N'select * from customer where id in (select id from customer where comid=1 and code=''30.00.0000'')order by code'应该可以工作但没有意义,因为你不需要子查询或 sp_executesql -
伙计们,我很欣赏所有这些关于我如何思考解决问题的方法。但我认为这不是逻辑错误。它是我想要克服的技术限制。如何生成没有变量的可执行脚本!以及主题!
标签: sql-server tsql variables execute sp-executesql