2017-06-28 1 views
1

Id aiment exécuter cette requête sur le serveur SQL 2012 sans variables à l'aide:sp_executesql ou exécuter sans variables

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 

J'ai donc essayé ceci:

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'')' 

sans effet car elle produit la requête à la place de retourner les valeurs.

La version ci-dessus est recadrée. C'est ensemble du script:

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

Pourquoi avez-vous besoin d'utiliser SQL dynamique ici en premier lieu? De ce que vous avez posté le SQL dynamique n'est pas nécessaire. –

+0

et vous n'avez pas besoin de la sous-requête. Vous avez juste besoin de 'select * du client où comid = 1 et code = '30 .00.0000 'commander par code' – scsimon

+0

c'est une partie de mon script seulement pour la raison d'être répondu. Mon script principal est aussi très grand et dynamique. –

Répondre

0

Prendre votre code

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'')' 

et la suppression d'un niveau d'imbrication (le sp_executesql) nous obtenons

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') 

lequel des sorties de cours

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

comme vous bserved.

Je pense que vous devriez faire:

sp_executesql @query