admin管理员组文章数量:1332339
I have a table called #table1, larger but similar to the one below. I want to move the results to a single string variable.
ColumnA | ColumnB | ColumnC | ColumnD |
---|---|---|---|
date1 | datavalue1 | identifier1 | description1 |
date2 | datavalue2 | identifier2 | description2 |
I have a table called #table1, larger but similar to the one below. I want to move the results to a single string variable.
ColumnA | ColumnB | ColumnC | ColumnD |
---|---|---|---|
date1 | datavalue1 | identifier1 | description1 |
date2 | datavalue2 | identifier2 | description2 |
I want the table to reference the table as a string variable in a format where columns are separated by an underscore and rows separated by a comma - such as:
@var = 'date1_datavalue1_identifier1_description1,date2_datavalue2_identifier2_description2'
I have done this manually on a smaller scale with the below
select convert(varchar,columnA) + '_' + convert(varchar,ColumnB) + '_' + convert(varchar,columnC) + '_' + convert(varchar,columnD) as comment
from #table1
Is this possible in SQL and is there a way to do this dynamically that isn't restricted by number of table rows?
Share Improve this question edited Nov 20, 2024 at 19:53 Dale K 27.5k15 gold badges58 silver badges83 bronze badges asked Nov 20, 2024 at 19:52 TheDownsideUpCodingTheDownsideUpCoding 111 bronze badge 15 | Show 10 more comments2 Answers
Reset to default 0You can try below code sample.
dbfiddle Link : https://dbfiddle.uk/W-ZfeIlg
DECLARE @var varchar(max)
SELECT @var = STUFF((SELECT ',' + convert(varchar,columnA) + '_' + convert(varchar,ColumnB) + '_'
+ convert(varchar,columnC) + '_' + convert(varchar,columnD)
FROM table1
FOR XML PATH('')), 1, 1, '')
SELECT @var as comment
For SQL Server 2017
be careful with string limit,null values, implicit conversions about string agg function
use string_agg and concat function
sample
DECLARE @comments VARCHAR(MAX) = (
SELECT STRING_AGG(CONCAT_WS('_',ColumnA,ColumnB,ColumnC,ColumnD),',')
FROM TABLE1)
SELECT @comments as comment
本文标签: sqlConvert a multi columnrow table output into a single stringStack Overflow
版权声明:本文标题:sql - Convert a multi columnrow table output into a single string - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742333192a2455103.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
string_agg
? And you must provide a size when you convert tovarchar
else you might truncate your values. – Dale K Commented Nov 20, 2024 at 19:55STRING_AGG
is the solution here, @DaleK ; that is for delimiting rows, not columns. – Thom A Commented Nov 20, 2024 at 20:21concat_ws
– Dale K Commented Nov 20, 2024 at 20:24