INSERT INTO if not exists SQL server

前端 未结 8 472
无人共我
无人共我 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;
            }
    
    0 讨论(0)
  • 2020-12-05 12:02

    Here is a (probably oversimplified) example that addresses your issue. Note that it is always best to use parameters to prevent injection attacks, especially when verifying users.

    CREATE PROCEDURE AddUser
      @username varchar(20)
    AS
      IF NOT EXISTS(SELECT username FROM users WHERE username=@username)
        INSERT INTO users(username) VALUES (@username)
    
    0 讨论(0)
  • 2020-12-05 12:05
    IF NOT EXISTS (select * from users where username = 'username')
    BEGIN
        INSERT INTO ...
    END
    
    0 讨论(0)
  • 2020-12-05 12:10

    Basically you can do it like this:

    IF NOT EXISTS (SELECT * FROM USER WHERE username = @username)
        INSERT INTO users (username) VALUES (@username)
    

    But seriously, how you're going to know if user visited your website for the first time? You have to insert records in table user, when somebody register on your website, not login.

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

    @gbn answer needs SQL server 2008 or higher. I tried a non-merge way to do it. Ugly perhaps, but it works.

    declare @user varchar(50)
    set @user = 'username'
    insert into users (username) 
    select @user
    where not exists (
     select username 
     from users 
     where username = @user
    );
    

    If you want to test any of the answers, here is the SQL for the table -

    CREATE TABLE [dbo].[users](
        [userid] [int] NULL,
        [username] [varchar](50) NULL
    )
    
    INSERT [dbo].[users] ([userid], [username]) VALUES (1, N'John')
    INSERT [dbo].[users] ([userid], [username]) VALUES (2, N'David')
    INSERT [dbo].[users] ([userid], [username]) VALUES (3, N'Stacy')
    INSERT [dbo].[users] ([userid], [username]) VALUES (4, N'Arnold')
    INSERT [dbo].[users] ([userid], [username]) VALUES (5, N'Karen')
    
    0 讨论(0)
  • 2020-12-05 12:13

    Or using the new MERGE syntax:

    merge into users u
    using ( 
       select 'username' as uname
    ) t on t.uname = u.username
    when not matched then 
      insert (username) values (t.uname);
    
    0 讨论(0)
提交回复
热议问题