天天看点

SQL实现16进制到10进制的转换

SQL 实现对 16进制 到10进制的转换

CREATE FUNCTION dbo. f_hex_dec(@s varchar( 16))
RETURNS bigint
AS
BEGIN
  DECLARE @i int ,@result bigint
  SELECT @i=0 ,@result= 0,@s =RTRIM( LTRIM(UPPER (REVERSE( @s))))
  WHILE @i<LEN (@s)
  BEGIN
    IF SUBSTRING (@s, @i+1 ,1) not between '0' and '9' and SUBSTRING(@s ,@i+ 1,1 ) not between 'A' and 'F'
    BEGIN
      SELECT @result =0
      break
    END
    SELECT @[email protected] +(CHARINDEX( SUBSTRING(@s ,@i+ 1,1 ),'0123456789ABCDEF')- 1)*POWER (16, @i),@i [email protected]+ 1
  END
  RETURN @result
END
GO

select distinct (dbo. f_hex_dec(substring (ExETCTermCode, 8,5 ))) as ExETCTermCode , ExRoadID,ExStationID ,ExLaneID from tb_LaneExList201406 where ExETCTermCode <>'0' order by ExRoadID ,ExStationID, ExLaneID
           

函数解释: RTRIM 、LTRIM 去除字符串中的左右空白; REVERSE 翻转字符串;CHARINDEX(S1,S2,index)寻找并返回S1在S2中的位置,index 为开始寻找位置,不填,负数或0均默认从S2开头位置寻找



sql