locked
Converting columns to rows. RRS feed

  • Question

  • Hi,

    I have values something like this

    SELECT 64291,64316,64529,64554,64612,64653,64671

    and i want to convert them to

    64291

    64316

    64529

    64554

    64612

    64653

    64671

    i.e. i want to convert columns to rows. i dont want to use union as i can have 1000's of values in select list. is there any other way to do it.

    Thanks

    Thursday, June 14, 2012 11:46 AM

Answers

  • Try this:

    declare @aa table
    (cola varchar(max))
    insert into @aa 
    select '64291,64316,64529,64554,64612,64653,64671'
    
    ;WITH cteSplit(CSVVal)
    AS (
    	SELECT 
    		CAST('<r><i>' + REPLACE(cola, ',', '</i><i>') + '</i></r>' AS XML) AS CSVVal
    	FROM @aa
    )
    SELECT
    	r.i.value('.', 'VARCHAR(50)') AS [ColA]
    FROM    cteSplit AS s
    CROSS APPLY CSVVal.nodes('r/i') AS r(i)


    Krishnakumar S

    • Proposed as answer by Sali SQL Thursday, June 14, 2012 12:32 PM
    • Marked as answer by Iric Wen Thursday, June 21, 2012 8:32 AM
    Thursday, June 14, 2012 12:12 PM

All replies

  • Hi,

    Do you have a single column having all the values or having mutiple columns with each column  having single value?

    If you have a single column with all the values  then try this:

    declare @aa table
    (cola varchar(max))
    insert into @aa 
    select '64291,64316,64529,64554,64612,64653,64671'
    
    declare @temp varchar(max)
    set @temp=(select cola from @aa)
    declare @index int
    declare @text varchar(max)
    declare @Temptable Table (cola varchar(max)) 
    
    
    while LEN(@temp)>2
    BEgin
    SET @index = CHARINDEX(',', @temp)
    
    IF (@index = 0) AND (LEN(@temp) > 2)
              BEGIN  
                Insert  into @Temptable(cola)(select @temp)
                BREAK 
            END 
    
    
    
    set @text=SUBSTRING (@temp,0,@index)
    
    set @temp=REPLACE(@temp,@text+',','')
    insert  into @Temptable(cola)
    (select @text)
    
    END
    
    
    select * from @Temptable

    Thanks,

    Saikat

    • Proposed as answer by Saikat_1983 Monday, June 18, 2012 10:10 AM
    Thursday, June 14, 2012 12:03 PM
  • Try this:

    declare @aa table
    (cola varchar(max))
    insert into @aa 
    select '64291,64316,64529,64554,64612,64653,64671'
    
    ;WITH cteSplit(CSVVal)
    AS (
    	SELECT 
    		CAST('<r><i>' + REPLACE(cola, ',', '</i><i>') + '</i></r>' AS XML) AS CSVVal
    	FROM @aa
    )
    SELECT
    	r.i.value('.', 'VARCHAR(50)') AS [ColA]
    FROM    cteSplit AS s
    CROSS APPLY CSVVal.nodes('r/i') AS r(i)


    Krishnakumar S

    • Proposed as answer by Sali SQL Thursday, June 14, 2012 12:32 PM
    • Marked as answer by Iric Wen Thursday, June 21, 2012 8:32 AM
    Thursday, June 14, 2012 12:12 PM