Tuesday, December 1, 2015

Concatenating rows of data into a single row

I wanted to create a report that would feature a hyperlink to AiM daily assignment browse screen that required a "in" operator with comma seperated values. I made a separate data set that looked up all the shop people for a particular shop and then used the following script to concatenated the rows into a single row, separated by the URL encode for a comma so that I could make a dynamic hyperlink to the daily assignment browse. 

Here's the script:
DECLARE @Txt1 VARCHAR(MAX)
DECLARE @shop varchar (20)
SET @Txt1=''
SET @shop='WC03' 
SELECT  @Txt1 = @Txt1 + shop_person +'%2C'
FROM    ae_l_shp_d  
where shop=@shop and date_to is null
SELECT  @shop as shop, LEFT(@Txt1,LEN(@Txt1)-3) AS shop_person

So instead of getting data like this:

 I get data that looks like this:


I used the hyperlink editor to dynamically build my hyperlink with these values.

Similarly, I converted sql datetime to URL date time using this script. 

select convert(varchar, GW_OPENS_DONES.dates, 23) + '%2000%3A00%3A00.0' as url_date
to make values like this:2015-11-11%2000%3A00%3A00.0