Msg 1086, Level 15, State 1, Line 20 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.
I get this error when i run this:
SELECT
STUFF((
SELECT 1
UNION ALL
SELECT 2
FOR XML PATH('')
),1,0,'') [COLUMN]
works fine when i run this (without Union ALL)
SELECT
STUFF((
SELECT 1
FOR XML PATH('')
),1,0,'') [COLUMN]
Any suggestions why UNION ALL Doesn't work, or how to get it to work inside the STUFF()
?
We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.
A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.
Using the Where Clause With the UNION Operator We can use the WHERE clause in either one or both of the SELECT statements to filter out the rows being combined. We can also use the WHERE clause in only one of the SELECT statements in the UNION.
Conclusion. Combining several tables to one large table is possible in all 3 ways. As we have seen, the behavior of UNION in SQL Server and UNION in DAX within Power BI is very similar.
There's a simple workaround for that, you should wrap your union query(or any derived table for that matter) with another select. Do this and then continue the syntax normally:
select * from
(
SELECT 1 as I
UNION ALL
SELECT 2 as J
) as K
Something like this is what you're searching for:
SELECT STUFF((
select * from(
SELECT * from dbo.Table1 as I
UNION ALL
SELECT * from dbo.Table2 as j
) as k
FOR XML PATH('')
),1,0,'')
I checked and it works flawlessly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With