+ -
当前位置:首页 → 问答吧 → 请教表关联问题!

请教表关联问题!

时间:2011-11-22

来源:互联网

产品表:(产品ID 产品名称要求唯一)

产品ID 产品名称 产品价格

库存表:

产品ID 产品名称 库存数量

假如有2个表如上所示,如果要删除或修改产品表中一项纪录,而库存表能够自动更新,请问要怎么做?谢谢!
另外:帮忙解释一下主键、外键、索引及它们的作用,谢谢!

作者: fxwzzbd   发布时间: 2011-11-22

在产品表加更新及删除触发器,在产品表有变动时,更新库存表,
主键、外键、索引及它们的作用参考联机丛书

作者: jyh070207   发布时间: 2011-11-22

需要用触发器实现。

作者: fredrickhu   发布时间: 2011-11-22

SQL code



-- create table product (aid int,name varchar(10),price numeric(18,2))
-- 
-- insert product select '1','aaa','18' union all
-- select '2','bbb','25' union all
-- select '3','ccc','36.9'
-- 
--  create table pstore (aid int,name varchar(10),num varchar(10))
-- insert pstore select '1','aaa','999' union all
-- select '2','bbb','19999' union all
-- select '3','ccc','25862' 

select * from product
select * from pstore

-- create procedure pr_update @aid int,@name varchar(10)
-- as
-- begin
--     update product set name=@name where aid=@aid
--     
--     update pstore set name=b.name  from pstore a,product b where a.aid=b.aid and b.aid=@aid
-- end

exec  pr_update '3','ccc01'


作者: renadg   发布时间: 2011-11-22

SQL code

--触发器实现
if object_id('产品表','U') is not null
   drop table 产品表
go
create table 产品表
(
 产品ID int,
 产品名称 varchar(10),
 产品价格 int
)
go
if object_id('库存表','U') is not null
   drop table 库存表
go
create table 库存表
(
 产品ID int,
 产品名称 varchar(10),
 库存数量 int
)
go
--只实现了插入的触发,楼主可以根据需要实现update,delete的触发器
if object_id('tr_cp_insert','tr') is not null
   drop trigger tr_cp_insert
go
create trigger tr_cp_insert on 产品表
for insert
as
  if exists(select 1 from 库存表 where 产品id in(select 产品id from inserted))
     update 库存表 set 库存数量=库存数量+1
  else
     insert into 库存表 select 产品ID,产品名称,1 from inserted
go
insert into 产品表 select 1,'矿泉水',10
select * from 库存表
/*
产品ID        产品名称       库存数量
----------- ---------- -----------
1           矿泉水        1

(1 行受影响)

*/

作者: pengxuan   发布时间: 2011-11-22