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