I have a database structured as follows:
users
userid (Primary Key)
username
group
There is a simple solution! I Found it in this post!
INSERT INTO users (Username)
SELECT ('username')
WHERE NOT EXISTS(SELECT * FROM users WHERE Username= 'username')
In my project I needed to do it with 2 values. So my code was:
INSERT INTO MyTable (ColName1, ColName2)
SELECT 'Value1','Value2'
WHERE NOT EXISTS
(SELECT * FROM MyTable WHERE ColName1 = 'Value1' AND ColName2= 'Value2')
Hope this helps!
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