在字符串为“KG”或“15KG”的列中,我尝试创建一个新列,其中行为“15KG”的位置为 15,行为“KG”的位置为 1,并将其转换为 INT。下面列出的第四列出错了,我不知道为什么。 错误指出:关键字“AS”附近的语法不正确。 我很乐意提供任何建议。显然,我提出的这个场景是整个项目的简化版本,因此我无法为这两种情况做一个简单的 CASE/WHEN 。我尝试过创建一个函数,但我正在使用的程序似乎不尊重它们。
SELECT
CONVERT(NUMERIC(18,3), t2.[Quantity]) AS [Quantity]
,t2.[Unit of Measure Code]
,CONVERT(NUMERIC(18,3), t2.[Quantity (Base)]) AS [Quantity (KG)]
,CAST(CASE WHEN LEFT(SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10),
PATINDEX('%[^0-9.-]%', SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10) + 'X') -1) = 0 THEN 1
ELSE LEFT(SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10),
PATINDEX('%[^0-9.-]%', SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10) + 'X') -1) AS INT) AS [UOMNumWORKING]
FROM [dbo].[{{DatabaseTablePrefix}}$Sales Invoice Header{{DatabaseTableSuffix}}] t1 WITH (NOLOCK)
LEFT JOIN [dbo].[{{DatabaseTablePrefix}}$Sales Invoice Line{{DatabaseTableSuffix}}] t2 WITH (NOLOCK) ON t2.[Document No_] = t1.[No_]
WHERE t2.[Unit of Measure Code] = 'KG' OR t2.[Unit of Measure Code] = '15KG'
您缺少 CASE 语句的 END。更新后的声明如下:
SELECT CONVERT(NUMERIC(18, 3), t2.[Quantity]) AS [Quantity]
,t2.[Unit of Measure Code]
,CONVERT(NUMERIC(18, 3), t2.[Quantity (Base)]) AS [Quantity (KG)]
,CAST(CASE
WHEN LEFT(SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10), PATINDEX('%[^0-9.-]%', SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10) + 'X') - 1) = 0
THEN 1
ELSE LEFT(SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10), PATINDEX('%[^0-9.-]%', SUBSTRING(t2.[Unit of Measure Code], PATINDEX('%[0-9.-]%', t2.[Unit of Measure Code]), 10) + 'X') - 1)
END AS INT) AS [UOMNumWORKING]
FROM [dbo].[{{DatabaseTablePrefix}}$Sales Invoice Header{{DatabaseTableSuffix}}] t1 WITH (NOLOCK)
LEFT JOIN [dbo].[{{DatabaseTablePrefix}}$Sales Invoice Line{{DatabaseTableSuffix}}] t2 WITH (NOLOCK) ON t2.[Document No_] = t1.[No_]
WHERE t2.[Unit of Measure Code] = 'KG'
OR t2.[Unit of Measure Code] = '15KG'