Sql-Server

如何將多行結果集轉換為逗號分隔的單行文本

  • September 13, 2018

我正在使用這個查詢

select Name, valueType from mytable where ID = 1

並得到這張表:

在此處輸入圖像描述

但我需要將結果集轉換為:

'idGasto int, noTicket string, fechaFact string, ..., etc.'

你有什麼建議嗎?

這是你想要的?

--demo setup
Declare @Table table (Name varchar(100), ValueType varchar(100))
DECLARE @ConcatString varchar(100)

insert into @Table values
('idGasto','int'), 
('noTicket','String'), 
('fechaFact','String'), 
('fecha','String'), 
('concepto','String')

--The actual query
SELECT @ConcatString = isnull(@ConcatString + ',', '') + Name + ' ' + ValueType
from @Table

print @ConcatString

idGasto int,noTicket String,fechaFact String,fecha String,concepto String

注意:如果您至少使用 SQL Server 2017,則可以使用STRING_AGG

Declare @Table table (Name varchar(100), ValueType varchar(100))
DECLARE @ConcatString varchar(100)

insert into @Table values
('idGasto','int'), 
('noTicket','String'), 
('fechaFact','String'), 
('fecha','String'), 
('concepto','String')

--If you're on at least SQL Server 2017, you can use STRING_AGG
select @ConcatString = STRING_AGG(Name + ' ' + ValueType, ',') 
from @table

print @ConcatString

idGasto int,noTicket String,fechaFact String,fecha String,concepto String

引用自:https://dba.stackexchange.com/questions/217428