17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7: Advanced Use of ConstraintsSET NOCOUNT ON ;BEGIN TRANSACTION ;DECLARE @ItemID INT ,@ChangeQuantity INT ,@ChangeDate DATETIME ;SET @ItemID = 1 ;SET @ChangeQuantity = 5 ;SET @ChangeDate = '20100101' ;-- this is a valid change:-- we can always add to InventoryLogINSERT INTO dbo.InventoryLog( ItemID ,ChangeDate ,ChangeQuantity ,CurrentQuantity)SELECT @ItemID ,@ChangeDate ,@ChangeQuantity ,COALESCE(( SELECT TOP (1)CurrentQuantityFROM dbo.InventoryLogWHERE ItemID = @ItemIDAND ChangeDate < @ChangeDateORDER BY ChangeDate DESC), 0) + @ChangeQuantity-- we do not have log entries for later daysWHERE NOT EXISTS ( SELECT *FROM dbo.InventoryLogWHERE ItemID = @ItemIDAND ChangeDate > @ChangeDate ) ;SET @ItemID = 1 ;SET @ChangeQuantity = -3 ;SET @ChangeDate = '20100105' ;233

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!