插入前检查值是否存在

时间:2013-12-10 14:24:26

标签: c# sql

我必须插入一个值,在插入之前我必须检查值是否存在。我怎样才能以简单的方式实现它?

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

2 个答案:

答案 0 :(得分:4)

忽略代码中的其他一些问题,你应该看看IF NOT EXISTS

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

答案 1 :(得分:3)

首先要做的是将插入SQL移动到存储过程中。这将为您带来2个好处 - 单个数据库调用来完成工作,它将消除您提供的代码所带来的SQL注入问题。

然后在存储过程中,在插入之前检查值。

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