在我們向資料庫的主從表插入時候(子表需要獲得主表的插入的自增id) 併發是經常發生的
其實可以採取辦法 避免的 下面介紹乙個簡單的方法
就是建立乙個儲存過程 採用儲存過程插入資料 然後 採用scope_identity()獲取id
例如
create procedure [dbo].[ski_insert_hotel_ts_type]
/***********
建立人:
日期、:
功能:新增客房型別
*********/
(@hotel_ts_type_name varchar(100),--型別名稱
@ski_ts_item_id varchar(100),---專案id
@hotel_ts_yj_price numeric(18,4),--預設**
@hotel_ts_zk int,--是否折扣
@hotel_ts_type_qy int--是否啟用)as
set nocount on;
insert into hotel_ts_type(hotel_ts_type_name,ski_ts_item_id,hotel_ts_yj_price,hotel_ts_zk,hotel_ts_type_qy)
values(@hotel_ts_type_name,@ski_ts_item_id,@hotel_ts_yj_price,@hotel_ts_zk,@hotel_ts_type_qy)
select scope_identity()--獲取主表id前台返回
select
set nocount off;
go
下面是引用msdn中的幫助說明為什麼要採用這個函式 而不是和他 功能相近的
ident_current 和 @@identity
scope_identity、ident_current 和 @@identity 在功能上相似,因為它們都返回插入到 identity 列中的值。
ident_current 不受作用域和會話的限制,而受限於指定的表。ident_current 返回為任何會話和作用域中的特定表所生成的值。有關更多資訊,請參見 ident_current。
scope_identity 和 @@identity 返回在當前會話中的任何表內所生成的最後乙個標識值。但是,scope_identity 只返回插入到當前作用域中的值;@@identity 不受限於特定的作用域。
例如,有兩個表 t1 和 t2,在 t1 上定義了乙個 insert 觸發器。當將某行插入 t1 時,觸發器被激發,並在 t2 中插入一行。此例說明了兩個作用域:乙個是在 t1 上的插入,另乙個是作為觸發器的結果在 t2 上的插入。
假設 t1 和 t2 都有 identity 列,@@identity 和 scope_identity 將在 t1 上的 insert 語句的最後返回不同的值。
@@identity 返回插入到當前會話中任何作用域內的最後乙個 identity 列值,該值是插入 t2 中的值。
scope_identity() 返回插入 t1 中的 identity 值,該值是發生在相同作用域中的最後乙個 insert。如果在作用域中發生插入語句到標識列之前喚醒呼叫 scope_identity() 函式,則該函式將返回 null 值。
sql2000 基本刪除,插入,查詢
insert into table1 name subject,class values 我的名字 英語 3 select from table1 insert into table1 subject,class values 英語 3 update table1 set name where is...
SQL2000表分組問題
現sql2000伺服器上有一張表,格式如下 檔案內容 檔案組 1 a2 a 3 a4 b 5 c6 d 7 e8 e 9 f要實現將表內容更新為 檔案內容 檔案組 a1 a 2 a3 a b4 b c5 c d6 d e7 e 8 ef 9 f意思是將分組資訊直接加在檔案內容之中?如果不用游標,不知...
sql2000臨時表分頁
if exists select from dbo.sysobjects where id object id n temp and objectproperty id,n isusertable 1 drop table temp create table temp pager2011 id in...