1

我(将)有数十万条记录,我插入一次,永远不会更新许多行包含相同的previousId。我可以保证一个开始/结束索引吗?我在 table_c 中使用事务插入 X 行,并将开始和结束(或开始和长度或结束和长度)写入 table_b,而不是让每一行都保存 table_b ID?

如果是这样,我该如何编写 SQL?我刚在想

begin transaction
insert XYZ rows into tbl_c
c_rowId = last_insert_rowid
insert table_b with data + start=c_rowId-lengthOfInsert, end=c_rowId;
commit; end transaction

这会按我的预期工作吗?

4

2 回答 2

3

看起来你想要的是一个自动编号列。在大多数 DBMS 中,您可以将此列定义为表定义的一部分,它会自动为行编号。您可以使用函数来获取插入的最后一行的 ID;在 SQL Server (T-SQL) 中,您可以使用 SCOPE_IDENTITY() 函数。如果 ID 必须是某个值或值范围,您可能需要手动执行此操作并使用锁定提示来防止另一个并发事务修改您的标识符信息。

于 2009-09-27T03:32:11.013 回答
1

您可以使用 tablockx 锁定 sql server 中的完整表。

所以:

begin the transaction, 
select max(txnid) from table with (tablockx)  -- now the table is locked

--figure out how many more you are going to insert 
lastId = maxNum + numToInsert

set allow insert auto_increment on insert -- not sure what this is

while (moreToInsert)
  insert int table (id,x,y) values (id+1,'xx','yy')

commit transaction

但是,问题在于它完全锁定了表。自动递增列(auto_increment (mysql) 或标识 mssql)可能是您真正想要的,并且不会限制对整个表的访问。(这在另一个答案中注明)

于 2009-09-27T03:31:53.027 回答