Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to separate string into different columns?

I've a table with entries like this.

    MachineName
-----------------------

    Ab bb zecos
    a zeng
    zeng
    empty

4 rows in a table.

How can i seperate those 4 rows to get output like.

       M1       M2       M3
-----------------------------------
       Ab       bb      zecos
       a        zeng     NULL
       zeng     NULL     NULL
       NULL     NULL     NULL
like image 227
user614978 Avatar asked Jun 25 '12 07:06

user614978


1 Answers

Instead of using split function there is a function called ParseName which returns the specified part of the object which spilts the string delimated by . Please go through the ParseName link which helped me in writing this query

Declare @Sample Table
(MachineName varchar(max))

Insert into @Sample
values 
('Ab bb zecos'),('a Zeng')


  SELECT 
  Reverse(ParseName(Replace(Reverse(MachineName), ' ', '.'), 1)) As [M1]
 , Reverse(ParseName(Replace(Reverse(MachineName), ' ', '.'), 2)) As [M2]
 , Reverse(ParseName(Replace(Reverse(MachineName), ' ', '.'), 3)) As [M3]

  FROM  (Select MachineName from @Sample
  ) As [x] 
like image 174
praveen Avatar answered Sep 22 '22 01:09

praveen