Solved

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

Posted on 2013-11-07
2
364 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
  • 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

Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

Question has a verified solution.

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

Suggested Solutions

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

810 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