SQL Server: Auto increment char pk(SQL Server:自动递增 char pk)
问题描述
表上是否可以有一个 char 主键?比如'WC001'会自动加1,所以pk的下一条记录就是'WC002'等等.
Is it possible to have a char primary key on a table? For example 'WC001' then will it automatically increment by 1, so the next record for the pk will be 'WC002' and so on.
谁能给我举个例子?
谢谢
推荐答案
不是直接 - 但你可以有一个普通的 INT IDENTITY
自动递增数字 ID,然后定义一个计算的持久列(SQL Server2005 年及更新版本) - 类似于:
Not directly - but you could have a normal INT IDENTITY
auto-incrementing numerical ID and then defines a computed persisted column (SQL Server 2005 and newer) - something like:
CREATE TABLE dbo.YourTable
(ID INT IDENTITY(1,1),
CharID AS 'WC' + RIGHT('000' + CAST(ID AS VARCHAR(3)), 3) PERSISTED,
CONSTRAINT PK_YourTable PRIMARY KEY(CharID)
)
将值插入此表将导致 ID
列为 1, 2, 3, 4, 5,
..... 和 CharID
列将自动为 WC001
、WC002
、WC003
等.
Inserting values into this table will cause the ID
column to be 1, 2, 3, 4, 5,
..... and the CharID
column will automatically be WC001
, WC002
, WC003
and so forth.
由于它是一个持久化计算列,其值始终是最新的,您甚至可以在其上放置一个索引(如主键).
Since it's a persisted computed column, the values is always up to date, and you can even put an index (like the primary key) on it.
这篇关于SQL Server:自动递增 char pk的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL Server:自动递增 char pk


基础教程推荐
- 从字符串 TSQL 中获取数字 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01