重置每个外键字段的种子

时间:2016-12-18 08:29:07

标签: sql sql-server

我创建了2个表,Header和Lines:

CREATE TABLE HEADER 
(
HeaderId int IDENTITY (1,1),
HeaderName varchar(20)
CONSTRAINT pk_header PRIMARY KEY (HeaderId)
);

CREATE TABLE Lines
(
LineId int IDENTITY (1,1),
HeaderId int REFERENCES HEADER(HeaderId),
LineName varchar(20)
CONSTRAINT pk_header_line PRIMARY KEY (LineId, HeaderId)
)

这是插入一些数据后我的Lines表的样子:

LineId  HeaderId    LineName
1       1           Header1 Line1
2       1           Header1 Line2
3       2           Header2 Line1

当HeaderId发生变化时,LineId是否有可能从1开始?

这样的事情:

LineId  HeaderId    LineName
1       1           Header1 Line1
2       1           Header1 Line2
1       2           Header2 Line1

1 个答案:

答案 0 :(得分:1)

没有内置机制。
您可以在HEADER表中添加lines int列,其中包含每个标题的行数,默认为0.
将记录插入行时,应使用HEADER.lines + 1作为LineId,并将HEADER.lines增加1。
您可以通过应用程序或使用触发器在线上插入来执行此操作 在任何情况下都要考虑到Line上的删除会破坏序列。

create table header 
(
    headerid    int         identity (1,1) constraint header_pk_headerid primary key
   ,headername  varchar (20)
   ,lines       int         not null    default (0)
)


create table lines
(
    lineid      int         not null
   ,headerid    int         not null    constraint lines_fk_headerid references header(headerid)
   ,linename    varchar (20)
   ,constraint lines_pk_headerid_lineid primary key (lineid, headerid)
)

go

create trigger lines_trg_ins  
on lines
instead of insert
as  

    declare @lines table (headerid int,lines int)

    update  h
    set     h.lines = h.lines + i.lines
    output  deleted.headerid,deleted.lines into @lines
    from            header as h 
            join    (select headerid,count(*) as lines from inserted group by headerid) as i
            on      i.headerid = h.headerid

    insert into lines (lineid,headerid,linename)
    select  row_number() over (partition by i.headerid order by getdate()) + l.lines,l.headerid,i.linename
    from    inserted i join @lines l on l.headerid = i.headerid 
insert into header (headername) values ('header1'),('header2')
insert into lines (headerid,linename) values (1,'header1 line1'),(1,'header1 line2'),(1,'header1 line3'),(2,'header2 line1'),(2,'header2 line2')
select * from header
+----------+------------+-------+
| headerid | headername | lines |
+----------+------------+-------+
| 1        | header1    | 3     |
+----------+------------+-------+
| 2        | header2    | 2     |
+----------+------------+-------+
select * from lines order by headerid,lineid
+--------+----------+---------------+
| lineid | headerid | linename      |
+--------+----------+---------------+
| 1      | 1        | header1 line1 |
+--------+----------+---------------+
| 2      | 1        | header1 line2 |
+--------+----------+---------------+
| 3      | 1        | header1 line3 |
+--------+----------+---------------+
| 1      | 2        | header2 line1 |
+--------+----------+---------------+
| 2      | 2        | header2 line2 |
+--------+----------+---------------+