日期:2014-05-18  浏览次数:20628 次

sqlserver 中如何将一个字段的数值进行转换
大家好,我的数库里有一个表lac的字段是lac_hex,里面的数值是十六进制的,另一个表是lac_in,里面的字段lac是十进制的,
这两个表要进行关联,怎么实现lac_hex和lac的关联,也就是十六进制和十进制的转换

------解决方案--------------------
你可以创建存储过程实现该转换
------解决方案--------------------
http://topic.csdn.net/u/20070116/10/0c7d9ec1-acaa-4918-86cd-51516f7f517f.html
------解决方案--------------------
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 @result=@result+(CHARINDEX(SUBSTRING(@s,@i+1,1), '0123456789ABCDEF ')-1)*POWER(16,@i),@i=@i+1 
END 
RETURN @result 
END 
GO 


-- 
select dbo.f_hex_dec( 'A ') 


--res 

10
------解决方案--------------------
SQL code

create Function [dbo].[IntToHex](@IntNum int)
returns varchar(16)
as
begin
  declare @Mods int,@res varchar(16)
  set @res=''
  while @IntNum <> 0 
  begin
    set @Mods =@IntNum % 16
    if @Mods > 9 
      set @res = Char(Ascii('A')+@Mods-10)+@res
    else 
      set @res = Cast(@Mods as varchar(4)) + @res
    set @IntNum = @IntNum/16
  end
  return @res
end

------解决方案--------------------
SQL code

create Function [dbo].[IntToHex](@IntNum int)
returns varchar(16)
as
begin
  declare @Mods int,@res varchar(16)
  set @res=''
  while @IntNum <> 0 
  begin
    set @Mods =@IntNum % 16
    if @Mods > 9 
      set @res = Char(Ascii('A')+@Mods-10)+@res
    else 
      set @res = Cast(@Mods as varchar(4)) + @res
    set @IntNum = @IntNum/16
  end
  return @res
end


go
declare @lac table (lac_hex varchar(2))
insert into @lac
select 'A' union all
select 'AB' union all
select '2B'

declare @lac_in table (lac int)
insert into @lac_in
select 171 union all
select 10 union all
select 67

select * from @lac a full join 
@lac_in b on dbo.[IntToHex](b.lac)=a.lac_hex
/*
lac_hex lac
------- -----------
AB      171
A       10
NULL    67
2B      NULL

(4 row(s) affected)
*/