Monday, 26 November 2018

MSSQL - Display multiple results in comma separated field


Watch this example on YouTube




Table

CREATE TABLE [dbo].[Product](
    [ProductID] [int] IDENTITY(1,1) NOT NULL,
    [Name] [varchar](50) NULL,
    [SomeNumber] [int] NULL,
    [test] [bit] NOT NULL,
    [isFinalSale] [bit] NOT NULL,
    [isThisFinalSale] [bit] NOT NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
    [ProductID] ASC,
    [test] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]

Query

Select Stuff((Select ',' + Name From Product
Group by Name
For XML Path(''), Type).value('.', 'varchar(max)'),1,1,'')

No comments:

Post a Comment