简体   繁体   中英

Check if value exists or not before insert

I have to insert a value and before inserting i have to check either a value exists or not. how can i achieve it in a simple way?

public int AddCountry(string cntName)
{
    try
    {
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }

        SqlCommand sqlCmd = new SqlCommand("INSERT INTO Country VALUES(" + 
            cntName + ")", conn);
        sqlCmd.Parameters.AddWithValue("@Country_Name", cntName);
    }
    catch (Exception)
    {   
        throw;
    }
}

ignoring some of the other issues in your code, you should look at IF NOT EXISTS

IF NOT EXISTS
    (
    SELECT 1
    FROM Country 
    WHERE Country_Name = @countryName
    )
INSERT INTO Country (Country_Name) values (@countryName)

First thing to do would be to move the insert SQL into a stored procedure. This would give you 2 benefits - a single DB call to do the work and it would get rid of the SQL Injection problem you have with the code supplied.

Then in the stored procedure, check for the value before inserting.

DECLARE @count INT
SELECT @count = COUNT(*) FROM Country WHERE Name = @countryName
IF @count <= 0 BEGIN
 // INSERT HERE
END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM