2008年6月25日 11:12:28
1.检查要创建的表是否存在? IFOBJECT_ID('Price_history','U') ISNOTNULL DROPTABLE Price_history
2.复到一个表的表结构以开成一个新表。 SELECT1AS ProductID,UnitPrice AS OldPrice,UnitPrice AS NewPrice,GETDATE() AS Date INTO Price_history FROM dbo.Products WHERE1=0
3.判断某触发器是否存在? IFOBJECT_ID('trg_Products_u','TR') ISNOTNULL DROPTRIGGER trg_Products_u; GO
4.创建一个触发器 CREATETRIGGER trg_Products_u ON dbo.Products FORUPDATE AS --如果更新的不是UnitPrice或没有更新直接返回 IFNOTUPDATE(UnitPrice) OR@@ROWCOUNT=0 RETURN; ELSE INSERTINTO price_history//实现了在更新价格时在日志表里记录下原始价格和新价格 SELECT i.ProductID,d.UnitPrice,i.UnitPrice,getdate() FROM inserted i join deleted d //用Inserted和Deleted这两个表实现:) on i.ProductID=d.ProductID GO
5.一个带多表查询的UPdate语句 update p set UnitPrice=UnitPrice*1.5 from dbo.Products p join dbo.Suppliers s on p.SupplierID=s.SupplierID where s.city=N'London'
6.检查、创建、执行存储过程 IFOBJECT_ID('prc_UpdateProductPrice','P') ISNOTNULL DROPPROC prc_UpdateProductPrice; GO CREATEPROCEDURE prc_UpdateProductPrice WITH RECOMPILE AS BEGIN SET NOCOUNT ON; update p set UnitPrice=UnitPrice*1.5 from dbo.Products p join dbo.Suppliers s on p.SupplierID=s.SupplierID where s.city=N'London' END GO EXEC prc_UpdateProductPrice GO