How to automatically generate unique id in SQL like UID12345678?(如何在 SQL 中自动生成唯一 ID,如 UID12345678?)
问题描述
我想自动生成带有每个定义代码的唯一 ID.
I want to automatically generate unique id with per-defined code attach to it.
例如:
UID12345678
CUSID5000
我尝试了 uniqueidentifier
数据类型,但它生成的 id 不适合用户 ID.
I tried uniqueidentifier
data type but it generate a id which is not suitable for a user id.
大家有什么建议吗?
推荐答案
我认为唯一可行的解决方案是使用
The only viable solution in my opinion is to use
ID INT IDENTITY(1,1)
列让 SQL Server 处理数值的自动递增- 一个计算的、持久的列,用于将该数值转换为您需要的值
- an
ID INT IDENTITY(1,1)
column to get SQL Server to handle the automatic increment of your numeric value - a computed, persisted column to convert that numeric value to the value you need
所以试试这个:
CREATE TABLE dbo.tblUsers
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
.... your other columns here....
)
现在,每次您在 tblUsers
中插入一行而不指定 ID
或 UserID
的值时:
Now, every time you insert a row into tblUsers
without specifying values for ID
or UserID
:
INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
然后 SQL Server 将自动且安全地增加您的 ID
值,并且 UserID
将包含像 UID00000001
这样的值, UID00000002
,......等等——自动、安全、可靠、无重复.
then SQL Server will automatically and safely increase your ID
value, and UserID
will contain values like UID00000001
, UID00000002
,...... and so on - automatically, safely, reliably, no duplicates.
更新:UserID
列是计算的 - 但它仍然当然有一个数据类型,快速浏览一下对象资源管理器就会发现:
Update: the column UserID
is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:
这篇关于如何在 SQL 中自动生成唯一 ID,如 UID12345678?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 SQL 中自动生成唯一 ID,如 UID12345678?


- 更改自动增量起始编号? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- SQL 临时表问题 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01