我有一列
GL_DESCRIPTION
,其中有这样的值
select distinct GL_DESCRIPTION FROM database_actual_pemupukan;
PEMUPUKAN - CPD HIK ROTASI 3 EMDEK - TRANSPORT
PEMUPUKAN - CPD HIK ROTASI 2 EMDEK - UPAH
PEMUPUKAN - CPD HIK ROTASI 2 - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 1 - TRANSPORT
PEMUPUKAN - CPD HIK ROTASI 3 - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 1 - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 2 EMDEK - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 3 EMDEK - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 1 EMDEK - MATERIAL
PEMUPUKAN - CPD HIK ROTASI 1 EMDEK - TRANSPORT
我在 INT 中有一个名为
Rotasi
的新列,它可以在“ROTASI”之后存储任何数字字符的值
所以对于这个要求,我的代码将是这样的:
UPDATE database_actual_pemupukan SET Rotasi = SUBSTRING(GL_DESCRIPTION,
PATINDEX('%[0-9]%', GL_DESCRIPTION), LEN(GL_DESCRIPTION));
它返回这样的错误
消息 245,第 16 级,状态 1,第 1 行 将 varchar 值“1 - MATERIAL”转换为数据类型 int 时转换失败。
我也尝试过这个查询
UPDATE database_actual_pemupukan
SET rotasi =
CASE
WHEN PATINDEX('%[0-9]%', GL_DESCRIPTION) > 0 THEN
CAST(
-- Extract the number starting from the first digit
SUBSTRING(GL_DESCRIPTION,
PATINDEX('%[0-9]%', GL_DESCRIPTION),
CASE
WHEN PATINDEX('%[^0-9]%', GL_DESCRIPTION + 'a') = 0 THEN LEN(GL_DESCRIPTION) - PATINDEX('%[0-9]%', GL_DESCRIPTION) + 1
ELSE PATINDEX('%[^0-9]%', GL_DESCRIPTION + 'a') - PATINDEX('%[0-9]%', GL_DESCRIPTION)
END
) AS INT
)
ELSE NULL -- If no number is found, set rotasi to NULL
END;
它返回这样的错误
消息 537,第 16 级,状态 2,第 1 行 传递给 LEFT 或 SUBSTRING 函数的长度参数无效。 该声明已终止。
我错在哪里?
您的起点是正确的,您只需要有条不紊地完成提取,例如
WITH cte1 AS (
SELECT *
FROM (
VALUES
('PEMUPUKAN - CPD HIK ROTASI 3 EMDEK - TRANSPORT'),
('PEMUPUKAN - CPD HIK ROTASI 2 EMDEK - UPAH'),
('PEMUPUKAN - CPD HIK ROTASI 2 - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 1 - TRANSPORT'),
('PEMUPUKAN - CPD HIK ROTASI 3 - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 1 - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 2 EMDEK - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 3 EMDEK - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 1 EMDEK - MATERIAL'),
('PEMUPUKAN - CPD HIK ROTASI 1 EMDEK - TRANSPORT')
) x (GL_DESCRIPTION)
), cte2 AS (
SELECT
GL_DESCRIPTION
, PATINDEX('%[0-9]%', GL_DESCRIPTION) FirstNumber, LEN(GL_DESCRIPTION) Length
FROM cte1
), cte3 AS (
SELECT *
, CHARINDEX(' ', SUBSTRING(GL_DESCRIPTION, FirstNumber, Length-FirstNumber)) FirstSpace
FROM cte2
)
SELECT
GL_DESCRIPTION
, CONVERT(INT, SUBSTRING(GL_DESCRIPTION, FirstNumber, FirstSpace)) ExtractedNumber
FROM cte3;