INSERT INTO if not exists SQL server

前端 未结 8 473
无人共我
无人共我 2020-12-05 11:45

I have a database structured as follows:

users

userid (Primary Key)
username

group



        
相关标签:
8条回答
  • 2020-12-05 12:14

    There is a simple solution! I Found it in this post!

    INSERT INTO users (Username) 
    SELECT ('username')
    WHERE NOT EXISTS(SELECT * FROM users WHERE Username= 'username')
    

    In my project I needed to do it with 2 values. So my code was:

    INSERT INTO MyTable (ColName1, ColName2) 
    SELECT 'Value1','Value2' 
    WHERE NOT EXISTS
    (SELECT * FROM MyTable WHERE ColName1 = 'Value1' AND ColName2= 'Value2')
    

    Hope this helps!

    0 讨论(0)
  • 2020-12-05 12:20

    I would first create a stored proc on the db to do the check and insert if necessary:

    CREATE PROCEDURE AddNewUserProc
    (
    @username       VarChar(50) -- replace with your datatype/size
    )
    
    AS
    
        IF NOT EXISTS (SELECT * FROM users WHERE username = @username)
        BEGIN
            INSERT INTO users
            VALUES (@username)
        END
    

    Then a method on the app that will call this procedure

    public void AddNewUserMethod(string userName)
    {
        SqlConnection connection = new SqlConnection("connection string");
        SqlCommand command = new SqlCommand("AddNewUserProc", connection);
    
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("username", SqlDbType.VarChar, 50).Value = userName;
    
        try
        {
            connection.Open();
            command.ExecuteNonQuery();
        }
        finally
        {
            if (connection.State == ConnectionState.Open) { connection.Close(); }
        }
    }
    

    Note leaving this as alternative/historical, but for purpose of correctness the correct way is using the Merge statement, see answer https://stackoverflow.com/a/9649040/167304 or checkout MS doc https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver15

    0 讨论(0)
提交回复
热议问题