Substring with IF or CASE statement

  • Hi,

    I am trying to import into SQL Server 2008 R2 a list of strings as follows:

    =KET+N.207-13-F4001

    =KET+DG014-13-F4011

    =KET+RE002-36-MV009

    I need to split the strings so they are inserted into separate fields. One of the substring statements is:

    'SUBSTRING(xlCode; 15; 2) [if the second position is a number, and]

    'SUBSTRING(xlCode; 15; 1) [if the second position is anything else]

    AS GroupNo

    My experience with T-SQL is just not enough to figure this one out. Can you tell me how the statement should be set up?

    Thanks in advance for any help.

    Maarten

  • First, welcome to SSC. To save you some grief - in the future I would suggest posting some DDL so that we can better understand exactly what you are trying to do. See the link at the bottom for more details.

    You can go to this article[/url] for a copy of the PatternSplit function I am using (and a great read).

    Because I am not sure exacly how you want to split your strings up I will give you a couple ideas to get started; see my comments in the code for more details....

    IF OBJECT_ID('tempdb..#strings') IS NOT NULL DROP TABLE #strings;

    CREATE TABLE #strings (string_id int primary key, string varchar(20));

    INSERT INTO #strings

    SELECT 1, 'KET+N.207-13-F4001' UNION ALL SELECT 2,'KET+DG014-13-F4011' UNION ALL SELECT 3,'KET+RE002-36-MV009';

    SELECT string_id, item

    FROM #strings s

    CROSS APPLY dbo.PatternSplitCM(string,'%-%')

    WHERE Matched=0

    GO

    --Lets say we want to split by '-' & '+'

    SELECT string_id, item

    FROM #strings

    CROSS APPLY dbo.PatternSplitCM(string,'%[+-]%')

    WHERE Matched=0

    --Lets say we want to split by '-' & '+' & '.'

    SELECT string_id, item

    FROM #strings

    CROSS APPLY dbo.PatternSplitCM(string,'%[+-.]%')

    WHERE Matched=0

    http://www.sqlservercentral.com/articles/Best+Practices/61537/ [/url]

    Edit: accidently clicked post before finishing comment ...

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001

  • Thanks for your reply, Alan.B.

    I posted the same topic under the forum 'SQL Server 2008 - General' and got the answer I was looking for.

    Here's the topic link:

    http://www.sqlservercentral.com/Forums/Topic1432866-391-1.aspx?Update=1

    Thanks for your input.

    Maarten

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply