2017-06-28 24 views
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) 
+2

为什么你需要摆在首位在这里使用动态SQL?从你发布的动态sql是没有必要的。 –

+0

而且你也不需要子查询。您只需要'select * from客户,其中comid = 1和code = '30.00.0000'订单代码' – scsimon

+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 
当你o时

bserved。

我认为你应该做的:

sp_executesql @query