2008年1月29日 星期二

把10進位的數字變成2進位--數字為0-15(16進制轉成2進制用)

ALTER FUNCTION [dbo].[10Transfer2_16] (@Code Int) RETURNS Nvarchar(4)
AS
BEGIN
 DECLARE @Number Int
 DECLARE @I INT
 DECLARE @Two Nvarchar(4)

 SET @Number = @Code
 SET @I = 3 --只除3次
 SET @Two = ''

 WHILE @I <> 0
 BEGIN
  SET @Two = CONVERT(Nvarchar(1), @Number%2) + @Two
  SET @Number = @Number / 2
  SET @I = @I - 1
 END

 IF @I = 0
 BEGIN
  SET @Two = CONVERT(Nvarchar(1), @Number) + @Two
 END

 RETURN LTRIM(RTRIM(@Two))
END

EX:Select dbo.[10Transfer2_16](14)==> 1110

沒有留言: