Identity-like column but based on Group By criteria

心不动则不痛 提交于 2019-12-01 19:05:23

I agree with Sean - add an identity column, and then just use a computed column for the task id. Even though I've answered a question very much like this one here, I'm not sure about marking this one as a duplicate. The reason for this is that you want to use the task_id as a part of the primary key.
However, I'm not sure that's possible, since in order to include a computed column in the primary key it must be persisted, and for some reason (I think it's because of the use of a UDF) SQL Server will not allow me to mark it as persisted.
Anyway, here is my proposed solution for this:

First, create a function that will calculate the task id:

CREATE FUNCTION dbo.GenerateTaskId
(
    @Row_Id int,
    @Issue_Id int,
    @Issue_Sub_Id int
)
RETURNS Int
AS
BEGIN

    RETURN 
    (
        SELECT COUNT(*)
        FROM dbo.Tasks
        WHERE Issue_Id = @Issue_Id
        AND Issue_Sub_ID = @Issue_Sub_ID
        AND Row_Id <= @Row_Id
    )
END
GO 

Then, create the table with the task id as a computed column:

CREATE TABLE dbo.Tasks
(
    Row_Id [int] IDENTITY(1,1),
    Issue_ID [int] NOT NULL,
    Issue_Sub_ID [int] NOT NULL,
    Task_Id AS dbo.GenerateTaskId(Row_Id, Issue_Id, Issue_Sub_Id), 
    CONSTRAINT PK_Tasks PRIMARY KEY (Row_Id)
)
GO

Now, test it:

INSERT INTO Tasks VALUES
(12345, 1),
(12345, 1),
(12345, 1),
(12345, 2),
(12345, 2),
(67890, 2),
(67890, 2),
(67890, 2)

SELECT *
FROM Tasks

Results:

Row_Id  Issue_ID    Issue_Sub_ID    Task_Id
1       12345       1               1
2       12345       1               2
3       12345       1               3
4       12345       2               1
5       12345       2               2
6       67890       2               1
7       67890       2               2
8       67890       2               3

You can see a live demo on rextester.

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