我有一个包含LastAnalysisAmount
列(varchar
数据类型)的临时表,其中包含如下值:
LastAnalysisAmount
-------------------
0000000.00
0000114.77-
0000367.78
0290367.45
0090367.26-
此列包含正数和负数。我需要将此LastAnalysisAmount
列值转换为具有正确格式的十进制值,并将其加载到目标表中。
例如,在目标表中,值应为
0.00
-114.77
367.78
290367.45
-90367.26
你能帮我写一个SQL函数来做这个转换吗?
感谢您的帮助和时间。
答案 0 :(得分:1)
您可以这样做以加载目标表
INSERT INTO dest_table (LastAnalysisAmount)
SELECT CAST(CASE WHEN RIGHT(LastAnalysisAmount,1) = '-'
THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
ELSE LTRIM(LastAnalysisAmount)
END AS decimal(10,2))
FROM from_table
答案 1 :(得分:1)
试试这个:这将处理负值情况并将其转换为DECIMAL(8,2)
SELECT CAST(
CASE WHEN CHARINDEX('-',LastAnalysisAmount) > 0
THEN STUFF(LEFT(LastAnalysisAmount,LEN(LastAnalysisAmount)-1),1,0,'-')
ELSE LastAnalysisAmount
END AS DECIMAL(8,2)
) AS LastAnalysisAmount
答案 2 :(得分:0)
您可以使用varchar()
case
sttaement:
select (case when LastAnalysisAmount like '%-'
then '-' + replace(LastAnalysisAmount, '-', '')
else LastAnalysisAmount
end) as LastAnalysisAmount
如果要将数据作为小数发送,可以将其转换为适当的类型。
答案 3 :(得分:0)
您可以将REPLACE()
和TRIM()
与CASE EXPRESSION
:
SELECT CASE WHEN LastAnalysisAmount LIKE '%-'
THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
ELSE LTRIM(LastAnalysisAmount)
END as LastAnalysisAmount
FROM YourTable
将其作为十进制加载到目标表:
INSERT INTO Destination_Table (LastAnalysisAmount)
SELECT CAST(CASE WHEN LastAnalysisAmount LIKE '%-'
THEN '-' + REPLACE(LTRIM(LastAnalysisAmount),'-','')
ELSE LTRIM(LastAnalysisAmount)
END AS decimal(10,2))
FROM YourTable