简体   繁体   English

自动创建字母数字列 - SQL 服务器

[英]Auto create alpha numeric column - SQL Server

Is there anyway to auto generate specific alpha numeric data in a primary key column?无论如何在主键列中自动生成特定的字母数字数据? The column has maximum length of 2 characters.该列的最大长度为 2 个字符。

The table looks like this:该表如下所示:

id
----
4S
33
J6
US

I'm looking to create a stored procedure that inserts a random 2 alpha numeric characters value.我正在寻找创建一个存储过程来插入一个随机的 2 个字母数字字符值。 Is this possible in SQL Server?这在 SQL 服务器中可能吗?

I need it to be auto generated with a combination like我需要使用类似的组合自动生成它

id like '[A-Z][0-9]') 
  or (id like '[A-Z][A-Z]' )
  or (id like '[0-9][0-9]' )
  or (id like '[0-9][A-Z]' )

Don't do it.不要这样做。

Primary keys are internal row identifiers, that are not supposed to be sexy or good looking.主键是内部行标识符,不应该是性感或好看的。 Their purpose is to uniquely identify rows and no more.它们的目的是唯一标识行,仅此而已。

If you need a key to have some format it means you probably want to expose it somewhere, in the user interface or through an API;如果您需要一个具有某种格式的密钥,这意味着您可能希望在用户界面或通过 API 的某个地方公开它; primary keys are not suitable to be exposed to the world.主键不适合暴露给世界。

Now, if you need to expose a key, then you can create a secondary key.现在,如果您需要公开一个密钥,那么您可以创建一个辅助密钥。 This could be an extra column, maybe an auto-generated virtual column, or maybe it can be populated using a trigger.这可能是一个额外的列,可能是一个自动生成的虚拟列,或者可能它可以使用触发器来填充。

Actually you have 2 problems:其实你有2个问题:

  1. Unique random number唯一随机数

You can find answers here: Generate list of new unique random numbers in T-SQL您可以在这里找到答案: 在 T-SQL 中生成新的唯一随机数列表

  1. convert regular (base10) number to Base36 ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')将常规 (base10) 数字转换为 Base36 ('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')

For 2 characters length you can use this code:对于 2 个字符的长度,您可以使用此代码:

DECLARE @Base10ToBase36 AS TABLE (
    ID      TINYINT NOT NULL IDENTITY(0,1) PRIMARY KEY,
    Symbol  CHAR(1) NOT NULL CHECK(Symbol LIKE '[0-9,A-Z]')
)

INSERT INTO @Base10ToBase36(Symbol)
VALUES  ('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9'), 
        ('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'),
        ('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'),
        ('U'), ('V'), ('W'), ('X'), ('Y'), ('Z')

SELECT  TOP (1) 
        pos1.ID * 36 + pos0.ID AS Base10Number,
        pos1.Symbol,
        Pos0.Symbol,
        CONCAT(pos1.Symbol, Pos0.Symbol) AS Base36
FROM    @Base10ToBase36 AS pos0
        CROSS JOIN @Base10ToBase36 AS pos1
ORDER BY NEWID()    -- random

About random you can get more explanation here: Random record from a database table (T-SQL)关于随机你可以在这里得到更多的解释: Random record from a database table (T-SQL)

Regarding primary key - I'm totally agree with @TheImpaler.关于主键——我完全同意@TheImpaler。 It's bad idea这是个坏主意

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

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