1

I have a select query I want to split the number into 3 values. Please help me to do this.

SELECT Code FROM Source
Code
----------------
21859633525935

I want to split the Code into 3 values and display in 3 columns using SELECT query, i.e.:

First value      Second value     Third value
--------------------------------------------------- 
21               85963            3525935
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
Developer
  • 145
  • 2
  • 2
  • 11
  • Are the numbers fixed in length? First=2, second=5, third=7? – jpw Nov 29 '14 at 12:47
  • I don't get why this is marked duplicate. Splitting a bigint is not the same use case as splitting a character field. Using integer div & mod: `declare @number bigint = 21859633525935, @bigDivisor bigint = 1000000000000; select [First] = @number / @bigDivisor, [Second] = @number % @bigDivisor / 10000000, [Third] = @number % 10000000` – gknicker Sep 01 '22 at 23:41

2 Answers2

1

If the input is a character type (char,varchar) then the various string functions will do this:

SELECT 
    First  = LEFT(code,2), 
    Second = SUBSTRING(code, 3, 5), 
    Third  = SUBSTRING(code, 8, 14) -- or RIGHT(code, 7)
FROM Source

If it's a number type (eg bigint) you have to convert it to a char type first:

SELECT 
    First  = LEFT(CAST(code AS varchar(14)),2), 
    Second = SUBSTRING(CAST(code AS varchar(14)), 3, 5), 
    Third  = SUBSTRING(CAST(code AS varchar(14)), 8, 14)
FROM Source

Or (if it's a number) you could use arithmetic:

SELECT 
    CAST(code / 1000000000000 AS int),
    CAST((code / 1000000000000-CAST(code / 1000000000000 AS int))* 1000000 AS int),
    code % 10000000
FROM Source
jpw
  • 44,361
  • 6
  • 66
  • 86
1

FIRST CHECK DATA TYPE OF CODE AND THEN SPLIT IT

 IF (SELECT data_type 
    FROM Information_Schema.Columns 
    WHERE Table_Name= 'SOURCE'
    AND Column_Name = 'CODE' ) LIKE '%CHAR' --CHECK DATA TYPE OF CODE
BEGIN 
SELECT    substring([Code] ,1,2)   [First value],
          substring([Code] ,3,5)   [Second value],
          substring([Code] ,8,7)   [Third value]
FROM Source
END
ELSE
BEGIN
SELECT    substring(CONVERT(VARCHAR(50),[Code]) ,1,2)   [First value],
          substring(CONVERT(VARCHAR(50),[Code]) ,3,5)   [Second value],
          substring(CONVERT(VARCHAR(50),[Code]) ,8,7)   [Third value]
FROM Source
END

enter image description here

Dudi Konfino
  • 1,126
  • 2
  • 13
  • 24