sql server - SQL - Identity Group By -
in sql server 2012 database, i'm creating "tasks" table have compound primary key composed of 3 fields:
issue_id [int] not null, issue_sub_id [int] not null, task_id [int] not null issue_id , issue_sub_id foreign keys other tables. in table i'm creating, there can many tasks associated each issue_id / issue_sub_id combination.
what establish default value task_id column, similar if used identity(1,1), auto-increment based on issue_id / issue_sub_id group. example, task_id results follows, given provided issue_id / issue_sub_id values:
issue_id issue_sub_id task_id ======== ============ ======= 12345 1 1 12345 1 2 12345 1 3 12345 2 1 12345 2 2 67890 2 1 67890 2 2 67890 2 3 i'm familiar row_number() over(partition issue_id, issue_sub_id order issue_id, issue_sub_id) possible solution but, i'd column part of compound primary key of table, don't think work.
thanks in advance.
i agree sean - add identity column, , use computed column task id. though i've answered question 1 here, i'm not sure marking 1 duplicate. reason want use task_id part of primary key.
however, i'm not sure that's possible, since in order include computed column in primary key must persisted, , reason (i think it's because of use of udf) sql server not allow me mark persisted.
anyway, here proposed solution this:
first, create function calculate task id:
create function dbo.generatetaskid ( @row_id int, @issue_id int, @issue_sub_id int ) returns int begin return ( select count(*) dbo.tasks issue_id = @issue_id , issue_sub_id = @issue_sub_id , row_id <= @row_id ) end go then, create table task id 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 dbo.generatetaskid(row_id, issue_id, issue_sub_id), constraint pk_tasks primary key (row_id) ) go now, test it:
insert tasks values (12345, 1), (12345, 1), (12345, 1), (12345, 2), (12345, 2), (67890, 2), (67890, 2), (67890, 2) select * 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
Comments
Post a Comment