Displaying row count from SQL server to program

倾然丶 夕夏残阳落幕 提交于 2019-12-16 18:02:11

问题


I am working on a program on C# VS 2015. In my program, there is a big text display box that generates message when I click a certain button to indicate an action is being performed.

Anyway, I have a SQL script where it has queries for COUNT for some tables. I can run that script through my program. However , since row count displays total number of rows for a table and can only be viewed inside SQL server. I was wondering is there a way to execute my script and also display the ROW COUNTS inside my program at the big text display box?

Here is a snippet of my code to run that SQL script:

    /*  open sql connection to execute SQL script: Row count script*/
    try
    {
        using (SqlConnection con = new SqlConnection(constr))
        {
            con.Open();
            FileInfo file = new FileInfo(DIRECTORY OF THE SCRIPT);
            string script = file.OpenText().ReadToEnd();
            Server server = new Server(new ServerConnection(con));
            server.ConnectionContext.ExecuteNonQuery(script);
            Display("ABCDG"); -- to display message on text display
            con.Close();



        }

    }
    catch (Exception ex)
    {

        textBox1.AppendText(string.Format("{0}", Environment.NewLine));
        textBox1.AppendText(string.Format("{0} MainPage_Load() exception - {1}{2}", _strThisAppName, ex.Message, Environment.NewLine));
        Display(ex.Message + ""); -- display message to textbox
        textBox1.AppendText(string.Format("{0}", Environment.NewLine));
        Debug.WriteLine(string.Format("{0} MainPage_Load() exception - {1}", _strThisAppName, ex.Message));


    }

Here is a snapshot of my program:

  https://i.stack.imgur.com/uKP99.png

回答1:


If you have multiple queries in your script file, then you should enhance your script with @rowsAffected variable as shown in T-SQL below. Then, in your C# code you will need to call ExecuteScalar to get the detailed rows affected by your script.

**Script file with @rowsAffected variable logic**

--add following variable at start of your script
DECLARE @rowsAffected VARCHAR(2000);

INSERT INTO [dbo].[Products] ([ProductName]) VALUES ('sun1'),('sun2'),('sun3');

--after each query that you want to track, include the following line
SET @rowsAffected = 'Products : ' + CAST(@@rowcount AS varchar(20));

UPDATE [dbo].[newTable]   SET [ColB] = 'b' ,[ColC] = 'd',[ColD] = 'e'  ,[ColE] = 'f'  WHERE ColA='a';

 --after each query that you want to track, include the following line
SET @rowsAffected = @rowsAffected + ', newTable : ' + CAST(@@rowcount AS varchar(20));

-- add the query below at end of your script 
SELECT @rowsAffected;

You will have to read the text from your script file, as you are doing in your code, and then create a command object using the text read from file before executing the code in snippet below.

C# code to execute above script

string rowsAffected =(string) command.ExecuteScalar();
//you can now use rowsAffected variable in any way you like
//it will contain something like Table1 : 4, Table2 : 6

Detailed C# code using your original code

    using (SqlConnection con = new SqlConnection(constr))
    {

        FileInfo file = new FileInfo(DIRECTORY OF THE SCRIPT);
        string script = file.OpenText().ReadToEnd();

        SqlCommand command = new SqlCommand(script, con);
        command.CommandType = CommandType.Text;
        try
        {
            con.Open();
            string rowsAffected =(string) command.ExecuteScalar();
            Display( rowsAffected);
            con.Close();
        }
        catch (Exception ex)
        {
            con.Close();
            Display(ex.Message);
        }
    }



回答2:


As Tetsuya Yamamoto said in his comment, what you are looking for is the use of the ExecuteScalar method. Your code change may look something like the below

     int numOfRows = (int)server.ConnectionContext.ExecuteScalar(script);
     string displayText =  numOfRows.ToString();
     Display(displayText); -- to display message on text display
     con.Close();

The cast ToString is just for safety purposes as I am unsure how your Display will handle an int value



来源:https://stackoverflow.com/questions/47469585/displaying-row-count-from-sql-server-to-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!