Solved

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

Posted on 2013-11-07
2
349 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
Comment Utility
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
Comment Utility
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Everyone has problem when going to load data into Data warehouse (EDW). They all need to confirm that data quality is good but they don't no how to proceed. Microsoft has provided new task within SSIS 2008 called "Data Profiler Task". It solve th…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
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.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now