SQL十進位轉二進位和十六的兩個函數

來源:互聯網
上載者:User

十進位轉二進位和十六的兩個函數
A.調用測試:
Update MySheet1 set 二進位=  dbo.inttobit(十進位)
Update MySheet2 set 十六進位=  dbo.inttohex(十進位)
B.函數內容
--十進位轉二進位函數
CREATE FUNCTION  dbo.inttobit (@number int)
returns varchar(100)
as
BEGIN
DECLARE @i int
DECLARE @j float
DECLARE @m int
DECLARE @OUT1 varCHAR(1)
DECLARE @OUT2 varchar(20)
SET @i=@number
set @out2=' '
WHILE @i>=1
BEGIN
SET @j=@i/2
SET @m=@i%2
SET @i=floor(@j)
SET @OUT1=cast(@m as char(1))
SET @OUT2=@OUT1+@OUT2
END
RETURN @OUT2
END

--十進位轉十六進位函數
CREATE   function dbo.inttohex(@i int)
returns varchar(15) 
begin
--declare @i int
--set @i=11259375
declare @r varchar(10)  
set @r=''
while @i/16>0
begin
set @r=
(case 
when (@i % 16)<=9 then convert(varchar(1),@i % 16)
when (@i % 16)=10 then 'A'
when (@i % 16)=11 then 'B'
when (@i % 16)=12 then 'C'
when (@i % 16)=13 then 'D'
when (@i % 16)=14 then 'E'
when (@i % 16)=15 then 'F'
end)
+@r
--select @r,@i
set @i=@i/16
end
--select @r,@i
if @i>0 
set @r=(case 
when (@i % 16)<=9 then convert(varchar(1),@i % 16)
when (@i % 16)=10 then 'A'
when (@i % 16)=11 then 'B'
when (@i % 16)=12 then 'C'
when (@i % 16)=13 then 'D'
when (@i % 16)=14 then 'E'
when (@i % 16)=15 then 'F'
end)+@r
-- select @r
return @r
end

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.