Pages

Wednesday, October 14, 2015

Sql things -- create comma separated list of values of a column in ms sql

1. To convert integer column values to varchar in ms sql


1. SELECT CONVERT(varchar(10), PType_ID) FROM PType

2. create comma separated list of values of a column in ms sql 

Declare @Str varchar(max)
select @Str = coalesce (@Str +',' ,'') + convert(varchar(10) , PriceType_ID )
from PriceType with (NOLOCK)
where PriceTypeCode in ('01', '02', '03', '04')

select @lStr as val

note: here PriceType_ID  is a integer column so i need to convert it to varchar.
in case if this column is already varchar then you do not need to use convert function. 

2 comments:

  1. in case if you will be using this code in a stored proc and you will be including this generated list in your dynamic query for a integer column.

    you will get problem with data conversion with this list. this below post will help you. I found when i got same problem.

    http://stackoverflow.com/questions/16663789/converting-string-list-into-int-list-in-sql

    ReplyDelete
  2. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    ReplyDelete