We're on SQL Server 2008 and I'm trying to figure out if there's a way to have a stored procedure return my results in 1 CSV field
for example:
SELECT TOP 4 carModels
FROM dbo.Models
would return
Jeep
Honda
Mitsubishi
Ford
I would like this returned in 1 field like so: Jeep,Honda,Mitsubishi,Ford
I know we can do this with an assembly, temp tables, or server side code but would prefer not to go that route. Are there any tips / tricks you could suggest to get the result I'm looking for?
try this:
DECLARE @x varchar(8000)
SELECT TOP 4
@x=ISNULL(@x+', ','')+carModels
FROM dbo.Models
SELECT @x AS carModels
EDIT same answer as above, but here is complete code to test it out...
declare @Models table (RowID int not null primary key identity(1,1), carModels varchar(20))
insert into @Models values ('Jeep')
insert into @Models values ('Honda')
insert into @Models values ('Mitsubishi')
insert into @Models values ('Ford')
insert into @Models values ('Mazda')
DECLARE @x varchar(8000)
SET @x=null
SELECT TOP 4
@x=ISNULL(@x+', ','')+carModels
FROM @Models
SELECT @x AS carModels
output:
carModels
----------------------------------
Jeep, Honda, Mitsubishi, Ford
(1 row(s) affected)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With