Tuesday, 23 December 2014

How to split column value into 3 separate values.


How to split column value into 3 separate values.

    Using simple function you can achieve these

  Declare @column varchar(100) = 'AB12-23PP-tKK%IU'
  Select @column,
              PARSENAME(REPLACE(@column,'-','.'),3)'Second',
              PARSENAME(REPLACE(@column,'-','.'),2)'Third',
              PARSENAME(REPLACE(@column,'-','.'),1)'Fourth'

  If you want to create function

CREATE FUNCTION dbo.splitValue(@string VARCHAR(MAX), @delim CHAR(1))
RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
AS
BEGIN
 WHILE CHARINDEX(@delim,@string) > 0
  BEGIN
   INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
   SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
  END
   INSERT INTO @result (value) VALUES (@string)

RETURN
END
GO

DECLARE @table TABLE (value VARCHAR(20))
INSERT INTO @table VALUES('AB12-23PP-tKK%IU')
INSERT INTO @table VALUES('XYz-PrP-Hind')

SELECT *
  FROM (
SELECT t.*, x.id, x.value as stringValue
  FROM @table t
    CROSS APPLY dbo.splitValue(value,'-') x
       ) s
  PIVOT( max(stringValue) for id in ([1],[2],[3])) pv



No comments:

Post a Comment