Solved

Returning a value From SQL

Posted on 2006-11-12
6
242 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

Question has a verified solution.

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

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
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.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

770 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