Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2013-11-07
2
Medium Priority
?
389 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 2000 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

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

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.
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
Via a live example, show how to shrink a transaction log file down to a reasonable size.

705 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