INSERT INTO if not exists SQL server

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

I have a database structured as follows:

users

userid (Primary Key)
username

group



        
8条回答
  •  温柔的废话
    2020-12-05 12:02

    The following code is a method that returns 0 if user already exists and returns the new user ID that just added :

      private int TryToAddUser(string UserName)
            {
                int res = 0;
                try
                {
                    string sQuery = " IF NOT EXISTS (select * from users where username = @username) \n\r" + 
                    " BEGIN \n\r" + 
                    "     INSERT INTO users values (@username) \n\r" + 
                    " SELECT SCOPE_IDENTITY() \n\r " + 
                    " END \n\r " + 
                    " ELSE SELECT 0";
                    using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand())
                    {
                        cmd.CommandText = sQuery;
                        cmd.Parameters.AddWithValue("@username",UserName);
                        cmd.Connection = new System.Data.SqlClient.SqlConnection("SomeSqlConnString");
                        cmd.Connection.Open();
                        res = (int)cmd.ExecuteScalar();
                        cmd.Connection.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                return res;
            }
    

提交回复
热议问题