2017-02-09 157 views
0

我有這個疑問轉換XML輸出爲varchar

select 
    ',' + CONVERT(VARCHAR,FileID) 
from 
    [RETRY_INPUT_JSON] A 
inner join 
    RETRY_JSON_STATUS B on JsonStatus = StatusID 
where 
    RetryStatus = 'FAILED'   

Union 

select 
    ',' + CONVERT(VARCHAR,FileID) 
from 
    [RETRY_INPUT_JSON] A 
inner join 
    RETRY_JSON_STATUS B on SendESBStatus = StatusID 
where 
    RetryStatus In ('FAILED', 'Success')    
order by 
    ',' + CONVERT(VARCHAR,FileID) 
FOR XML PATH('') 

這將返回的輸出:

enter image description here

我想將其轉換爲varchar

對於我試過:

DECLARE @FILEID AS VARCHAR(MAX) 

     SET @FILEID =(SELECT STUFF 
         (
          (
select ',' + CONVERT(VARCHAR,FileID) from [RETRY_INPUT_JSON] A inner join RETRY_JSON_STATUS B 
     on JsonStatus=StatusID 
     where RetryStatus='FAILED'   
     Union 
     select ',' + CONVERT(VARCHAR,FileID) from [RETRY_INPUT_JSON] A inner join RETRY_JSON_STATUS B 
     on SendESBStatus=StatusID 
     where RetryStatus In ('FAILED','Success')   
     ORDER BY ',' + CONVERT(VARCHAR,FileID) FOR XML PATH('') 
    ), 
          1, 1, '' 
         )) 

print @FILEID 

但我得到一個錯誤:

消息1086,級別15,狀態1,行18
FOR XML子句是在視圖中無效,內聯函數,派生表和子查詢,當它們包含set操作符時。要解決此問題,請使用派生表語法來包裝包含set操作符的SELECT,然後在其上應用FOR XML。

回答

1

選中此項。

 DECLARE @FILEID AS VARCHAR(MAX) 
     DECLARE @xml_var XML 

     SET @xml_var = (select ',' + CONVERT(VARCHAR,A) 
          from 
           (

             select 
             CONVERT(VARCHAR,FileID) A 
             from 
             [RETRY_INPUT_JSON] A 
             inner join 
             RETRY_JSON_STATUS B on JsonStatus = StatusID 
             where 
             RetryStatus = 'FAILED'  

           Union 

             select 
             CONVERT(VARCHAR,FileID) A 
             from 
             [RETRY_INPUT_JSON] A 
             inner join 
             RETRY_JSON_STATUS B on SendESBStatus = StatusID 
             where 
             RetryStatus In ('FAILED', 'Success')    


           )A 
           order by A 
           FOR XML PATH('') 
         ) 

     select @FILEID = CONVERT(VARCHAR(MAX), @xml_var) 
     SELECT @FILEID 
     pRINT @FILEID