Convert Hexadecimal to INT and vice versa

2019-09-10 13:08发布

问题:

I will be creating a sequential Serial Number made from Hexadecimal values

With this Format:

XX-XX-XX-YYYY
Which XX-XX-XX is default value
And YYYY is the incrementing hexa decimal value

Now to create the serial number based on hex value I need Add 6 to the last generated hex value

MIN: 2D41 + 6 = 2D47    
     2D47 + 6 ... and so on
MAX: 4100   generation of serial will stop when I meet the MAX value.

I already created it in c# but I need to do it on SQL

int num1 = int.Parse("2D41", NumberStyles.HexNumber); //Convert hex to int
int result = num1 + 6; //Add + 6 for increment
string myHex = result.ToString("X");  //Convert result to hex
MessageBox.Show(myHex);  // result 2D47

How can this be done in T-SQL?

回答1:

Hope this helps you

declare @seed varchar(max) = '2D41';
declare @limit varchar(max) = '4100';

select convert(int, convert(varbinary(max), '0x'+@seed,1)),
       convert(int, convert(varbinary(max), '0x'+@limit,1));

;with seedlimit(seed, limit) as (
    select convert(int, convert(varbinary(max), '0x'+@seed,1)),
           convert(int, convert(varbinary(max), '0x'+@limit,1))
)
select SerialNumber = 'XX-XX-XX-' + right(convert(varchar(10),cast(s.seed + 6 * v.number as varbinary(max)),1),4)
from seedlimit s
join master.dbo.spt_values v on type='p'
where s.seed + 6 * v.number <= s.limit;

The basic ingredients are in there for you to create a view/procedure/function out of the answer,

Output:

SerialNumber
-------------
XX-XX-XX-2D41
XX-XX-XX-2D47
...
XX-XX-XX-40F7
XX-XX-XX-40FD


回答2:

DECLARE @x VARBINARY(8) = 0x00002D41;
SELECT CONVERT(VARBINARY(8), CONVERT(INT, @x) + 6);

In order to handle the output as a string:

DECLARE @x VARBINARY(8) = 0x00002D41;
SELECT CONVERT(CHAR(10), CONVERT(VARBINARY(8), CONVERT(INT, @x) + 6), 1);


回答3:

If you already have it in C#, leave it there and simply convert your code to a SQL CLR function.

For a simple example see:

http://blog.sqlauthority.com/2008/10/19/sql-server-introduction-to-clr-simple-example-of-clr-stored-procedure/