I'm trying to print a result in one line instead of multiple lines. I have a query looks like :
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M'
By using the Except query, I have :
lineNumber MachName
1 WinMach2
2 WinMach6
And I would like to have :
WinMach2, WinMach6
So, to print the result in one line, I tried :
select stuff((SELECT DISTINCT ', ' + RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M'
for xml path ('')
), 1, 2, '') as machineName
FROM GROUPS
But, The error is :
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.
It's working if I do :
select stuff((SELECT DISTINCT ', ' + RTRIM(LTRIM(MACHNAME)) FROM MACHS WHERE MACHID <> 0
for xml path ('')), 1, 2, '') as machineName
FROM MACHS
The result is:
WinMach1, WinMach2, WinMach3, WinMach4, WinMach5, WinMach6, WinMach7, WinMach8, WinMach9
I checked this : SQL UNION FOR XML name output column. But, I wasn't able to understand the fix.
And I tried : Using UNION ALL in STUFF / XML Path But, when I did the first part:
SELECT * FROM (SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM MACHS
WHERE MACHID <> 0
EXCEPT
SELECT DISTINCT RTRIM(LTRIM(MACHNAME))
FROM GROUPS
WHERE GROUPS.GROUPTYPE = 'M') AS K
The error is 'No column name was specified for column 1 of 'K'.
Could you help me?
Thanks