• 用触发器实现主从表关系(主表更改从表更改 )


     
    用触发器实现的  插入 更新  删除  子表也变化
                                 
    CREATE TABLE [dbo].[tablex] (
        
    [idx] [int] IDENTITY (11NOT NULL ,
        
    [ProductID] [int] NULL ,
        
    [productName] [char] (10) COLLATE Chinese_PRC_CI_AS NULL 
    ON [PRIMARY]
    GO

    CREATE TABLE [dbo].[tabley] (
        
    [idy] [int] IDENTITY (11NOT NULL ,
        
    [ProductID] [int] NULL ,
        
    [productname] [char] (10) COLLATE Chinese_PRC_CI_AS NULL 
    ON [PRIMARY]
    GO




    CREATE TRIGGER  triDelete ON [dbo].[tablex] 
    FOR   delete
    AS

    begin
    declare @aa varchar(200)
    set @aa=(select  productid   from deleted)
    if @@rowcount>0
    delete  tabley    where productid=@aa
    end





    CREATE trigger tritmp on tablex for insert
    as
    insert into tabley(ProductID) select i.ProductId from inserted as i   where  i.ProductId>100



    CREATE TRIGGER  triUpdate  ON [dbo].[tablex] 
    FOR   UPDATE
    AS
    IF UPDATE(productname)
    begin
    declare @aa varchar(200)
    set @aa=(select  productid  from INSERTED)
    declare @bb varchar(200)
    set @bb=(select  productname  from INSERTED)
    if (@@rowcount>0)
    update  tabley  set productname=@bb where productid=@aa
    end






    insert tablex values(300,'东方')

    update tablex set productname='大海' where productid=300
    select * from tablex

    select * from tabley

    delete from tablex where productid=300
    select * from tablex

    select * from tabley


    其实删除时也可以用外键
    删除

    CREATE TABLE [dbo].[TABLE1] (
        
    [UserId] [int] IDENTITY (11NOT NULL ,
        
    [name] [char] (10) COLLATE Chinese_PRC_CI_AS NULL 
    ON [PRIMARY]


    CREATE TABLE [dbo].[TABLE2] (
        
    [id] [int] IDENTITY (11NOT NULL ,
        
    [Userid] [int] NULL ,
        
    [name] [char] (10) COLLATE Chinese_PRC_CI_AS NULL 
    ON [PRIMARY]
    GO




    ALTER TABLE [dbo].[TABLE2] ADD 
        
    CONSTRAINT [FK_TABLE2_TABLE1] FOREIGN KEY 
        (
            
    [Userid]
        ) 
    REFERENCES [dbo].[TABLE1] (
            
    [UserId]
        ) 
    ON DELETE CASCADE 
    GO

    select * from table1

    select * from table2

    insert table1 values('def')
    insert table2 values (5,'def')
     
    select * from table1

    select * from table2

    delete from table1 where userid=5
  • 相关阅读:
    Redis(01)基础知识
    MySQL(05)触发器&事件&事务&锁
    MySQL(04)索引&存储过程
    MySQL(02)DDL&DML
    MySQL(03)表查询
    Go高级编程(01)
    兼容IE8灰色遮罩层处理方法
    AJAX请求跨域的问题
    Sql Server批量删除数据表
    [转]SQL操作日期
  • 原文地址:https://www.cnblogs.com/gwazy/p/484536.html
Copyright © 2020-2023  润新知