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

时间:2010-11-30 21:00:11

标签: 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“不是空的”)不是真的,但我想你们可能会明白这一点。

5 个答案:

答案 0 :(得分:7)

我不明白为什么当问题中的查询是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个匹配。

答案 1 :(得分:3)

如果要检查是否有匹配的记录,可以计算它们:

string sql = "select count(*) from dbo.ste where project = 'whatever' and date = '11/30/10'";

要获得结果,请使用ExecuteScalar方法:

int cnt = Convert.ToInt32(cmd.ExecuteScalar());

答案 2 :(得分:2)

看起来您想var result = cmd.ExecuteScalar();,然后比较if (result == DBNull.Value)

答案 3 :(得分:1)

ExecuteNonQuery返回受影响的行数(如果未选择某些选项)作为整数。因此,您可以验证计数是否等于(或大于)某些成功条件或执行标量并从查询中返回一个值以表示成功。

答案 4 :(得分:0)

试试这个:

string sql = "select COUNT(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);
int count = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();

if(count != 0)
{
//do this string
}
else
{

//do this one
}