Sql column separated by comma|sql Header separated by comma| Column Comma Separated String using XML Path Method(Stuff,COALESCE())

Create table syntax:
CREATE TABLE [TransactionHead]
 ([Code] [int] IDENTITY(1,1) NOT NULL,
 [BranchCode] [int] NULL,
 [TransactionHeadName] [varchar](100) NULL,
 [LookUp] [varchar](100) NULL,
 [GroupHeadCode] [int] NULL,
) 
Insert Records.
INSERT INTO TransactionHead([BranchCode],[TransactionHeadName],[LookUp],[GroupHeadCode])
VALUES ('1','Cash','Cash in hand','10');
INSERT INTO TransactionHead([BranchCode],[TransactionHeadName],[LookUp],[GroupHeadCode])
VALUES ('1','Trade','Trade','5');
INSERT INTO TransactionHead([BranchCode],[TransactionHeadName],[LookUp],[GroupHeadCode])
VALUES ('1','Expenses','Expenses','5');
INSERT INTO TransactionHead([BranchCode],[TransactionHeadName],[LookUp],[GroupHeadCode])
VALUES ('1','Others','Others','15');
INSERT INTO TransactionHead([BranchCode],[TransactionHeadName],[LookUp],[GroupHeadCode])
VALUES ('1','Discount','Discount','15');
select * from TransactionHead; 
TransactionHead table has Data like:
sql Header separated by comma.
DECLARE @Table nvarchar(max) = 'transactiontable'; 
SELECT REVERSE(STUFF(REVERSE((SELECT name + ','
FROM   sys.columns 
WHERE  object_id = Object_id(@Table)
FOR XML PATH (''))), 1, 1, ';'));
Output Like.
sql Column separated by comma.
Scalar function use the COALESCE() to make comma separated list.
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + transactionheadName
FROM transactionHead
SELECT @listStr
Output like.

Post a Comment

0 Comments