Solved

Returning a value From SQL

Posted on 2006-11-12
6
224 Views
Last Modified: 2008-03-06
ok here is my code which as you will see does not work,
All I need is to store the record count into a variable I just dont know how to do that with ASP.net

            string QiD = (string)Request.QueryString["testid"];
            SqlDataReader dtr;
            SqlConnection oConn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\quiz.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("usp_Question_Count", oConn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter workParam = new SqlParameter("@QuizId", QiD);
            workParam.Value = QiD;
            cmd.Parameters.Add(workParam);
            // With...
           
            oConn.Open();
            dtr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            // get the total number of products
            int iReturn = Convert.ToInt32(cmd.Parameters["Count"].Value);
           
            int testID = int.Parse(Request.QueryString["testid"]);


and here is my Stored Procedure

ALTER PROCEDURE dbo.usp_Question_Count
     @QuizId int
     /*@QuestionCount int OUTPUT
     
     (
     @parameter1 int = 5,
     @parameter2 datatype OUTPUT
     )
     */
     
AS
DECLARE @Count AS int
     /* SET NOCOUNT ON */
     /*DECLARE @Count AS int*/
     SELECT @Count=COUNT(QuestionOrder) FROM Question WHERE (QuizID = @QuizId)
    /* SET @QuestionCount = @Count*/
      RETURN @Count


0
Comment
Question by:Scripter25
  • 3
  • 3
6 Comments
 
LVL 29

Accepted Solution

by:
Nightman earned 500 total points
ID: 17926712
Your stored proc looked fine (cleaned up a little)

ALTER PROCEDURE dbo.usp_Question_Count
     @QuizId int
     @QuestionCount int OUTPUT
   
AS
 SELECT @QuestionCount=COUNT(QuestionOrder) FROM Question WHERE (QuizID = @QuizId)


BUT what you want is to run ExecuteNonQuery (you don't really need a data reader here, it's an overhead) and you need to define the @QuestionCount parameter as output - then you can query it (bear with me - I don't have a compiler with me to check syntax, so this is all from memory):

            string QiD = (string)Request.QueryString["testid"];
            SqlConnection oConn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\quiz.mdf;Integrated Security=True;User Instance=True");
            SqlCommand cmd = new SqlCommand("usp_Question_Count", oConn);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameter workParam = new SqlParameter("@QuizId", SqlDbType.Int);
            workParam.Value = QiD;
            cmd.Parameters.Add(workParam);
             SqlParameter countParam = new SqlParameter("@QuestionCount", SqlDbType.Int);
            countParam.Direction=ParameterDirection.Output
            cmd.Parameters.Add(workParam);
            cmd.Parameters.Add(countParam);
     
            oConn.Open();
            cmd.ExecuteNonQuery();
            // get the total number of products
            int iReturn = Convert.ToInt32(cmd.Parameters["QuestionCount"].Value);
           oConn.Close();
0
 
LVL 29

Expert Comment

by:Nightman
ID: 17926730
You were on the right track - there is no need for a datareader or a dataset if you can simply return an output parameter - and it's far more efficient (less load on SQL, less load on the network, less load in memory and CPU on the web server).

Don't forget to put a try catch finally around this and make sure that the oConn.Close() method happens there (SQL connections use pooling by default, and DON'T get implicitly closed. There may be an overload for the ExecuteNonQuery() to do CommandBehavior.CloseConnection, but wihtout the ompiler I can't check ;)

You can find some good examples at:

http://www.codersource.net/microsoft_data_access_application_block_azam.html
http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
and the MSDN
0
 

Author Comment

by:Scripter25
ID: 17926747
You are the man I only had to fix two very small things in your script above

 //cmd.Parameters.Add(workParam); It gave an error
also
I had to put the @ on
int iReturn = Convert.ToInt32(cmd.Parameters["@QuestionCount"].Value);


Hey hope you are going to be on for awhile tonight I am trying to get this part of this project done tonight and will probably have atleast 1 if not two or 3 500 point questions coming through
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 29

Expert Comment

by:Nightman
ID: 17926759
0
 

Author Comment

by:Scripter25
ID: 17926820
Yeah the last one has been marked to be removed for sometime now I just posted in the community support area for a cleanup of that and one other one.


Thank you again
0
 

Author Comment

by:Scripter25
ID: 17926877
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

746 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

14 Experts available now in Live!

Get 1:1 Help Now