I need a query that can merge many columns in just one.
For Example i have these rows for a column:
'JOHNNY WALKER KILIAN JOURNET ANNA FROST'
'JOHNNY CUERVO KILIAN JOURNET ANNA FROST'
'JOHNNY WALKER KILIAN JONES ANNA FROST'
'JOHNNY WALKER KILIAN JOURNET EMELIE FROST'
then I want to merge all the rows into just one:
'JOHNNY CUERVO KILIAN JONES EMELIE FROST'
Is it possible to do this? This is because I´m trying to do a dynamic query, that then conditions are retrieved by from an XML, but i dont know how much conditions I will get from the XML, so I'm trying with a CTE to loop the conditions from the XML and replace the dinamic query. Finally I'm getting many rows with the query and some of the conditions.. so i need to merge the differences and preserve the similarity.
THe XML is:
<ROOT>
<PARAMETROS>
<USU_LOGIN>yleon</USU_LOGIN>
<USU_NOMBREPRIMERO>Yerusha</USU_NOMBREPRIMERO>
<USU_APELLIDOPRIMERO>Leon</USU_APELLIDOPRIMERO>
<USU_EMAIL>yleon@email.com.ve</USU_EMAIL>
<USU_FECHACREACION>20130510</USU_FECHACREACION>
<USU_CODICIONES1 TIPO="MC" MARCADOR="CONDICIONES1">AND USU_ID=1</USU_CODICIONES1>
<USU_CODICIONES2 TIPO="MC" MARCADOR="CONDICIONES2">AND USU_ID=2</USU_CODICIONES2>
<USU_CODICIONES3 TIPO="MC" MARCADOR="CONDICIONES3">AND USU_ID=3</USU_CODICIONES3>
<USU_CODICIONES4 TIPO="MC" MARCADOR="CONDICIONES4">AND USU_ID=4</USU_CODICIONES4>
<USU_CODICIONES5 TIPO="MC" MARCADOR="CONDICIONES5">AND USU_ID=5</USU_CODICIONES5>
<USU_CODICIONES6 TIPO="MC" MARCADOR="CONDICIONES6">AND USU_ID=6</USU_CODICIONES6>
</PARAMETROS>
</ROOT>
AND MY CODE IS:
DECLARE @XML AS XML
DECLARE @QUERY AS VARCHAR(MAX)
--Lectura del XML almacenado en la tabla SESIONESREPORTES
SET @XML = (SELECT TOP 1 SER_PARAMETROS FROM SESIONESREPORTES WHERE REP_ID = 4 AND SER_ID = 9)
SET @QUERY = 'SELECT * FROM USUARIOS WHERE 1=1 CONDICIONES1 CONDICIONES2 CONDICIONES3 CONDICIONES4 CONDICIONES5 CONDICIONES6'
SELECT T.Item.value('data(.)', 'varchar(255)') AS ELEMENTOSMC
, T.Item.value('data(@MARCADOR)', 'varchar(255)') AS MARCADOR
, REPLACE(@QUERY,T.Item.value('data(@MARCADOR)', 'varchar(255)'), T.Item.value('data(.)', 'varchar(255)')) AS QUERY2
, 0 n
FROM @xml.nodes('/ROOT/PARAMETROS/*') AS T(Item)
WHERE T.Item.value('data(@TIPO)', 'varchar(255)')='MC'
here is a better solution, more simple, with minor potential incidents, and faster, was provided by @Alexander Fedorenko, I just adapted for this question:
Dynamic query construccion looping conditions from a xml
Here's a (mostly) XQuery solution:
Produces: