I have the script below. It only prints out one value, PLGG not all of them.
Pot
ABC
MPOT
NVPN
PLGG
However when I remove the order by case section then it prints all of the values. Why is that? Is it no possible to use a custom order by here?
declare @pot nvarchar(max) = ''
select @pot = @pot + QUOTENAME(pot) + ','
from myTbl
group by pot
order by case when pot = 'MPot' then '1'
else pot end
print(@pot)
If you're trying to create a delimited list, there are "better" ways. If you're using 2017+, you can use STRING_AGG
:
CREATE TABLE dbo.myTbl (Pot varchar(4));
INSERT INTO dbo.myTbl (Pot)
VALUES('ABC'),
('MPOT'),
('NVPN'),
('PLGG');
GO
DECLARE @Pot nvarchar(MAX)
SET @Pot = (SELECT STRING_AGG(QUOTENAME(Pot), ',') WITHIN GROUP (ORDER BY CASE WHEN Pot = 'MPot' THEN '1' ELSE Pot END) FROM dbo.myTbl);
PRINT @Pot;
If you're on 2016-, then you can use FOR XML PATH
:
DECLARE @Pot nvarchar(MAX);
SET @Pot = STUFF((SELECT ',' + QUOTENAME(Pot)
FROM dbo.myTbl
ORDER BY CASE WHEN Pot = 'MPot' THEN '1' ELSE Pot END
FOR XML PATH(N''), TYPE).value('.', 'nvarchar(MAX)'),1,1,'');
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