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 ?

  • Here's an interesting approach using a generic string splitter (DelimitedSplit8K) that can be found here: http://www.sqlservercentral.com/articles/Tally+Table/72993/

    DECLARE @CHARACTERS TABLE (CHARS CHAR(1))

    INSERT INTO @CHARACTERS VALUES

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

    DECLARE @STRINGS TABLE (STRING VARCHAR(500));

    INSERT INTO @STRINGS

    SELECT '2449.555N06704.2855EM0701H071T44.098V11.764L0.372C1';

    ;WITH rCTE AS (

    SELECT STRING, n, ItemNumber, Item

    FROM @STRINGS

    INNER JOIN (

    SELECT n=ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),CHARS

    FROM @CHARACTERS) a ON n=1

    CROSS APPLY dbo.DelimitedSplit8K(STRING, CHARS)

    UNION ALL

    SELECT STRING, b.n+1, c.ItemNumber, c.Item

    FROM rCTE b

    INNER JOIN (

    SELECT n=ROW_NUMBER() OVER (ORDER BY (SELECT NULL)),CHARS

    FROM @CHARACTERS) a ON a.n = b.n + 1

    CROSS APPLY dbo.DelimitedSplit8K(Item, CHARS) c

    WHERE b.ItemNumber <> 1

    )

    SELECT mvoltage=MAX(CASE WHEN n=1 THEN Item ELSE NULL END)

    ,mnorth=MAX(CASE WHEN n=2 THEN Item ELSE NULL END)

    ,meast=MAX(CASE WHEN n=3 THEN Item ELSE NULL END)

    ,mtime=MAX(CASE WHEN n=4 THEN Item ELSE NULL END)

    ,mtemperature=MAX(CASE WHEN n=5 THEN Item ELSE NULL END)

    ,mheight=MAX(CASE WHEN n=6 THEN Item ELSE NULL END)

    ,mcompraser=MAX(CASE WHEN n=7 THEN Item ELSE NULL END)

    ,mluman=MAX(CASE WHEN n=8 THEN Item ELSE NULL END)

    FROM rCTE

    WHERE ItemNumber = 1

    GROUP BY STRING

    Forgive me Jeff... Just having a bit of fun.


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St