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
- 无法解决整理冲突 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
