There are couple of ways you can created comma delimited strings from a select statement. But am confused as to why the string has to be initialized first in one and not in the other.
Using a Coalesce statement you do not have to initialize the string and the string comes out perfect. If you, inititialize the string to '', you will get a leading comma.
If you don't use a Coalesce statement, and don't initialize it, you will get nothing. If you do initialize it, you will get a leading comma.
Why is that?
Thanks,
Tom
Using a Coalesce statement you do not have to initialize the string and the string comes out perfect. If you, inititialize the string to '', you will get a leading comma.
If you don't use a Coalesce statement, and don't initialize it, you will get nothing. If you do initialize it, you will get a leading comma.
Code:
CREATE TABLE Employees
(
Emp_UniqueID smallint PRIMARY KEY,
Emp_FName varchar(30) NOT NULL,
Emp_LName varchar(30) NOT NULL,
)
INSERT Employees VALUES (1,'Jeff','Bagwell')
INSERT Employees VALUES (2,'Jose','Lima')
INSERT Employees VALUES (3,'Chris','Truby')
INSERT Employees VALUES (4,'Craig','Biggio')
go
DECLARE @EmployeeList varchar(100)
SELECT @EmployeeList = COALESCE(@EmployeeList + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM Employees
SELECT @EmployeeList
GO
-- IF you initialize the @EmployeeList you will get a leading comma
DECLARE @EmployeeList2 varchar(100)
SELECT @EmployeeList2 = ''
SELECT @EmployeeList2 = COALESCE(@EmployeeList2 + ', ', '') +
CAST(Emp_UniqueID AS varchar(5))
FROM Employees
SELECT @EmployeeList2
GO
-- You can do the same thing without Coalesce and must initialize the varchar
-- If you don't, you will get nothing.
DECLARE @EmployeeList3 varchar(100)
SELECT @EmployeeList3 = ''
SELECT @EmployeeList3 = @EmployeeList3 + ', ' + CAST(Emp_UniqueID AS varchar(5))
FROM Employees
SELECT @EmployeeList3
GO
Why is that?
Thanks,
Tom