我有一个看起来像这样的表:
| PK | Col Name | Type |
|----+----------+------|
| X | ParentId | int
| X | Id | int
我尝试将Id
设置为标识,并在父表上设置ParentId。我希望数据看起来像是:
| ParentId | Id |
|----------+----|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
但它看起来像:
| ParentId | Id |
|----------+----|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 4 |
| 2 | 5 |
| 3 | 6 |
事后才有意义。是否可以通过某种方式实现预期的效果?
答案 0 :(得分:1)
如果您想仅从ParentId
获得所需的输出,我也建议您这样做,您可以使用:
select ParentId,
ROW_NUMBER() OVER (PARTITION BY parentid order by parentid) as Id
from Foo
但是如果您仍想在表格中使用,可以在桌面上创建INSTEAD OF INSERT
触发器,这是您可以使用的触发器:
create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
insert into dbo.Foo
(ParentId, Id)
select ParentId,
Id =
isnull( (select max(Id)
from dbo.Foo
where ParentId = i.ParentId), 0) +
row_number() over (partition by ParentId order by (select 1))
from inserted i;
end;
以上触发器的简化版
create trigger dbo.trInsertFoo on dbo.Foo instead of insert
as begin
insert into dbo.Foo
(ParentId, Id)
select ParentId,
Id =
(select isnull(max(Id), 0) + 1 from dbo.Foo where ParentId = i.ParentId)
from inserted i;
end;
但是这个不适用于批量插入,如:
INSERT INTO Foo (ParentId) VALUES (1), (1), (1), (2), (2), (3)`