SQL : Insert if Not Exist

Asked

Viewed 46 times

0

Doubt:

I made a form in C# connecting to the bank
I wanted to know how I can include in this query the if not exits @param1
In order to avoid duplication.

Link to the Reference Code:

Mysql: Insert record if not exists in table [Uplicate]

Basis of my code:

public void InsertDataToDb()
{
    string connectionString = ConfigurationManager.ConnectionStrings["connection"].
        ConnectionString;
    var records = GetRecords();

    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();

        SqlCommand cmd =
            new SqlCommand(
                "INSERT INTO TableName (param1, param2, param3) " +
                " VALUES (@param1, @param2, @param3)");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;
        cmd.Parameters.Add("@param1", DbType.String);
        cmd.Parameters.Add("@param2", DbType.String);
        cmd.Parameters.Add("@param3", DbType.String);

        foreach (var item in records)
        {
            cmd.Parameters[0].Value = item.param1;
            cmd.Parameters[1].Value = item.param2;
            cmd.Parameters[2].Value = item.param3;

            cmd.ExecuteNonQuery();
        }

        conn.Close();
    }
}

1 answer

1


You can add a WHERE to his insert making this check, as in that reply:

...
new SqlCommand(
    "INSERT INTO TableName (param1, param2, param3) " +
    "VALUES (@param1, @param2, @param3) " +
    "WHERE NOT EXISTS (SELECT 1 FROM TableName WHERE @param1 <> param1)");
...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.