如果SQL server不存在,请插入INTO
本文关键字:插入 INTO 不存在 SQL server 如果 | 更新日期: 2023-09-27 18:27:17
我有一个数据库结构如下:
用户
userid (Primary Key)
username
组
groupid (PK)
groupName
用户组
userid (Foreign Key)
groupid (Foreign Key)
用户第一次登录时,我希望将他们的信息添加到用户表中。因此,从本质上讲,如果
if (//users table does not contain username)
{
INSERT INTO users VALUES (username);
}
如何使用SQLServer/C#智能地做到这一点?
或者使用新的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);
基本上你可以这样做:
IF NOT EXISTS (SELECT * FROM USER WHERE username = @username)
INSERT INTO users (username) VALUES (@username)
但说真的,如果用户是第一次访问你的网站,你怎么知道呢?当有人在你的网站上注册时,你必须在表用户中插入记录,而不是登录。
IF NOT EXISTS (select * from users where username = 'username')
BEGIN
INSERT INTO ...
END
我会首先在数据库上创建一个存储的proc来进行检查,并在必要时插入:
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(); }
}
}
注意将其作为备选/历史记录,但为了正确起见,正确的方法是使用Merge语句,请参阅答案https://stackoverflow.com/a/9649040/167304或签出MS文档https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver15
有一个简单的解决方案!我在这个帖子里找到的!
INSERT INTO users (Username)
SELECT ('username')
WHERE NOT EXISTS(SELECT * FROM users WHERE Username= 'username')
在我的项目中,我需要使用两个值。所以我的代码是:
INSERT INTO MyTable (ColName1, ColName2)
SELECT 'Value1','Value2'
WHERE NOT EXISTS
(SELECT * FROM MyTable WHERE ColName1 = 'Value1' AND ColName2= 'Value2')
希望这能有所帮助!
以下代码是一个方法,如果用户已经存在,则返回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;
}
@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')
这里有一个(可能过于简单化了)例子来解决您的问题。请注意,最好始终使用参数来防止注入攻击,尤其是在验证用户时。
CREATE PROCEDURE AddUser
@username varchar(20)
AS
IF NOT EXISTS(SELECT username FROM users WHERE username=@username)
INSERT INTO users(username) VALUES (@username)