Question

I'm using this query

select Name, valueType from mytable where ID = 1

and getting this table:

enter image description here

But I need to covert the result set into something like:

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

Do you have any suggestion?

Was it helpful?

Solution

Is this what you are looking for?

--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

NOTE: If you are on at least SQL Server 2017, you can use 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

OTHER TIPS

You can also use COALESCE

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = COALESCE(@SQL + ', ', '') + Col1 + '.' + Col2 
FROM table

PRINT @SQL
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top