Solved

get total record from a table use cmd.ExecuteScalar()

Posted on 2013-11-07
2
383 Views
Last Modified: 2013-11-08
Hi Expert,

I need get total record from a table

sqlScript="Select count(*) from table"

SqlCommand cmd = new SqlCommand(sqlScript, con);
 con.Open();


can I use cmd.ExecuteScalar() to return the number? If yes, how I can do it?

thanks in advance.
0
Comment
Question by:dshi15
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 29

Expert Comment

by:Paul Jackson
ID: 39632450
See the below code :

Dim SQLString As String = “SELECT Count(*) FROM tableName“
Dim yourDBConnection As New SqlConnection()
yourDBConnection.ConnectionString = yourConnectionString

 Dim cmd As New SqlCommand()
Dim recCount As Integer

yourDBConnection.Open()

cmd.Connection = yourDBConnection
 cmd.CommandText = SQLString 
 recCount = Integer.Parse(cmd.ExecuteScalar().ToString)

yourDBConnection.Close()

Open in new window

0
 
LVL 29

Accepted Solution

by:
Paul Jackson earned 500 total points
ID: 39632455
Converted to c# :

string SQLString = "SELECT Count(*) FROM tableName";
SqlConnection yourDBConnection = new SqlConnection();
yourDBConnection.ConnectionString = yourConnectionString;

SqlCommand cmd = new SqlCommand();
int recCount = 0;

yourDBConnection.Open();

cmd.Connection = yourDBConnection;
cmd.CommandText = SQLString;
recCount = int.Parse(cmd.ExecuteScalar().ToString);

yourDBConnection.Close();

Open in new window

0

Featured Post

10 Questions to Ask when Buying Backup Software

Choosing the right backup solution for your organization can be a daunting task. To make the selection process easier, ask solution providers these 10 key questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

635 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question