-2

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?

3

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
1

You can also use COALESCE

DECLARE @SQL NVARCHAR(MAX)

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

PRINT @SQL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.