your code works:
--I added this
DECLARE @str varchar(1000)
declare @sometable table (value varchar(50))
insert into @sometable values ('aaaa|bbbb|cccc|dddd')
insert into @sometable values ('1111|2222|3333|4444')
insert into @sometable values ('xx|yy|zz')
--your code unchanged, other than "dbo.sometable" to "@sometable"
SET @str = ''
SELECT @str = @str +
CASE WHEN SUBSTRING(value,CHARINDEX('|',value)+1,LEN(value)) <> '' THEN
'$' +REPLACE(value,'|',' - ')
ELSE
'$' +ISNULL(REPLACE(value,'|',''),'')
END + ', '
FROM @sometable --<<only changed table name
print @str
OUTPUT:
$aaaa - bbbb - cccc - dddd, $1111 - 2222 - 3333 - 4444, $xx - yy - zz,
I think your concatenation looks good, run this to check your query isn't just wrong:
SELECT value
FROM dbo.sometable
you may have a bad where
or join if you have more details in your actual query.
---- EDIT ----
Also, you can not use ORDER BY
in your query when concatenating this way. If you need to concatenate with an order by
you can use can use something like this:
set nocount on;
declare @YourTable table (RowID int, HeaderValue int, ChildValue varchar(5))
insert into @YourTable VALUES (4,3,'<br>')
insert into @YourTable VALUES (1,1,'CCC')
insert into @YourTable VALUES (3,2,'AAA')
insert into @YourTable VALUES (5,3,'A & Z')
insert into @YourTable VALUES (2,2,'B<&>B')
set nocount off
SELECT
t1.HeaderValue
,STUFF(
(SELECT
', ' + t2.ChildValue
FROM @YourTable t2
WHERE t1.HeaderValue=t2.HeaderValue
ORDER BY t2.ChildValue --<<<<<<<<<<<<ORDER BY
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
) AS ChildValues
FROM @YourTable t1
GROUP BY t1.HeaderValue
OUTPUT:
HeaderValue ChildValues
----------- ---------------
1 CCC
2 AAA, B<&>B
3 <br>, A & Z
(3 row(s) affected)
here is a working example of your code:
DECLARE @str varchar(1000)
declare @sometable table (value varchar(50))
insert into @sometable values ('aaaa|bbbb|cccc|dddd')
insert into @sometable values ('1111|2222|3333|4444')
insert into @sometable values ('xx|yy|zz')
--your code unchanged, other than "dbo.sometable" to "@sometable"
SET @str = ''
SELECT @str = @str + STUFF(
(SELECT ', ' +
CASE WHEN SUBSTRING(value,CHARINDEX('|',value)+1,LEN(value)) <> '' THEN
'$' +REPLACE(value,'|',' - ')
ELSE
'$' +ISNULL(REPLACE(value,'|',''),'')
END
FROM @sometable t2
ORDER BY t2.value --<<<<<<<<<<<<ORDER BY
FOR XML PATH(''), TYPE
).value('.','varchar(max)')
,1,2, ''
)
print @str
OUTPUT:
$1111 - 2222 - 3333 - 4444, $aaaa - bbbb - cccc - dddd, $xx - yy - zz