Home Forums SQL Server 2008 T-SQL (SS2K8) I need to compare and split the string and then save it in the detail_tb but dont know how ? RE: I need to compare and split the string and then save it in the detail_tb but dont know how ?

  • I take it you want to pivot the results so that they are on a single row rather than on several rows.

    DECLARE @CHARACTERS TABLE (CHARS CHAR(1))

    INSERT INTO @CHARACTERS VALUES

    ('N'), ('E'), ('M'), ('H'), ('T'), ('V'), ('L'), ('C' );

    DECLARE @STRING VARCHAR(500);

    SET @STRING= '2449.555N06704.2855EM0701H071T44.098V11.764L0.372C1';

    DECLARE @len int;

    SET @len =LEN(@STRING);

    IF(@len > 0)

    BEGIN

    WITH CTE AS (

    SELECT CHARINDEX(CHARS,@STRING,1) x

    , CAST(REVERSE(LEFT(REVERSE(LEFT(@STRING,

    CHARINDEX(CHARS,@STRING,1)-1)), PATINDEX('%[^0-9,.]%',

    REVERSE(LEFT(@STRING,CHARINDEX(CHARS,@STRING,1)-1)) + 'Z')-1))

    AS VARCHAR(50)) AS RESULT

    FROM @CHARACTERS )

    Select

    pid,MAX([1]) Col1,MAX([2]) Col2,MAX([3]) Col3,MAX([4]) Col4,MAX([5]) Col5,MAX([6]) col6,MAX([7]) col7

    From (

    SELECT 1 pid,ROW_NUMBER() OVER(Order by x) pivotcol,* FROM CTE WHERE LEN(RESULT)>2) s

    pivot(max(RESULT) FOR pivotcol in ([1],[2],[3],[4],[5],[6],[7])) pvt

    group by pid

    END

    This will generate a resultset of : pid,Col1,Col2,Col3,Col4,Col5,col6,col7

    If the string has more than 7 elements then you will need to extend the pivot and outer select to handle it.

    Edit : typos and column list.

    _________________________________________________________________________
    SSC Guide to Posting and Best Practices