Monday, March 19, 2012

I came across some very cool t-sql to generate a comma delimited list of (char,varchar) column values from selected rows:  (Note: the '' in the code snippets are two single quotes ' ', not a double quote)

DECLARE @MyList VARCHAR(1000)
SELECT @MyList = ISNULL(@MyList,'') + Title + ', ' FROM Titles
SELECT @MyList


For a comma delimited list of integer values, use:

DECLARE @MyList VARCHAR(1000)
SELECT @MyList = ISNULL(@MyList,'') + CAST(Id AS CHAR(5)) + ', ' FROM MyPeople WHERE firstname=''  AND  lastname= ''
SELECT @MyList


I find this very useful for generating a list to be used in a t-sql  WHERE clause, for example:
Let's say the above query generated the result  :   2,4,6,25,66,
1. I copy the string  2,4,6,25,66,
2. Then remove the last comma to get 2,4,6,25,66
3. and paste the edited result into the following example query:
UPDATE MyPeople SET  col_note= 'Bad Data' where Id in (2,4,6,25,66)

To see this code in action, use the following script:

CREATE TABLE Titles(
PKey int NOT NULL,
Title varchar(50) NULL
)

insert Titles ( pkey, title) values (1, 'Doctor')
insert Titles ( pkey, title) values (2, 'Nurse')
insert Titles ( pkey, title) values (3, 'Administrator')
insert Titles ( pkey, title) values (4, 'CMA')

select * from Titles

DECLARE @MyList VARCHAR(1000)
SET @MyList = ''
SELECT @MyList = ISNULL(@MyList,'') + Title + ', ' FROM Titles
SELECT @MyList DECLARE @MyList VARCHAR(1000) SELECT @MyList = ISNULL(@MyList,'') + cast(contacts_PKey as char(5)) + ', ' FROM MedicalPersons where firstname='' and lastname= '' select @MyList