INSERT INTO如果不存在SQL服务器

时间:2012-03-10 18:15:27

标签: c# sql sql-server database-design

我的数据库结构如下:

用户

userid (Primary Key)
username

groupid (PK)
groupName

user_groups

userid (Foreign Key)
groupid (Foreign Key)

用户首次登录时,我希望将他们的信息添加到users表中。所以基本上我想要的逻辑是

if (//users table does not contain username)
{
INSERT INTO users VALUES (username);
}

如何使用SQL Server / C#智能地执行此操作?

8 个答案:

答案 0 :(得分:19)

或使用新的MERGE语法:

merge into users u
using ( 
   select 'username' as uname
) t on t.uname = u.username
when not matched then 
  insert (username) values (t.uname);

答案 1 :(得分:10)

基本上你可以这样做:

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

但严重的是,您是如何知道用户是否第一次访问您的网站? 当有人在您的网站上注册而不登录时,您必须在表用户中插入记录。

答案 2 :(得分:4)

IF NOT EXISTS (select * from users where username = 'username')
BEGIN
    INSERT INTO ...
END

答案 3 :(得分:3)

我首先在db上创建一个存储过程来进行检查并在必要时插入:

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

然后在应用程序上调用此过程的方法

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(); }
    }
}

答案 4 :(得分:1)

以下代码是一种方法,如果用户已经存在则返回0并返回刚刚添加的新用户 ID

  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;
        }

答案 5 :(得分:1)

@gbn 回答需要SQL Server 2008或更高版本。我尝试了一种不合并的方式来做到这一点。也许丑陋,但它的确有效。

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

如果你想测试任何答案,这里是表格的SQL -

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')

答案 6 :(得分:0)

这是一个解决您问题的(可能过于简化的)示例。请注意,最好使用参数来防止注入攻击,尤其是在验证用户时。

CREATE PROCEDURE AddUser
  @username varchar(20)
AS
  IF NOT EXISTS(SELECT username FROM users WHERE username=@username)
    INSERT INTO users(username) VALUES (@username)

答案 7 :(得分:0)

有一个简单的解决方案!我在此post中找到了它!

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

在我的项目中,我需要使用2个值。所以我的代码是:

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

希望这会有所帮助!