2011-07-15 109 views
0

我想創建一個將字符串轉換爲bigint的函數。如果轉換不可行,該函數應該返回null。我希望函數的正常表現(例如「10000」)和尾數,指數表示工作(「1E1 + 10」),這是我至今寫:convert varchar to bigint function

ALTER FUNCTION [dbo].[udf_get_bigint]  
( 
@character varchar(100) 
) 
RETURNS bigint 

AS 
BEGIN 

    if ISNUMERIC(@character)=0 return null 
    if LEN(ltrim(rtrim(@character)))>25 return null 
    declare @nr numeric(25,4) 
    if charindex('e',lower(@character))>0 
    begin 
     declare @real real 

     **set @nr=CONVERT(real,@character)** 
     if @nr not between convert(numeric(25),-9223372036854775808) and 
       convert(numeric(25),9223372036854775807) 
       return null 
     set @real = convert(real, @nr) 
     return convert(bigint,convert(numeric(25),@real)) 

    end 
    else 
     set @nr=CONVERT(numeric(25,4),@character) 
     if @nr between convert(numeric(25),-9223372036854775808) and 
      convert(numeric(25),9223372036854775807) return convert(bigint,@nr) 
       return null 
END 

目前看來唯一的問題時,我需要處理尾數指數表示的溢出。粗體轉換在溢出的情況下下降;但我想要它做的是返回null。 如何在轉換上放置一些先決條件,使其不再掉落。

呼叫例如:select dbo.udf_get_bigint( '3e0210') 輸出:算術溢出錯誤將表達式轉換爲數據類型真實。

回答

3

使用float而不是實數。它可能會與變量名,但它使腳本工作

declare @real float 

的那部分該代碼將驗證

select CONVERT(float,'3e0210') 
+0

也可以做'CAST(「3e0210」作爲浮動)' – Manatherin