当前位置: 代码迷 >> Sql Server >> sqlserver 中怎么将一个字段的数值进行转换
  详细解决方案

sqlserver 中怎么将一个字段的数值进行转换

热度:104   发布时间:2016-04-27 14:46:03.0
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 @[email protected]+(CHARINDEX(SUBSTRING(@s,@i+1,1), '0123456789ABCDEF ')-1)*POWER(16,@i),@[email protected]+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)asbegin  declare @Mods int,@res varchar(16)  set @res=''  while @IntNum <> 0   begin    set @Mods [email protected] % 16    if @Mods > 9       set @res = Char(Ascii('A')[email protected])[email protected]    else       set @res = Cast(@Mods as varchar(4)) + @res    set @IntNum = @IntNum/16  end  return @resend
------解决方案--------------------
SQL code
create Function [dbo].[IntToHex](@IntNum int)returns varchar(16)asbegin  declare @Mods int,@res varchar(16)  set @res=''  while @IntNum <> 0   begin    set @Mods [email protected] % 16    if @Mods > 9       set @res = Char(Ascii('A')[email protected])[email protected]    else       set @res = Cast(@Mods as varchar(4)) + @res    set @IntNum = @IntNum/16  end  return @resendgodeclare @lac table (lac_hex varchar(2))insert into @lacselect 'A' union allselect 'AB' union allselect '2B'declare @lac_in table (lac int)insert into @lac_inselect 171 union allselect 10 union allselect 67select * from @lac a full join @lac_in b on dbo.[IntToHex](b.lac)=a.lac_hex/*lac_hex lac------- -----------AB      171A       10NULL    672B      NULL(4 row(s) affected)*/
  相关解决方案