Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
SQLServerSpotlight
Yak Posting Veteran
57 Posts |
Posted - 2004-08-24 : 18:48:51
|
I noticed in one of spirits posts the following sql:declare @ColumnList varchar(500)select @ColumnList = COALESCE(@ColumnList + ';', '') + Col1from Table1select @ColumnList Wow! It seems there is a cool way to do string concat(ie: take a field from every row and concat them together with a supplied separator - excellent!)Now how do I do this without a variable?create table #t_test (n int, s sysname)insert into @t_test select 0, 'a'insert into @t_test select 0, 'b'insert into @t_test select 0, 'c'insert into @t_test select 1, 'x'insert into @t_test select 1, 'y'insert into @t_test select 1, 'z'I want to:select n, concat(s,':') from #t_testto get result: 0, 'a:b:c:' 1, 'x:y:z:'I have a complex sql-statement that does this, but it doesn't use COALESCE. So I'm hoping to get a good optimization.Thanks in advance, J |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2004-08-24 : 18:55:16
|
| [code]CREATE FUNCTION udf_Convert_ToCSV(@n int)RETURNS varchar(4000)ASBEGINDECLARE @s varchar(4000)SELECT @s = COALESCE(@s + ':', '') + sFROM t_testWHERE n = @nRETURN (@s)ENDGOcreate table t_test (n int, s sysname)insert into t_test select 0, 'a'insert into t_test select 0, 'b'insert into t_test select 0, 'c'insert into t_test select 1, 'x'insert into t_test select 1, 'y'insert into t_test select 1, 'z'SELECT DISTINCT n, dbo.udf_Convert_ToCSV(n) AS sFROM t_testdrop function udf_Convert_ToCSVdrop table t_test[/code]Tara |
 |
|
|
SQLServerSpotlight
Yak Posting Veteran
57 Posts |
Posted - 2004-08-24 : 19:16:29
|
| That is very nice Tara, unfortuantly I failed to mention we still support sqlserver7(ie: No functions).I know I can do this in a loop and I'll test the speed of doing that,however I was hoping for a magic use of COALESCE that would be 'concat'Thanks anyway, J |
 |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
|
|
|
|
|
|
|