这个问题的关键在于:如何立即获取到刚插入的记录的自动编号。因为这个编号需要立即插到另一个表中。例如:有两个表
表格Users的列清单(用户表)
| 名称 | 注释 | 数据类型 | 主要的 | 外来键 |
| U_ID | 用户编号 | int | TRUE | FALSE |
| U_PIN | 身份证号 | char(18) | FALSE | FALSE |
| U_Name | 姓名 | char(10) | FALSE | FALSE |
| U_Sex | 性别,1为男,0为女 | bit | FALSE | FALSE |
| U_Age | 年龄 | int | FALSE | FALSE |
| U_Pic | 图像路径 | varchar(100) | FALSE | FALSE |
| U_Type | 用户类型:0表示管理员,1表示学生,2表示教师 | int |
表格Student的列清单(学生表)
| 名称 | 注释 | 数据类型 | 主要的 | 外来键 |
| S_ID | 学生编号 | int | TRUE | FALSE |
| U_ID | 用户编号 | int | FALSE | TRUE |
| S_ATID | 准考证号 | char(15) | FALSE | FALSE |
| S_School | 所在学校 | varchar(50) | FALSE | FALSE |
每个学生都是一个用户。
在插入一个学生的信息时需要同时向这两个表插入数据。学生表中的U_ID引用用户表中的U_ID.
存储过程如下:
--添加学生用户
if exists(select * from sysobjects where name='addStudent')
drop procedure addStudent
go
create procedure addStudent
(
@U_PIN char(18),--身份证号
@U_Name char(10),--姓名
@U_Sex bit,--性别
@U_Age int, --年龄
@U_Pic varchar(100), --图片
@U_Type int,--用户类别
@U_ATID char(15), --准考证号
@U_School varchar(50)--所在学校
)
as
set @U_Type=1
begin
insert into Users(U_PIN,U_Name,U_Sex,U_Age,U_Pic,U_Type)
values(@U_PIN,@U_Name,@U_Sex,@U_Age,@U_Pic,@U_Type)
declare @U_ID int
set @U_ID=IDENT_CURRENT('Users')--返回指定表中生成的最后一个标示值
insert into Student(U_ID,S_ATID,S_School) values(@U_ID,@U_ATID,@U_School)
end
go
-----------------------------------------------------------------------------------------------------------------------------------
相关知识:
SCOPE_IDENTITY、IDENT_CURRENT 和 @@IDENTITY 是相似的函数,因为它们都返回插入到标识列中的值。
@@IDENTITY 返回最后插入的标识值的系统函数。
SCOPE_IDENTITY() 返回插入到同一作用域中的标识列内的最后一个标识值。一个范围是一个模块:存储过程、触发器、函数或批处理。因此,如果两个语句处于同一个存储过程、函数或批处理中,则它们位于相同的作用域中。IDENT_CURRENT( 'table_name' ) 返回为某个会话和作用域中指定的表或视图生成的最新的标识值。
以下示例将显示由
IDENT_CURRENT、@@IDENTITY和SCOPE_IDENTITY返回的不同标识值。
USE AdventureWorks; GO DROP TABLE t6; DROP TABLE t7; GO CREATE TABLE t6(id int IDENTITY); CREATE TABLE t7(id int IDENTITY(100,1)); GO CREATE TRIGGER t6ins ON t6 FOR INSERT AS BEGIN INSERT t7 DEFAULT VALUES END; GO --End of trigger definition SELECT * FROM t6; --id is empty. SELECT * FROM t7; --ID is empty. --Do the following in Session 1 INSERT t6 DEFAULT VALUES; SELECT @@IDENTITY; /*Returns the value 100. This was inserted by the trigger.*/ SELECT SCOPE_IDENTITY(); /* Returns the value 1. This was inserted by the INSERT statement two statements before this query.*/ SELECT IDENT_CURRENT('t7'); /* Returns value inserted into t7, that is in the trigger.*/ SELECT IDENT_CURRENT('t6'); /* Returns value inserted into t6. This was the INSERT statement four statements before this query.*/ -- Do the following in Session 2. SELECT @@IDENTITY; /* Returns NULL because there has been no INSERT action up to this point in this session.*/ SELECT SCOPE_IDENTITY(); /* Returns NULL because there has been no INSERT action up to this point in this scope in this session.*/ SELECT IDENT_CURRENT('t7'); /* Returns the last value inserted into t7.*/
本文详细介绍了如何在数据库操作中立即获取插入记录后的自动编号,并通过存储过程实例展示了实现这一目标的方法。
1116

被折叠的 条评论
为什么被折叠?



