在SQL中将脚和英寸从varchar转换为float

时间:2017-01-26 18:46:37

标签: sql-server

我想使用select语句将长度以英尺和英寸为单位从varchar转换为float。

示例:

8' - > 8

8' 11" - > 8.9167

9' 5" - > 9.4167

3' 10.5" - > 3.875

此刻我正在使用此功能。但它会混淆一些值,如0' 0.5",NULL,空白等。先谢谢。

  CREATE  FUNCTION [dbo].[convert_detail_code]
(
    @detail_code varchar(64)
)
RETURNS float
AS BEGIN
    declare @length float
    declare @temp int
    declare @stringlen int
    declare @inches varchar(64)
    declare @fraction float

    set @length = 0

    if (@detail_code = '') or (@detail_code is null) begin
        set @length = 0
    end
    else begin
        set @temp = CharIndex('''',@detail_code)

        if @temp > 0 begin
            set @length = Convert(float,(Left(@detail_code,@temp-1)))
        end

        set @temp = CharIndex ('"',@detail_code)

        if @temp > 0 begin
            set @stringlen = @temp - CharIndex ('''',@detail_code) - 1
            set @inches = LTRIM(RTRIM(SubString (@detail_code, @temp - @stringlen, @stringlen)))
            set @temp = CharIndex (' ',@inches)
            if @temp > 0
            BEGIN
                set @length = @length + Convert (float, SubString(@inches,1,@temp)) / 12
                set @inches = SubString(@inches,@temp+1,LEN(@inches)-@temp)
                set @fraction = (Convert(float,SubString(@inches,1,CharIndex('/',@inches)-1)) / Convert(float,SubString(@inches,CharIndex('/',@inches)+1,Len(@inches)-CharIndex('/',@inches))))/Cast(12 as float)
                set @length = @length + @fraction
            END
            else
            BEGIN
                if charIndex('/',@inches) > 0
                begin
                    set @fraction = (Convert(float,SubString(@inches,1,CharIndex('/',@inches)-1)) / Convert(float,SubString(@inches,CharIndex('/',@inches)+1,Len(@inches)-CharIndex('/',@inches))))/Cast(12 as float)
                    set @length = @length + @fraction
                end
                else
                begin
                    set @length = @length + Convert (float, @inches) / 12.0
                end
            END
        end
    end

    return @length
end

GO

0 个答案:

没有答案