SQL Create Table that Auto-Increments one column based on another column

大城市里の小女人 提交于 2019-12-24 21:50:28

问题


I'm still a beginner with SQL so please bear with me. I need to create a table that stores information from a form. Each form has an ID associated with it that has two parts. The first part is MMYY and the second part is a 5 digit auto-incrementing integer. An example ID is 0714-00001. And every time the month changes, the 5 digit numbering should start over. So, I want the columns to look something like this:

Order_No. | Order_ID
----------------------------
0714         | 0001
0714         | 0002
0714         | 0003
0814         | 0001
0814         | 0002
0914         | 0001

Is there any way to get the auto-incrementing column to restart it's incrementing when the month changes in the SQL-Server?

I've also looked around and few answers suggested using PHP to do this, but because I am using a CMS, I can't enter any PHP script of my own.

UPDATE: I ended up just writing an IF statement in the CMS site for whether the order_no entered in the form matched the order_no in the existing table or not. If they matched the new row would be inserted into the existing table and if they didn't match, all the data from the existing table would be copied to a backup table, the existing table would then be truncated, and then the new would be inserted. Thus allowing the table to restart the counting at 1 again.


回答1:


Probably you can write a after insert trigger where you can validate whether the month changed and then reseed identity accordingly. I have tried to depict the scenario of yours and below is the sample code for the same

Create and Insert statement

CREATE TABLE Table1
    ([Order_No] varchar(4), [Order_ID] int not null identity)
;

INSERT INTO Table1
    ([Order_No])
VALUES
    ('0714'),('0714'),('0714');

select * from table1;

Create the trigger

create trigger trg_reseed on test.dbo.table1
after insert
as 
IF EXISTS (SELECT 1 FROM Table1 t1 
             JOIN inserted i ON t1.[Order_No] = i.[Order_No])
begin
DBCC CHECKIDENT (Table1, reseed, 1)
end

Test Scenario:

No change in Identity seed value, it will increment to next value since month is same

INSERT INTO Table1
    ([Order_No])
VALUES
    ('0714');

Reseed the identity value since inserted month is different

INSERT INTO Table1
    ([Order_No])
VALUES
    ('0914');

Hope this will get you idea and get started.



来源:https://stackoverflow.com/questions/24335341/sql-create-table-that-auto-increments-one-column-based-on-another-column

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