INSERT INTO if not exists SQL server

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

I have a database structured as follows:

users

userid (Primary Key)
username

group



        
8条回答
  •  离开以前
    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

提交回复
热议问题