C # sql query if () else () by null results?

The name is probably confusing, but basically I want to do something in line with this,

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
}

Obviously cmd "is not null") is not real, but I think you guys could understand the gist.

+5
source share
5 answers

I don’t understand why everyone is trying to use ExecuteNonQuery or ExecuteScalar when the query in question is a SELECT statement. If it was a call to a stored procedure that took care of the INSERT and UPDATE logic based on the existence of the value, ExecuteScalar would make sense, because you can return any single value from the stored procedure.

However, given the structure of the question, I am inclined to this as an answer.

// 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 .

+7

, , :

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

, ExecuteScalar:

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

, var result = cmd.ExecuteScalar();, if (result == DBNull.Value).

+2

ExecuteNonQuery ( ) . , , ( ) , , .

+1

:

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

All Articles