C# sql 查询 if() else() 基于结果 null?

标签 c#

标题可能有点困惑,但基本上我想做一些类似的事情,

string sql = "select dataset1 from dbo.ste where project = 'whatever' and date = '11/30/10'";
        SqlConnection con = new SqlConnection("Data Source= Watchmen ;Initial Catalog= doeLegalTrending;Integrated Security= SSPI");
        con.Open();
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();

if(cmd "is not null")
{
//do this string
}
else
{

//do this one
}

显然 cmd "is not null") 不是真实的,但我想你们可能明白这一点。

最佳答案

我不明白为什么当问题中的查询是 SELECT 语句时每个人都在尝试使用 ExecuteNonQuery 或 ExecuteScalar。如果它是一个存储过程调用,它根据值的存在来处理 INSERT 与 UPDATE 的逻辑,那么 ExecuteScalar 就有意义,因为您可以从存储过程返回任何您想要的单个值。

但是,鉴于问题的结构,我倾向于将此作为答案。

// Automatically dispose  the connection when done
using(SqlConnection connection = new SqlConnection(sqlConnection.ConnectionString)) {
    try {
        connection.Open();

        // query to check whether value exists
        string sql =  @"SELECT dataset1 
                        FROM   dbo.ste 
                        WHERE  project = 'whatever'
                               AND date = '2010-11-30'";

        // create the command object
        using(SqlCommand command = new SqlCommand(sql, connection)) {
            using(SqlDataReader reader = command.ExecuteReader()) {
                // if the result set is not NULL
                if(reader.HasRows) {
                    // update the existing value + the value from the text file
                }
                else {
                    // insert a value from a text file
                }
            }
        }
    }
    finally {
        // always close connection when done
        if(connection.State != ConnectionState.Closed) {
            connection.Close();
        }
    }
}

您可以更改查询以使用 WHERE EXISTS如果您不想流回完整的匹配项,但从它的声音来看,无论如何您最多只有 1 个匹配项。

关于C# sql 查询 if() else() 基于结果 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4318582/

相关文章:

c# - 当源和目标是同一个数组时,Array.Copy 是否安全?

c# - 带有嵌套列表的 TreeView

c# - SQL Server 列到组合框?

c# - TLSharp Fetch 组列表问题

c# - 向数据集添加一列 C#

c# - LINQ to Entities 无法识别方法 'System.String get_Item (System.String)' ,

c# - 登录到 jira soap api

c# - 如何解决无效对象名称 'dbo.AspNetUsers' 错误?

C# DateTime.ToString "o"格式在 Azure 上返回不同的字符串

c# - 是否通过对象初始化设置属性 : Any difference ?