将十六进制转换为 INT,反之亦然

Convert Hexadecimal to INT and vice versa(将十六进制转换为 INT,反之亦然)
本文介绍了将十六进制转换为 INT,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将创建一个由十六进制值组成的序列号

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

使用这种格式:

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

现在要根据十六进制值创建序列号,我需要将 6 添加到最后生成的十六进制值

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.

我已经在 c# 中创建了它,但我需要在 SQL 上进行

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

如何在 T-SQL 中做到这一点?

How can this be done in T-SQL?

推荐答案

希望对你有帮助

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,

输出:

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

这篇关于将十六进制转换为 INT,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)