1

I have a string in the format . (eg 902.5)
Need to split and collect this into separate variables in sql server 2008.

    DECLARE  
       @Core VARCHAR(10)='902.5',  
       @OrgNumber VARCHAR(6) = NULL,  
       @DeptNumber VARCHAR(2) = NULL

        IF (NULLIF(@Core, '')) IS NOT NULL
        BEGIN
             SELECT @OrgNumber =SUBSTRING(@Core, 1, CHARINDEX('.', @Core) - 1),
                   @DeptNumber =SUBSTRING(@Core, CHARINDEX('.', @Core) + 1, LEN(@Core))

             SELECT @OrgNumber = upper(nullif(ltrim(nullif(rtrim(@OrgNumber ), '')), '')), 
@DeptNumber = nullif(ltrim(nullif(rtrim(@DeptNumber ), '')), '')  
        END

However this does not handle the case where Contains the Org ref only(no dept ref) e.g 902
How do I handle the case gracefully within the same statement?

2
  • Is it always the same format? Commented Sep 7, 2015 at 4:28
  • Yes - it will always be x.y or simply x Commented Sep 7, 2015 at 4:28

2 Answers 2

2

Use PARSENAME function

DECLARE @Core VARCHAR(50)= '902.2'

SELECT Parsename(@Core, CASE WHEN Charindex('.', @Core) > 0 THEN 2 ELSE 1 END) AS OrgNumber,
       Parsename(@Core, CASE WHEN Charindex('.', @Core) > 0 THEN 1 ELSE 2 END) AS DeptNumber 
Sign up to request clarification or add additional context in comments.

1 Comment

PARSENAME works from right to left - and would assign org number to dept ref if the delimiter '.' is missing.
0

Updated your query. Also, notice that your IF (NULLIF(@Core, '')) IS NOT NULL is incorrect.

 DECLARE @Core       VARCHAR(10)='902', 
        @OrgNumber  VARCHAR(6) = NULL, 
        @DeptNumber VARCHAR(2) = NULL 

IF @Core IS NOT NULL 
  BEGIN 
      SELECT @OrgNumber = CASE 
                            WHEN Charindex('.', @Core) > 0 THEN 
                            Substring(@Core, 1, Charindex('.', @Core) 
                                                - 1) 
                            ELSE Substring(@Core, 1, Len(@Core)) 
                          END, 
             @DeptNumber = CASE 
                             WHEN Charindex('.', @Core) > 0 THEN 
                             Substring(@Core, 
                             Charindex('.', @Core) + 1 
                             , Len(@Core)) 
                             ELSE NULL 
                           END 

      SELECT @OrgNumber = Upper(NULLIF(Ltrim(NULLIF(Rtrim(@OrgNumber), '')), '') 
                          ), 
             @DeptNumber = NULLIF(Ltrim(NULLIF(Rtrim(@DeptNumber), '')), '') 
  END 

SELECT @OrgNumber, 
       @DeptNumber 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.