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


基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 在多列上分布任意行 2021-01-01