查找Query的简单方法返回SQL Server的行数

时间:2016-04-18 12:14:52

标签: c# sql sql-server

这是Windows后端服务,我需要将每个动作写入日志文件。我想找到SQL Select Query返回的行数,我想将该记录写入Log文件。

示例:

  

选择语句返回35行。

记录条目

4/18/2016 4:54:47 PM : -Class--> CallBackOption| -Function--> UpdateServiceIBC| -Message--> SELECT * FROM CALLBACKOPTION WHERE ProccessStatus = 0
4/18/2016 4:54:47 PM : -Class--> Update Service Call Back Option| -Function--> UpdateServiceCall Back Option| -Message--> ***** New Record *****
4/18/2016 4:54:47 PM : -Class--> Update Service Call Back Option| -Function--> UpdateServiceCall Back Option| -Message--> Formatting ANI[sip:03022745301@172.29.0.2] TO Contact[03022745301] against CA[400001358877]
4/18/2016 4:54:47 PM : -Class--> Update Service Call Back Option| -Function--> UpdateServiceCall Back Option| -Message--> Checking for Contact Number
4/18/2016 4:54:47 PM : -Class--> Update Service Call Back Option| -Function--> UpdateServiceCall Back Option| -Message--> Contact Number[9903022745301] call process Chain ID[1]
4/18/2016 4:54:47 PM : -Class--> Update Service Call Back Option| -Function--> UpdateServiceCall Back Option| -Message--> Updating AutoCall Back Option

代码段:

     string query = "SELECT * FROM CALLBACKOPTION WHERE ProccessStatus = 0";
                    Log.WriteErrorLog("CallBackOption", "UpdateServiceIBC", "SELECT * FROM CALLBACKOPTION WHERE ProccessStatus = 0");
                    using (SqlConnection con = new SqlConnection(ConnectionString))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand(query, con);
                        SqlDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            Log.WriteErrorLog("Update Service Call Back Option", "UpdateServiceCall Back Option", "***** New Record *****");
                            string dateTime = reader["DateTime"].ToString();
                            string ANI = reader["ANI"].ToString();
                            string contact = ANI.Substring(ANI.IndexOf(":") + 1, ANI.IndexOf("@") - 4);
                            string CA = reader["CUSTOMER_ACCOUNT"].ToString();
Log.WriteErrorLog("","", "Formatting ANI[" + ANI + "] TO Contact[" + contact + "] against CA[" + CA + "]");

2 个答案:

答案 0 :(得分:2)

我眼中最简单的方法(如果你在任何情况下都在阅读数据):

[...]
int counter=0;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()){
    counter++;
    [...]
}

变量counter将显示正在处理的行数。

是否还有其他CRUD声明?

答案 1 :(得分:0)

如果您只想知道可以使用的行数:

cmd.ExecuteNonQuery();

这将对Connection执行一条SQL语句,并返回受影响的行数。

MSDN