Using IF ELSE statement based on Count to execute different Insert statements

后端 未结 8 977
灰色年华
灰色年华 2020-12-01 08:40

While I am searching through my database, I run an INSERT statement if I find that a particular item does not exist, and I run a different INSERT statement if I find one or

8条回答
  •  余生分开走
    2020-12-01 09:21

    There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL

    We'll start by getting row count (Another Quick Example) and then do if/else

    -- Let's get our row count and assign it to a var that will be used
    --    in our if stmt 
    DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
    SELECT @HasExistingRows = Count(*) 
       ELSE 0 -- false
    FROM
       INCIDENTS
    WHERE {Your Criteria}
    GROUP BY {Required Grouping}
    

    Now we can do the If / Else Logic MSDN Docs

    -- IF / Else / Begin / END Syntax
    IF @HasExistingRows = 0 -- No Existing Rows
       BEGIN
          {Insert Logic for No Existing Rows}
       END
    ELSE -- existing rows are found
       BEGIN
          {Insert logic for existing rows}
       END
    

    Another faster way (inspired by Mahmoud Gamal's comment):

    Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.

    IF EXISTS ({SELECT Query})
       BEGIN
          {INSERT Version 1}
       END
    ELSE
       BEGIN
          {INSERT version 2}
       END
    

提交回复
热议问题