I want to assign the result of a SELECT FOR XML EXPLICIT statement to a XML Variable such as
CREATE PROCEDURE BILLING_RESPONSE
AS DECLARE @Data AS XML
SET @Data = (SELECT
1 AS Tag,
NULL AS Parent,
NULL AS 'CallTransactions!1!',
NULL AS 'TCALTRS!2!TRS_DAT_TE!cdata',
NULL AS 'TCALTRS!2!TRS_CRT_DT!Element'
UNION ALL
SELECT
2 AS Tag,
1 AS Parent,
NULL,
TRS_DAT_TE,
TRS_CRT_DT
FROM TCALTRS
WHERE TRS_CRT_DT between CONVERT(date,GETDATE()-1) and CONVERT(date,getdate()) and
TRS_DAT_TE like '%(Submit Response)%'
FOR XML EXPLICIT
)
SELECT @DATA
GO
When i execute this query am getting the following error Msg 1086, Level 15, State 1, Procedure BILLING_RESPONSE, Line 22 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.
The error is not particularly clear, but what it is saying is that you can't use the
FOR XML
clause in the inline subquery because it contains a UNION (a type of set operator)The suggested workaround is to wrap the subquery in something else and call it separately, for example: