MSSQL INSERT only if not exists

Posted on 2009-02-19
Last Modified: 2012-06-22
My Table

imei        date             month    
112232   12/21/01    200901

imei = PK

need to insert records into this table.
BUT If imei already exists donot insert
need syntax.....
Question by:isaackhazi
    LVL 32

    Accepted Solution

    if not exists (Select * from MyTable Where imei = 112232)
    Insert Into Mytable(imei, [Date], [Month])
      Values(112232, '12/21/2001', 200901)
    LVL 8

    Author Closing Comment

    Spot on....

    Expert Comment

    INSERT INTO dbo.ReportUsers (Report_Id, User_Id)
    SELECT r2.Report_Id, r2.User_Id
        dbo.ReportUsers r1 LEFT JOIN
        (SELECT 'rid1' AS Report_Id, 'JohnDoe' AS UserId) r2 ON
            r1.Report_Id = r2.Report_Id AND
            r1.UserId = r2.UserId
        s1.Report_Id IS NULL

    Expert Comment

    The above avoids any possibility that a duplicate row could slip in.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    Suggested Solutions

    There have been several questions about Large Transaction Log Files in SQL Server 2008, and how to get rid of them when disk space has become critical. This article will explain how to disable full recovery and implement simple recovery that carries…
    In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now