我有一个选择查询我想将数字拆分为3个值。请帮我这样做。
SELECT Code FROM Source
Code
----------------
21859633525935
我想将Code
拆分为3个值,并使用SELECT
查询显示在3列中,即:
First value Second value Third value
---------------------------------------------------
21 85963 3525935
答案 0 :(得分:1)
如果输入是字符类型(char,varchar),那么各种字符串函数将执行此操作:
SELECT
First = LEFT(code,2),
Second = SUBSTRING(code, 3, 5),
Third = SUBSTRING(code, 8, 14) -- or RIGHT(code, 7)
FROM Source
如果是数字类型(例如bigint),则必须先将其转换为char类型:
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
或者(如果是数字)你可以使用算术:
SELECT
CAST(code / 1000000000000 AS int),
CAST((code / 1000000000000-CAST(code / 1000000000000 AS int))* 1000000 AS int),
code % 10000000
FROM Source
答案 1 :(得分:1)
首先检查数据类型的代码然后将其拆分
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