简体   繁体   English

如何在sql server中创建字符和数字像字母数字的自动增量列?

[英]how to create auto increment column with characters and number like alphanumeric in sql server?

i have a table with primary key column which is auto-increment id of numerals starting from 1000.. 我有一个主键列表,它是从1000开始的数字的自动递增id。

now i have been asked to make a unique key for each records which starts with C20161, C20162, C20163 and so on the series goes on..... 现在我被要求为每个以C20161,C20162,C20163等开头的记录制作一个唯一的密钥......

so it is actually an alphanumeric key that auto-increments.... 所以它实际上是一个自动递增的字母数字键....

i would like to know how to implement the same in sql and also can i update the same to existing records? 我想知道如何在SQL中实现相同的,我也可以更新现有的记录?

is 'sequence' what i am looking for or something else? 是'序列'我在寻找什么或其他什么?

You need COMPUTED COLUMN for this purpose, 为此需要COMPUTED COLUMN

CREATE TABLE TableName(
     ID INT IDENTITY(1,1) NOT NULL,
     NewColumnName AS 'C' + CAST(ID AS VARCHAR(30)),
     .... Other columns list here
)

i hope this is what you ask 我希望这就是你的要求

first: i think you cant edit primary key. 第一:我认为你不能编辑主键。

second: if you want to update all existing data from int to varchar then first you need to change your database. 第二:如果要将所有现有数据从int更新为varchar,则首先需要更改数据库。

after that try to use execute 之后尝试使用执行

example to update from 1001 to C1001 示例从1001更新到C1001

@key nvarhcar(5)
execute('update table set key = ''C' + @var1 +''' where key = @key')

now all you need is get the key 现在你需要的只是得到钥匙
use for to get all key. 用于获取所有密钥。

hope this help you 希望这能帮助你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM