简体   繁体   中英

SQL Server IDENTITY column

How can I modify this command in order to have an identity column which has five digits integer like 00000 and start from 00001 ?

CREATE TABLE [dbo].[Company]
(
  [CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
  [Name] [nvarchar](200) NOT NULL
)

An integer does not have any leading 0 by itself. It is a formatting issue to deal with when converting the integer to a string for displaying.

If you really, really need to be able to present such a string right out of SQL, you can do it with a computed column:

CREATE TABLE [dbo].[Company]( 
  [CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
  [FormattedCompanyId] AS RIGHT('0000'+ CONVERT(VARCHAR,Num),5),
  [Name] nvarchar NOT NULL,

I would never use that solution myself though, formatting doesn't belong in the data store.

You need to add the leading zeros yourself. As a solution you can add an other colomn named say "formatedID" and update it with an "after insert trigger" with the value from the identity column and formatted with the leading zeros you want to.

Example :

CREATE TABLE [dbo].[Company]
(
  [CompanyId] [bigint] IDENTITY(1,1) NOT NULL,
  [FormattedID] [VARCHAR(20)],
  [Name] [nvarchar](200) NOT NULL
)

CREATE TRIGGER ON [dbo].[Company]
FOR INSERT
AS
BEGIN
  UPDATE [dbo].[Company]
  FROM inserted
  SET FormattedID = RIGHT('0000'+ CONVERT(VARCHAR, [dbo].[Company].CompanyId),5)
  WHERE dbo.Company.CompanyId = inserted.CompanyId

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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