Oops, our query failed. That was unexpected. What happened?
If you carefully read the error message, it will tell you that the types in the anchor and the recursive parts of our query do not match.
The data type for
SELECT
N''
is the data type for column X, i.e. Unicode String Literal.
The data type for
SELECT
X + W
is NVARCHAR of certain length. Unicode String Literal and NVARCHAR types do not match. The UNION ALL operator expects the types of corresponding columns to match; when they don't, the query fails.
What can we do about it? We have to explicitly cast the value N'' to match the type of the other expression, like this:
SELECT
CAST(N'' AS NVARCHAR(MAX))
The MAX argument makes sure that the type will be correct, because it forces the concatenation operator to return an NVARCHAR(MAX) type.
Unfortunately, there are no simple rules explaining what data type you must cast a column to get your query right.