2017-09-19 1 views
0

Ich versuche, ein XML-Feld in eine SQL-Variable (und dann letztlich in eine Tabellenspalte) zu bekommen, bekomme aber einen Fehler.XML EXPLICIT In Variable

Wenn ich laufen

Declare @tvTable Table (
    id int IDENTITY(1,1) 
    ,someThing varchar(100) 
    ,otherThing varchar(100) 
    ,thisThing varchar(100) 
); 

Insert @tvTable 
Values ('stuff', 'blah', 'foo') 
     ,('thing', 'data', 'bob'); 

Select [Tag]      = 1 
     ,[PARENT]     = NULL 
     ,[things!1!thingId]   = NULL 
     ,[thing!2!thingId!element] = NULL 
     ,[thing!2!thingOne!element] = NULL 
     ,[thing!2!thingTwo!cdata] = NULL 
     ,[thing!2!thingThree!cdata] = NULL 
UNION ALL 
Select 2 
     ,1 
     ,1 
     ,thingId = id 
     ,thingOne = someThing 
     ,thingTwo = otherThing 
     ,thingThree = thisThing 
From @tvTable 
FOR XML EXPLICIT; 

Dann erhalte ich eine richtige Rückkehr

<things> 
    <thing> 
    <thingId>1</thingId> 
    <thingOne>stuff</thingOne> 
    <thingTwo><![CDATA[blah]]></thingTwo> 
    <thingThree><![CDATA[foo]]></thingThree> 
    </thing> 
    <thing> 
    <thingId>2</thingId> 
    <thingOne>thing</thingOne> 
    <thingTwo><![CDATA[data]]></thingTwo> 
    <thingThree><![CDATA[bob]]></thingThree> 
    </thing> 
</things> 

aber sobald ich versuche, dass in eine Variable zu entleeren, erhalte ich eine Fehlermeldung:

The FOR XML clause is invalid in views, inline functions, derived tables, and 
subqueries when they contain a set operator. To work around, wrap the SELECT 
containing a set operator using derived table syntax and apply FOR XML on top 
of it. 

Ich muss XML EXPLICIT verwenden, weil ich bestimmte Felder in richtige CDATA-Tags (erster Versuch eingewickelt) haben muss warf diese einfach als Strings ein und der Anbieter lehnte die Datei ab.

Wie kann ich diese Abfrage so ändern, dass ich die Rückgabe in einer Variablen speichern kann?

Antwort

2

Behandeln Sie das XML auf der Variablenmenge nicht auf der Abfrage selbst.

Declare @tvTable Table (
    id int IDENTITY(1,1) 
    ,someThing varchar(100) 
    ,otherThing varchar(100) 
    ,thisThing varchar(100) 
); 

Insert @tvTable 
Values ('stuff', 'blah', 'foo') 
     ,('thing', 'data', 'bob'); 

declare @someVar nvarchar(max) 

;with cte as(
Select [Tag]      = 1 
     ,[PARENT]     = NULL 
     ,[things!1!thingId]   = NULL 
     ,[thing!2!thingId!element] = NULL 
     ,[thing!2!thingOne!element] = NULL 
     ,[thing!2!thingTwo!cdata] = NULL 
     ,[thing!2!thingThree!cdata] = NULL 
UNION ALL 
Select 2 
     ,1 
     ,1 
     ,thingId = id 
     ,thingOne = someThing 
     ,thingTwo = otherThing 
     ,thingThree = thisThing 
From @tvTable) 


select @someVar = (select * from cte FOR XML EXPLICIT) 

select @someVar 
+1

Das funktionierte perfekt, danke. –

Verwandte Themen