1
我还想不使用变量来执行的SQL Server 2012在此查询:sp_executesql的或执行不变量
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客户,其中comid = 1和code = '30.00.0000'订单代码' – scsimon
它的一部分我的脚本只是为了被回答。我的主要脚本也是大而有活力的方式。 –