27,582
社区成员




if exists (select * from sysobjects where id = OBJECT_ID('[UserRoles]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [UserRoles]
CREATE TABLE [UserRoles]
(
[UserID] [int] NOT NULL,
[RoleID] [int] NOT NULL
)
最好给出完整的表结构,测试数据,计算方法和正确结果.否则耽搁的是你宝贵的时间。
如果有多表,表之间如何关联?
/*
标题:两表通过字段关联进行级联删除。
作者:爱新觉罗·毓华(十八年风雨,守得冰山雪莲花开)
时间:2008-11-20
地点:广东深圳
*/
create table ta(id int not null)
create table tb(id int , aid int)
insert into ta values(1)
insert into ta values(2)
insert into tb values(1 , 1)
insert into tb values(2 , 2)
insert into tb values(3 , 1)
go
--一、查看原始数据
--ta表的原始数据
select * from ta
/*
id
-----------
1
2
*/
--tb表的原始数据
select * from tb
/*
id aid
----------- -----------
1 1
2 2
3 1
*/
--二、看看没有创建级联删除时的情况(删除ta表id=1的数据,看看是否影响tb表)
delete from ta where id = 1
select * from ta
/*
id
-----------
2
*/
select * from tb
/*
id aid
----------- -----------
1 1
2 2
3 1
*/
--三、恢复原始数据,创建级联删除,删除ta表id=1的数据,看看是否影响tb表
insert into ta values(1)
--为ta创建主健
alter table ta add constraint pk_ta_id primary key (id)
go
--为tb创建外健,并指定级联删除
alter table tb add constraint fk_tb_aid foreign key (aid) references ta(id) on delete cascade
go
delete from ta where id = 1
select * from ta
/*
id
-----------
2
*/
select * from tb
/*
id aid
----------- -----------
2 2
*/
--删除级联约束
alter table tb drop constraint fk_tb_aid
go
--删除测试表
drop table ta , tb
go
create trigger t_up on Users
after update
as
update a
set a.userID = c.userID
from UserRoles a,deleted b,inserted c
where b.id = c.id and a.userID = b.userID
--id是自增列,如果Users没有其他能够标识userID变化的,估计没办法!
if exists (select * from sysobjects where id = OBJECT_ID('[Users]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [Users]
create table Users(userid numeric(4),username varchar(10));
insert into users values(1,'a');
insert into users values(2,'b');
insert into users values(3,'c');
if exists (select * from sysobjects where id = OBJECT_ID('[Roles]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [Roles]
create table Roles(roleid numeric(3),rolename varchar(12));
insert into Roles values(100,'r1');
insert into Roles values(101,'r2');
insert into Roles values(102,'r3');
select * from users;
select * from roles;
if exists (select * from sysobjects where id = OBJECT_ID('[UserRoles]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [UserRoles]
CREATE TABLE [UserRoles]
(
[UserID] [int] NOT NULL,
[RoleID] [int] NOT NULL
)
insert into UserRoles select t1.userid,t2.roleid from users t1,roles t2;
select * from UserRoles;
userid username
------ ----------
1 a
2 b
3 c
(所影响的行数为 3 行)
roleid rolename
------ ------------
100 r1
101 r2
102 r3
(所影响的行数为 3 行)
(所影响的行数为 9 行)
UserID RoleID
----------- -----------
1 100
2 100
3 100
1 101
2 101
3 101
1 102
2 102
3 102
(所影响的行数为 9 行)