0

我正在使用存储过程对象执行一个查询。我想在执行查询后检索 Select 语句中返回的行数。

我在使用之间感到困惑ExecuteReader() & ExecuteScalar()

public static int getDuplicateEvent(string ATM, string Fault1, string Fault2, ref SqlConnection Connection)
{
    string sQuery = "";
    int result = 0;
    try
    {
        sQuery = /*Query With Format Select Code From A Union Select Code From B */
        using (SqlStoredProcedure sspObj = new SqlStoredProcedure(sQuery, Connection, CommandType.Text))
        {
            result = (int)sspObj.ExecuteScalar();
            sspObj.Dispose();
        }
    }
    catch (Exception xObj)
    {
        result = 0;
    }
    return result;
}
4

2 回答 2

3

ExecuteScalar returns the first column of the first row of the results

ExecuteReader returns a datareader that can be iterated through

You could also use ExecuteNonQuery or Fill into a DataSet or DataTable

Assuming you want the rows and the count, I would fill a DataTable and count the rows using Rows.Count

于 2012-10-09T13:02:13.590 回答
1

在以下行中创建查询:

SELECT COUNT(*) FROM dbo.Users

然后使用ExecuteScalar接收行数。

ExecuteScaler执行查询,并返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。

ExecuteReader将 CommandText 发送到 Connection 并构建 SqlDataReader。

于 2012-10-09T13:07:15.047 回答