注册 登录
编程论坛 SQL Server论坛

存储过程、触发器中令人纠结的问题

Benthy2 发布于 2012-08-14 01:42, 600 次点击
纠结问题一:写一个存储过程,该存储过程是向数据库的表插入数据,那如何返回id?比如下面的一个这个存储过程:
create proc myinsert
@name nvarchar(10),
@birthday date
as
insert into mydatabase (id, name,birthday) values(newid(),@name,@birthday)
怎么修改这个存储过程,使用它能“output”新增的数据的id??强调一点,id的数据类型是uniqueidentifier

纠结问题二:数据库中有两个相关联的表:表A、表B,表B通过一个外键关联表A。现在我们要删除表A里面的一些数据,但考虑到表B与表A的关系,我们需要先删除表B中的一些数据(这个大伙懂得,我就不那么麻烦地去细讲),问题是:如何为表A建一个触发器,当表A进行delete操作时,就会触发这个触发器先将表A的那些需要被删除的数据删除,从而可以省事地删除表A的数据,例如创建这样的两个表:
表student,
create table student
(
    Num char(12) primary key check(len(Num) = 12),
    name nvarchar(10),
    sex nchar(2) check(sex = '男' or sex = '女')  
)

表score,
create table score
(
    Num char(12) primary  key check(len(Num) = 12),
    math int check(math >= 0 and math <= 100 ),
    Chinese int check(math >= 0 and math <= 100 ),
    English int check(math >= 0 and math <= 100 ),
    foreign key(Num) references student(Num)  
)
创建出一个触发器,可以使删除表student的数据能直接使用SQL语句:delete from student where name = ...
5 回复
#2
Benthy22012-08-14 01:43
...
#3
netlin2012-08-14 08:26
第一个问题:
create proc myinsert
@name nvarchar(10),
@birthday date,
@NewID uniqueidentifier output
as
select @NewID=newid()
insert into mydatabase (id, name,birthday) values(@NewID,@name,@birthday)

#4
netlin2012-08-14 08:43
第二个问题:

建立 INSTEAD OF DELETE 触发器

#5
Benthy22012-08-16 14:44
回复 4楼 netlin
INSTEAD OF DELETE 触发器 只会删除表score的数据,删不掉表student的数据啊!
#6
Benthy22012-08-22 23:38
。。。
1