2013-10-10 41 views
0

我有一個帶有下面的金額列表的平面文件,可以請告訴我,我怎麼能把這個金額列表變成兩點十進制值,如1234567.80與{,A,H,E,C,I,F通過使用SQL?通過使用SQL將varchars轉換爲兩點十進制值

12345678{ 
00484326A 
00000210H 
00000185A 
00000077E 
00000833C 
00000255I 
00000077E 
00000039F 
00000088A 
00000000F 
00000000A 
00000100{ 

謝謝你,

+0

現在不能爲你寫,但嘗試SUBSTRING和CASE。 –

+0

我可以做的子字符串,但我必須知道,爲什麼每個值都以特定的charector結束。我想有一個理由要知道。 –

+0

eequalsmcaputo給你的CASE部分。 –

回答

1

嘗試以此爲with this SQLfiddle。不漂亮,但它的工作原理

SELECT 
    CAST(
     CONCAT(SUBSTRING(test_value,1, LENGTH(test_value) -2), 
       '.', 
       SUBSTRING(test_value, LENGTH(test_value) -1, 1)) 
    AS DECIMAL(7,1)) 
FROM TEST 
WHERE SUBSTRING(test_value, LENGTH(test_value)) = 'A' 
|| SUBSTRING(test_value, LENGTH(test_value)) = 'H' 
-- keep adding above line for the rest of the ending characters you want 
1

我寫了這是一個功能,因爲我覺得它更容易比內聯代碼爲:

create function dbo.convert_amount_str (@amount_str varchar(50)) 
returns money 
as 
begin 
declare @char_index int 
declare @amount money 
declare @char varchar(50) 
declare @decimal money 

-- Match the first non-numeric character 
select @char_index = PATINDEX('%[^0-9]%', @amount_str) 

-- Get the numeric characters into a numeric variable 
select @amount = convert(money, SUBSTRING(@amount_str, 0, @char_index)) 

-- Get the non-numeric character (will work for multiple characters) 
select @char = SUBSTRING(@amount_str, @char_index, (len(@amount_str) - @char_index) + 1) 

-- Convert the non-numeric characters into decimal amounts 
select @decimal = case @char 
    when 'A' then .8 -- whatever this should equate to 
    when 'H' then .7 -- whatever this should equate to 
    -- output for remaining characters 
    end 

return @amount + @decimal 
end 

就用這樣的:

select dbo.convert_amount_str('00484326A') 

或者,更可能的是,引用任何包含數字字符串值的列。