sp_executesql或不带变量执行

时间:2017-06-28 14:09:31

标签: sql-server tsql variables execute sp-executesql

我想在不使用变量的情况下在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)

1 个答案:

答案 0 :(得分:0)

拿你的代码

sp_executesql N'
select concat(''select * from sys.objects object_id id in ('',
(select object_id from sys.objects where object_id=1 and object_id=''30000000''),
'') order by object_id'')'

并删除一级嵌套(sp_executesql

select concat('select * from sys.objects object_id id in (',
(select object_id from sys.objects where object_id=1 and object_id='30000000'),
') order by object_id')

当然是输出

select * from sys.objects object_id id in () order by object_id

正如你所观察到的那样。

我认为你应该这样做:

sp_executesql @query