Create column which increases from last index [duplicate]

独自空忆成欢 提交于 2019-12-10 18:30:04

问题


I need to generate a column for InvoiceID. and I want to keep the formate of this column like this

INV0000001,
INV0000002,
.
.
.
.
INV0000010,
INV0000011,
.
. and so on. 

As you can see this column is increasing with last index. How can i do this.

I'm using SQL Server 2012.

I have searched, but couldn't find, how to increase a number like this.


回答1:


Try using computed column MSDN

CREATE TABLE Yourtablename
(
    ID int IDENTITY (1,1) NOT NULL,
    InvoiceID AS 'INV'+ right('000000'+cast(ID as varchar(20)),7) PERSISTED
);

SQLFIDDLE DEMO

For more info on why you need to make your computed column as persisted check here




回答2:


try, this one :- (completely dynamic)

Declare @NextInvoice    Int = 0

Select  @NextInvoice = Isnull(Max(Cast(Replace('INV0000011','INV','') As Bigint)),0) + 1

Select  'INV' + Left('0000000', (Len('0000000') -Len(@NextInvoice))) + Cast(@NextInvoice As Varchar(20))



回答3:


hope this will work for u

SELECT
    INV + right('000' + an_auto_increment_column, 3)  AS InvoiceID
    FROM yourTable


来源:https://stackoverflow.com/questions/31468567/create-column-which-increases-from-last-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!