Results 1 to 3 of 3

Thread: MSSQL Trigger Questions

  1. #1
    Join Date
    Dec 2008
    Posts
    3

    MSSQL Trigger Questions

    Hi,
    I have a table Barcodes which links to another table Stkmast(stockcodes). There can be multiple barcodes to any one stockcode. If a stockcode is deleted, all barcodes relative to it are deleted. There must always be at least one barcode for each stockcode. The basics I am handling with foreign keys but I have a problem with deleting when there are multiple barcodes.
    I have an Instead of Delete Trigger on my stock file as follows:
    Code:
    BEGIN
         UPDATE [stkmast] 
         set DeleteFlag = 'D'
         WHERE [stkmast].sysid = (SELECT sysid from deleted)
         -- Now delete the record
         DELETE [stkmast] from deleted
         where stkmast.sysid = deleted.SysId
    END
    This is necessary so that the deletion trigger in barcodes knows whether it needs to check how many barcodes exist for the stockcode.
    I have an After Delete Trigger on barcodes as follows:
    Code:
    DECLARE @Delflag char(1)        --check STKMAST.DeleteFlag
    DECLARE @Recs int               --number of barcodes for stockcode
    DECLARE @ErrMsg varchar(80)
    --
    BEGIN
         SET @DelFlag = (SELECT DeleteFlag FROM STKMAST WHERE
             STKMAST.StockCode = (SELECT Stockcode from deleted)
             AND STKMAST.Branch = (SELECT Branch from deleted))
         --
         IF @DelFlag <> 'D' BEGIN        --deleting barcode ONLY
            SET @Recs = (Select count(*) from barmast b     --count records
                WHERE b.Stockcode = (select stockcode from deleted)
                AND b.branch = (SELECT Branch from deleted))
            IF @recs < 1 BEGIN
               SET @ErrMsg = 'Deletion not Allowed' + char(13) + 'At least one barcode per stockcode required'
               RAISERROR(@ErrMsg,16,10)
               ROLLBACK TRANSACTION
            END
         END
    END
    As noted above, this all works fine except for when I delete a stockcode which has mutiple barcodes. I then get an error "Subquery returned more than 1 value".
    Can someone please give me some pointers on this? What am I doing wrong? Is there a better way of achieving this? I particularly want to process it at the trigger level for integrity reasons .

    Thanks

    David

  2. #2
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    UPDATE [stkmast]
    set DeleteFlag = 'D'
    WHERE [stkmast].sysid IN (SELECT sysid from deleted)
    -- Now delete the record
    DELETE [stkmast] from deleted
    where stkmast.sysid = deleted.SysId

  3. #3
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •