如何在 SQL 中自动生成唯一 ID,如 UID12345678? [英] How to automatically generate unique id in SQL like UID12345678?

查看:375
本文介绍了如何在 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 中插入一行而不指定 IDUserID 的值时:

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆