2012-11-16 118 views
1

一位朋友問,如何在SQL中將表示八進制值的varchar轉換爲整數,因此我在此處放置了一個答案並查看是否有人對其進行了改進。在SQL中將八進制轉換爲十進制

我曾希望能夠作爲查詢的一部分內聯運行的解決方案,而不必在數據庫中創建任何函數(例如,如果您只有權限查詢數據庫,但不能創建任何新函數或存儲過程在裏面)。

或者,我看到.Net Framework ToInt32方法可以輕鬆實現此目的,但似乎需要跳過很多CLR集成環路才能實現此目的。

回答

2

有點令人費解 - 需要2級標量子查詢

設置&查詢

declare @t table (oct varchar(10)); 
insert @t select '7101'; 
insert @t select '6'; 
insert @t select '110111'; 

select *, 
     (select sum(val) 
     from 
      (
      select substring(reverse(t.oct), v.number, 1) * power(8, v.number-1) val 
       from master..spt_values v 
      where v.type='p' and v.number between 1 and len(t.oct) 
      ) x 
     ) intVal 
    from @t t; 

結果

oct  intVal 
---------- ----------- 
7101  3649 
6   6 
110111  36937 
+0

不錯的技術。謝謝! – explunit

2

這裏是我的快速正骯髒的迭代版本:

CREATE FUNCTION dbo.fn_OctalToInt(@OctalVal varchar(50)) RETURNS BIGINT AS 
BEGIN 
    DECLARE @pos tinyint = 0 
    DECLARE @tot bigint = 0 
    WHILE @pos < LEN(@OctalVal) BEGIN 
     set @tot = @tot + cast(SUBSTRING(@OctalVal, len(@OctalVal) - @pos, 1) as tinyint) * power(8,@pos) 
     set @pos = @pos + 1 
    END 
    RETURN @tot 
END 
相關問題