c# - 插入前检查值是否存在

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

最佳答案

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

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

关于c# - 插入前检查值是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20497000/

相关文章:

c# - WPF 图像查看器示例应用程序

c# - Silverlight 的几何绘图和操作选项

java - SQL group by 替换不同的值

c# - 使图像的 ObservableCollection 很好地显示在屏幕上

c# - 对空类使用方法

c# - 关于代码放置的变量问题

mysql - 将查询结果优化为使用文件排序;

sql - 我可以使用别名作为过滤器吗? T-SQL 2012

java - 让 ExecuteBatch 执行得更快

mysql - 错误1005(HY000): Can't create table 'shrewd_db.alert_disable_register' (errno: 150)