June 20, 2012 at 10:09 am
I have a table with 1 column containing the following:
SELECT *
FROM TEST
STYLE
HK82382
HK82386
HK84174
HK86190
HK87143
HK87164
How do I build the string @StylesSelected, that looks like this:
'HK82382','HK82386','HK84174','HK86190','HK87143','HK87164'
My goal is to use @StylesSelected as follows using dynamic SQL:
SELECT @WHERE='WHERE ITEMMAST.STYLE IN (' + @StylesSelected + ')'
EXEC @WHERE
The executed statement will be:
WHERE ITEMMAST.STYLE IN ('HK82382','HK82386','HK84174','HK86190','HK87143','HK87164')
June 20, 2012 at 10:27 am
BEGIN TRAN
--Build sample data in TEST table
SELECT col1
INTO TEST
FROM (VALUES('STYLE'),('HK82382'),('HK82386'),
('HK84174'),('HK86190'),('HK87143'),
('HK87164'))a(col1);
--Actual solution starts here
DECLARE @StylesSelected VARCHAR(MAX);
SELECT @StylesSelected = STUFF((SELECT ',' + col1
FROM TEST
FOR XML PATH('')),1,1,'');
PRINT @StylesSelected;
ROLLBACK
PRINT @StylesSelected returns: -
STYLE,HK82382,HK82386,HK84174,HK86190,HK87143,HK87164
June 20, 2012 at 12:02 pm
I don't see any need for dynamic sql here. What about just using IN?
where ITEMMAST.STYLE in (Select STYLE from TEST)
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
June 20, 2012 at 1:03 pm
I knew there had to be a better way other than complicating the script with dynamic sql.
Thank you.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply