Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2002
    Posts
    42

    Unanswered: Conditional Insert

    I need to do a conditional insert. This is what I have tried, it does not work.
    What am I doing incorrectly?

    IF (SELECT COUNT(*) FROM TBL1 INNER JOIN
    TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
    TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
    TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC) > 0

    INSERT INTO TBL5
    SELECT TBL1.PRO_SITE, TBL1.MODEL_ID,
    TBL1.NUM_SLOTS, TBL1.TARGET_DAYS, GETDATE() AS Expr1,
    TBL3.TYPE_ID, NULL AS Expr2, TBL1.NUM_SLOTS AS Expr3, NULL AS Expr4, NULL
    AS Expr5, 0 AS RAMP
    FROM TBL1 INNER JOIN
    TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID INNER JOIN
    TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE INNER JOIN
    TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC

    UPDATE TBL5
    SET TEAMS=0
    GO
    UPDATE TBL5
    SET TEAMS = (SELECT NUM_SLOTS
    FROM TBL6 R1
    WHERE (R1.TEAM_ID = TBL5.TEAM_ID)
    )
    WHERE (TEAM_ID =
    (SELECT TEAM_ID
    FROM TBL6 R3
    WHERE (R3.TEAM_ID = TBL5.TEAM_ID)))
    GO
    UPDATE TBL5
    SET TOTALTEAMS = TEAMS + RAMP
    GO

    I need to do a conditional because sometimes the select that returns data contains no records.

    Thanks...

  2. #2
    Join Date
    Jan 2004
    Location
    In a large office with bad lighting
    Posts
    1,040
    Try this:

    IF EXISTS
    (SELECT 1
    FROM TBL1
    INNER JOIN TBL2 ON TBL1.MODEL_ID = TBL2.MODEL_ID
    INNER JOIN TBL3 ON TBL1.PRO_TYPE = TBL3.TYPE
    INNER JOIN TBL4 ON TBL1.PRO_SITE = TBL4.WHDESC)
    BEGIN
    UPDATE <stuff here>
    END
    ELSE
    BEGIN
    INSERT <stuff here>
    END

Posting Permissions

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