Question

Asp.Net DataGrid: Page Load is sssslllooowww!

Asked by: jay-are

Hello Experts!

I use this same code for two other Datagrids and I don't have this problem so I figure it's something with the select statement I'm using.  Every page load is taking around 15 seconds.  When I first load the page, edit, cancel, update, change to page 2.  All of it is taking a lot longer than it used to.  I'm not sure what I changed that did this.  Maybe the focus(), but I'm not sure.  Hopefully someone can spot what's causing the slow down.
Here is the code:

<%@ Page Language="VB" Debug="true" Explicit="true" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<%@ import Namespace="System.DateTime" %>
<script runat="server">

    ' TODO: update the ConnectionString and Command values for your application
   
                    Dim ConnectionString As String = "server=sqlserver;uid=uid;PWD=pwd;database=gwpf;"
                    Dim SelectCommand1 As String = "SELECT Distinct [First Name], [Last Name], [Document Date], Reference#, Control#, Acct#, Description, SumAmt, CommentBox, ControlNo, DateDiff(""d"",GetDate(),""Document Date"") as daysold FROM odsc_schedule4 INNER Join Comments1130 on Control# = ControlNo Inner Join odsc_names on [Name ID] = ControlNo Where (ODSC_Schedule4.AutoID IN (Select MAX(ODSC_SChedule4.AutoID) From Odsc_Schedule4 Where ACCT# = '1130' Group By Control#)) ORDER BY daysold ASC"
                    Dim SelectCommand2 As String = "SELECT distinct * FROM Comments1130"
                    Dim isEditing As Boolean = False
                              
                                
                                  
               Sub Page_Load(Sender As Object, E As EventArgs)
   
                        If Not Page.IsPostBack Then
   
                            ' Databind the data grid on the first request only
                            ' (on postback, bind only in editing, paging and sorting commands)
   
                            Yeah()  
                        End If
                   End Sub
   
                    ' ---------------------------------------------------------------
                    '
                    ' DataGrid Commands: Page, Sort, Edit, Update, Cancel, Delete
                    '
   
               Sub DataGrid_ItemCommand(Sender As Object, E As DataGridCommandEventArgs)
   
                        ' this event fires prior to all of the other commands
                        ' use it to provide a more graceful transition out of edit mode
   
                        'CheckIsEditing(e.CommandName)
               End Sub
   
               Sub CheckIsEditing(commandName As String)
   
                        If DataGrid1.EditItemIndex <> -1 Then
   
                            ' we are currently editing a row
                            If commandName = " Cancel " Then
   
                                ' user's edit changes (If any) will not be committed
                                Message.Text = "Your changes have not been saved yet.  Please press update to save your changes, or cancel to discard your changes, before selecting another item."
                                isEditing = True
                             Else If commandName = " Update"  Then
                             Message.Text = "Your changes have been made."
                             isEditing =  True
                            End If
   
                        End If
   
               End Sub
   
               Sub DataGrid_Edit(Sender As Object, E As DataGridCommandEventArgs)
   
                        ' turn on editing for the selected row
   
                       
      Dim CommentBox As Textbox
                          DataGrid1.EditItemIndex = e.Item.ItemIndex
                          Dim scriptJs As String
                                    
      BindGrid()
                              
      CommentBox = CType(DataGrid1.Items(DataGrid1.EditItemIndex).Cells(7).Controls(0), TextBox)
                                    
      scriptJs = "<script language=javascript>" & vbCrLf
      scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').focus();" & vbCrLf
      scriptJs &= "document.getElementById('" & CommentBox.UniqueID & "').select();" & vbCrLf
      scriptJs &= "<" & "/script>"
            If (Not Me.IsStartupScriptRegistered("Startup")) Then
                  Me.RegisterStartupScript("Startup", scriptJs)
            End If
                                    
               End Sub
   
               Sub DataGrid_Update(Sender As Object, E As DataGridCommandEventArgs)
   
                        ' update the database with the new values
   
                        ' get the edit text boxes
                        Dim Control As String = CType(e.Item.Cells(0).Controls(0), textbox).Text
                        Dim CommentBox As String = CType(e.Item.Cells(7).Controls(0), textbox).Text
   
                        ' TODO: update the Command value for your application
                        Dim myConnection As New SqlConnection(ConnectionString)
                        Dim UpdateCommand As SqlCommand = new SqlCommand()
                        UpdateCommand.Connection = myConnection
   
                        If AddingNew = True Then
                            UpdateCommand.CommandText = "INSERT INTO comments1130(ControlNo, CommentBox) VALUES (@Contno, @CommentBox)"
                        Else
                            UpdateCommand.CommandText = "UPDATE comments1130 SET CommentBox = @CommentBox WHERE controlNo = @ContNo"
                        End If
                        UpdateCommand.Parameters.Add("@ContNo", SqlDbType.VarChar, 8000).Value = Control
                        UpdateCommand.Parameters.Add("@CommentBox", SqlDbType.VarChar, 99).Value = CommentBox
   
                        ' execute the command
                        Try
                            myConnection.Open()
                            UpdateCommand.ExecuteNonQuery()
   
                        Catch ex as Exception
                            Message.Text = ex.ToString()
   
                        Finally
                            myConnection.Close()
   
                        End Try
   
                        ' Resort the grid for new records
                        If AddingNew = True Then
                            DataGrid1.CurrentPageIndex = 0
                            AddingNew = false
                        End If
   
                        ' rebind the grid
                        DataGrid1.EditItemIndex = -1
                        BindGrid()
               End Sub
   
               Sub DataGrid_Cancel(Sender As Object, E As DataGridCommandEventArgs)
   
                        ' cancel editing
   
                        DataGrid1.EditItemIndex = -1
                        BindGrid()
   
                        AddingNew = False
   
               End Sub
   
   
               Sub DataGrid_Page(Sender As Object, E As DataGridPageChangedEventArgs)
   
                        ' display a new page of data
   
                        If Not isEditing Then
   
                            DataGrid1.EditItemIndex = -1
                            DataGrid1.CurrentPageIndex = e.NewPageIndex
                            BindGrid()
   
                        End If
   
               End Sub
   
   
    Property AddingNew() As Boolean
   
                        Get
                            Dim o As Object = ViewState("AddingNew")
                            If o Is Nothing Then
                                Return False
                            End If
                            Return CBool(o)
                        End Get
   
                        Set(ByVal Value As Boolean)
                            ViewState("AddingNew") = Value
                        End Set
               End Property
   
   
   
   
         Sub Yeah()
               Const strSQL As String = "usp_SumByControlNo1130"
                        Dim myConnection As New SqlConnection(ConnectionString)
                       Dim mycommand = New SqlCommand(strSQL, myConnection)
                        myConnection.Open()
                        DataGrid1.DataSource = mycommand.ExecuteReader(CommandBehavior.CloseConnection)
                       BindGrid()
          End Sub
   
   
   
               Sub BindGrid()
                        Dim objDataSet As DataSet = New DataSet
                        Dim myConnection As New SqlConnection(ConnectionString)
                        Dim Adapter As SqlDataAdapter = New SqlDataAdapter
   
                        Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand1, myConnection)
                            myConnection.Open()
                           Adapter.Fill(objDataSet,"ODSC_Schedule4")
   
                           Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand2, myConnection)
                            Adapter.Fill(objDataSet,"comments1130")
   
                           
                        DataGrid1.DataSource = objDataSet
                        DataGrid1.Databind()
               End Sub
</script>
<html>
<head>
</head>
<body style="FONT-FAMILY: arial">
    <h4>Bad Checks - 1130&nbsp;&nbsp;&nbsp;<%=Now %><h4 align="right"><input type="button" value="Print Page" name="PrintBtn" onClick="window.print()">
    </h4>
    <hr size="2" />
    <form id="form1" runat="server">
        <asp:datagrid id="DataGrid1" runat="server" enableviewstate="true" ShowFooter="true" Font-Size="10pt" AutoGenerateColumns="False" width="90%" CellSpacing="2" GridLines="None" HorizontalAlign="Center" CellPadding="3" BackColor="White" ForeColor="Black" OnPageIndexChanged="DataGrid_Page" PageSize="12" AllowPaging="true" OnCancelCommand="DataGrid_Cancel" OnUpdateCommand="DataGrid_Update" OnEditCommand="DataGrid_Edit" OnItemCommand="DataGrid_ItemCommand" DataKeyField="Control#">
            <HeaderStyle font-bold="True" forecolor="white" backcolor="#4A3C8C"></HeaderStyle>
            <PagerStyle horizontalalign="Right" backcolor="#C6C3C6" mode="NumericPages" font-size="smaller"></PagerStyle>
            <ItemStyle backcolor="#DEDFDE"></ItemStyle>
            <FooterStyle backcolor="#C6C3C6"></FooterStyle>
            <Columns>
                <asp:BoundColumn DataField="Control#" ReadOnly="False" HeaderText="Cust. Number" />
                <asp:BoundColumn DataField="Reference#" ReadOnly="True" HeaderText="Reference#" />
                <asp:BoundColumn DataField="Document Date" DataFormatString="{0:d}" ReadOnly="True" HeaderText="Document Date" />
                <asp:BoundColumn DataField="Last Name" ReadOnly="True" HeaderText="Last Name" />
                <asp:boundColumn DataField="First Name" ReadOnly="True" HeaderText="First Name" />
                <asp:BoundColumn DataField="SumAmt" DataFormatString="{0:c}" ReadOnly="True" HeaderText="Amount" />
                <asp:BoundColumn DataField="daysold" ReadOnly="True" HeaderText="Days Old" />
                <asp:BoundColumn DataField="CommentBox" HeaderText="Comments" ReadOnly="False" />
                        <asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" CancelText="Cancel" EditText="Edit" ItemStyle-Font-Size="smaller" ItemStyle-Width="7%"></asp:EditCommandColumn>
                        
            </Columns>
        </asp:datagrid>
        <br />
        <br />
        <br />
        <asp:Label id="Message" runat="server" width="80%" forecolor="red" enableviewstate="false"></asp:Label>
    </form>
   
</body>
</html>

Sorry if the code is messy.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-08 at 10:53:12ID20845194
Tags

dataformatstring

Topic

.NET

Participating Experts
4
Points
0
Comments
50

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Datagrid & Dataset
    I'm not very familiar with Dataset usage. well, my objective is to get a datagrid populated with controls like textboxes, comboboxes & buttons. Is there anyway that I can populate the datagrid with all these controls together with some records from the database? How sh...
  2. Problem with SqlDataAdapters and Datasets
    strSQL = "SELECT * FROM Gather_PEllinor" Dim objsqlDA As New SqlDataAdapter() Dim sqlConn As New SqlConnection(ConfigurationSettings.AppSettings("strConn")) Dim sqlCmd As New SqlCommand(strSQL, sqlConn) objsqlDA.SelectCommand = sqlCmd Dim objDS As New D...
  3. new SqlCommand ("INSERT INTO")
    The Dreamweaver code shown below (asp.net 1.1, C#) gives this error on line 30: Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately....
  4. Stored Procedure to SqlDataAdapter to DataGrid
    The Code below is currently how my information is called from the database i want to quickly change this to be called from a stored procedure into the dataAdapter so it is displayed in the same way. Can someone throw me some code on how to do this? Dim ds As New Data...
  5. How to fill a DataSet using a SqlDataAdapter ???
    Hello Experts How to fill a DataSet using a SqlDataAdapter using C#. Thx

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: MattWarePosted on 2004-01-08 at 11:05:39ID: 10073958

Why don't you use stored procedures?

 

by: jay-arePosted on 2004-01-08 at 11:08:35ID: 10073985

I do use a stored procedure.  It's used to get sums for me.  Otherwise this same code(just different field names and mildly different select statement) works just fine for another grid I use.  This one for some reason just takes a while to load.  I was hoping it was something obvious that my eyes aren't seeing.

 

by: mmarinovPosted on 2004-01-08 at 11:09:32ID: 10073996

can you debug your code ( because we can not execute this will all of this sql stuff ) and check the time that your code is executed this lines
 Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand1, myConnection)
                            myConnection.Open()
                           Adapter.Fill(objDataSet,"ODSC_Schedule4")

and then check this

                           Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand2, myConnection)
                            Adapter.Fill(objDataSet,"comments1130")
that is the that you can understand if the problem is with the sqlstatements
if everything is fine - is the remaining time for display the page is too long

How many records do you display ?

B..G

 

by: jay-arePosted on 2004-01-08 at 11:11:35ID: 10074020

How do I do that?  This page wasn't built in VS.Net if you mean making breakpoints and such.  

 

by: mmarinovPosted on 2004-01-08 at 11:17:04ID: 10074078

just make datetime variables that are initialized in the begging of every code block

Dim dt as DateTime = DateTime.Now()
Dim dt1 as DateTime
Dim dt2 as DateTime

Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand1, myConnection)
                            myConnection.Open()
                           Adapter.Fill(objDataSet,"ODSC_Schedule4")
dt1 = DateTime.Now()

Adapter.SelectCommand = _
                            New SqlCommand(SelectCommand2, myConnection)
                            Adapter.Fill(objDataSet,"comments1130")

dt2 = DateTime.Now()

and log them into a file or Write them to the page

HTH
B..G

 

by: jay-arePosted on 2004-01-08 at 11:21:54ID: 10074111

Ok doing that gives me this:  1/1/0001 12:00:00 AM   1/1/0001 12:00:00 AM

I just displayed dt1 & 2 at the top of the page.  What was that for?

 

by: testnPosted on 2004-01-08 at 11:22:14ID: 10074114

I believe that your stored procedure is slow. Please post your stored proc code.

 

by: jay-arePosted on 2004-01-08 at 11:24:32ID: 10074131

The sproc code:

CREATE procedure usp_SumByControlNo1130
As
BEGIN
   
   INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4 Left Join Comments1130 on ODSC_Schedule4.Control# = Comments1130.ControlNo AND Comments1130.ControlNo Is Null
   WHERE odsc_Schedule4.Acct# = '1130' AND NOT EXISTS(SELECT 1 FROM Comments1130 C2 WHERE C2.ControlNo = ODSC_Schedule4.Control# )
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

 
   IF @@ERROR <> 0
   BEGIN
     RAISERROR('Insert into Comments1130 failed', 16, 1)
     RETURN -1
   END  
 
DELETE FROM Comments1130
   WHERE 0 = (
        SELECT SUM(Sched4.Amount)
        FROM ODSC_Schedule4 Sched4
        WHERE Sched4.Control# = Comments1130.ControlNo
        AND Sched4.Acct# = '1130'
   )

RETURN 0

END
GO

I have a table that is meant to have comments written to it from the datagrid.  So the stored procedure sums up the "amount" column per each control# in schedule4 table and writes that amount along with the control# to the comments1130 table.  That way I can link them up and write comments to the comments table.  It should only write the SumAmt and ControlNo if they don't exist in the Comments1130 table.
Hope that makes sense!

 

by: EBatistaPosted on 2004-01-08 at 11:41:25ID: 10074255

That is because you are using a nested ad hoc query, also you are forcing the db engine to do aditional work by using the DISTINCT clause. All that take performance down, and I'm assuming that your db index and primary keys are in right places.
Try to use stored procedures and avoid as much as possible using nested queries.(Also check your indexs a pryjmary keys)

 

by: jay-arePosted on 2004-01-08 at 11:43:18ID: 10074276

I don't have any indexes or primary keys.  I'm just getting started with this and haven't had to use anything like that yet.  

 

by: mmarinovPosted on 2004-01-08 at 11:45:57ID: 10074296

you have to make indexes on your tables so db can be much faster
because in your sp you perform 5 operation before you insert a record in Comments1130
HTH
B..G

 

by: jay-arePosted on 2004-01-08 at 11:48:22ID: 10074314

I've never done anything like that.  Can I index the schedule4 table without affecting anything else that's running?  

 

by: jay-arePosted on 2004-01-08 at 12:15:50ID: 10074519

Ok I was just reading some stuff about indexing.  Should I make the control# column an index since its not updated ever?  Will this help out with the query?  You'll have to excuse my stupidity, I'm new to vs.net and haven't learned anything really about sql at all.

 

by: jay-arePosted on 2004-01-08 at 12:34:46ID: 10074658

My original guess was that the select statement was slowing me down.  I use this sproc on a different datagrid project and it loads up quickly:

CREATE procedure usp_SumByControlNo2
As
BEGIN
   
   INSERT INTO Comments (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4 Left Join Comments on ODSC_Schedule4.Control# = Comments.ControlNo Where odsc_schedule4.Acct# = '1020' AND Comments.ControlNo Is Null
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

   IF @@ERROR <> 0
   BEGIN
     RAISERROR('Insert into Comments failed', 16, 1)
     RETURN -1
   END  

 
   DELETE FROM Comments
   WHERE 0 = (
        SELECT SUM(Sched4.Amount)
        FROM ODSC_Schedule4 Sched4
        WHERE Sched4.Control# = Comments.ControlNo
        AND Sched4.Acct# = '1020'
   )


RETURN 0

END
GO


So why would this other sproc which is almost exactly the same, cause such a decrease in performance?

 

by: testnPosted on 2004-01-08 at 12:55:10ID: 10074838

How many rows are in ODSC_Schedule4 and Comments1130 ?

 

by: testnPosted on 2004-01-08 at 12:56:33ID: 10074855

make sure that you create index on ODSC_Schedule4.Control# and Comments1130.ControlNo

 

by: jay-arePosted on 2004-01-08 at 12:58:03ID: 10074870

Schedule4 table contains = 57338 rows
Comments1130 contains = 19 rows

 

by: testnPosted on 2004-01-08 at 12:58:17ID: 10074872

and odsc_Schedule4.Acct#

 

by: testnPosted on 2004-01-08 at 12:59:07ID: 10074887

Ah ha..... that's why.
What are you trying to achieve by using that stored proc exactly? Maybe I can improve the stored procedure a little bit.

 

by: jay-arePosted on 2004-01-08 at 13:03:21ID: 10074929

The stored procedure needs to get the sum of the amounts in schedule4 table for each control# and write that info out to the comments1130 table.  Once the sum of amount is 0 it needs to then delete that line in comments1130.  

so the control# and sum of "amount" are written to comments1130 where they are either created cause its  a new record or overwrites the old control# and SumAmt cause the value has changed.

Does this make sense?

 

by: EBatistaPosted on 2004-01-08 at 13:03:23ID: 10074930

..as I told you you have this nested query:
"... AND NOT EXISTS(SELECT 1 FROM Comments1130 C2 WHERE C2.ControlNo = ODSC_Schedule4.Control# )" wich is additional  overload for the engine to process and it's not present in the stored procedure you posted above.

 

by: jay-arePosted on 2004-01-08 at 13:05:45ID: 10074949

EBatista:  I agree, but that nested query was added after the slowdown occured.  I've been working on this sproc in the sql forum and I just added that today to make sure the sproc was working properly.

 

by: testnPosted on 2004-01-08 at 13:13:30ID: 10075032

I think that you don't need "AND NOT EXISTS(SELECT 1 FROM Comments1130 C2 WHERE C2.ControlNo = ODSC_Schedule4.Control#" any more since you have "Comments1130.ControlNo Is Null" already. Tell me if I'm wrong.

 

by: testnPosted on 2004-01-08 at 13:15:43ID: 10075056

This statement is also unnecessary as your INSERT statement shouldn't insert the data that has sum amount = 0
DELETE FROM Comments1130
   WHERE 0 = (
        SELECT SUM(Sched4.Amount)
        FROM ODSC_Schedule4 Sched4
        WHERE Sched4.Control# = Comments1130.ControlNo
        AND Sched4.Acct# = '1130'
   )

 

by: jay-arePosted on 2004-01-08 at 13:16:50ID: 10075076

What if ControlNo isn't null?  I'm no sql expert...hell I'm not even a good beginner.  So I don't fully understand the concepts behind how these sprocs work.  
Can I just ignore the fact that the controlno might not exist and just write out the controlno and sumamt each time?

 

by: jay-arePosted on 2004-01-08 at 13:17:56ID: 10075094

Once the data reaches 0 in schedule4 I need some way of removing it from Comments1130 right?

From my udnerstanding that's what the delete method is doing for me.

 

by: testnPosted on 2004-01-08 at 13:25:20ID: 10075197

the controlno should be inserted in even in the first place if sum=0. Unless you insert it by the other stored proc

 

by: testnPosted on 2004-01-08 at 13:26:42ID: 10075209

Yeah..... then why don't you delete the whole table and resum everything from Schedule4 table?

 

by: testnPosted on 2004-01-08 at 13:28:35ID: 10075225

make it look like

CREATE procedure usp_SumByControlNo2
As
BEGIN
   
TRUNCATE TABLE Comments1130

INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

END

 

by: jay-arePosted on 2004-01-08 at 13:29:46ID: 10075233

Like I said, I'm a noob.  I have no idea what the best approach to this is other than the help I get from here.  

You are saying wipe the whole table clean each page load and re-insert the sums?  I have more than just those two columns in comments1130.  I have another column called "CommentBox".  This saves the comments entered by users for each controlno.  

 

by: testnPosted on 2004-01-08 at 13:30:06ID: 10075236

sorry

CREATE procedure usp_SumByControlNo1130
As
BEGIN
   
TRUNCATE TABLE Comments1130

INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

END

Anyway your stored procedure doesn't return the result set. Then you shouldn't be able to bind it to the datagrid though.

Was there any reason to put it in Comments1130 table? Why don't we just retrieve the value from Schedule4 directly?

 

by: testnPosted on 2004-01-08 at 13:30:48ID: 10075247

Oh ic.... then hold on.... new stored procedure is coming....

 

by: testnPosted on 2004-01-08 at 13:37:18ID: 10075296

Hope it will work....

CREATE procedure usp_SumByControlNo1130
As
BEGIN

UPDATE Comments1130    
SET SumAmt = (SELECT SUM(Amount) FROM ODSC_Schedule4 WHERE ODSC_Schedule4.Control#=Comments1130.ControlNo)
   
INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   LEFT JOIN Comments1130 ON ODSC_Schedule4.Control# = Comments1130.ControlNo AND Comments1130.ControlNo Is Null
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

DELETE Comments1130 WHERE SumAmt=0

SELECT * FROM Comments1130

END

 

by: jay-arePosted on 2004-01-08 at 13:38:37ID: 10075305

Ok let me test it and I'll be right back.

 

by: testnPosted on 2004-01-08 at 13:43:03ID: 10075346

Don't forget to create indexes on the following fields

ODSC_Schedule4.Control#
Comments1130.ControlNo
odsc_Schedule4.Acct#

by executing the following statement in Query Analyzer

SET NOCOUNT OFF
IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_schedule4_control')
   DROP INDEX odsc_Schedule4.idx_schedule4_control
GO

CREATE INDEX idx_schedule4_control
   ON odsc_Schedule4 (Control#)
GO
IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_schedule4_acct')
   DROP INDEX odsc_Schedule4.idx_schedule4_acct
GO
CREATE INDEX idx_schedule4_acct
   ON odsc_Schedule4 (acct#)
GO

IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_comment1130_controlno')
   DROP INDEX comment1130.idx_comment1130_controlno
GO
CREATE INDEX idx_comment1130_controlno
   ON comment1130(ControlNo)
GO
 

 

by: testnPosted on 2004-01-08 at 13:43:35ID: 10075352

sorry... the stored procedure is not correct.

CREATE procedure usp_SumByControlNo1130
As
BEGIN

UPDATE Comments1130    
SET SumAmt = (SELECT SUM(Amount) FROM ODSC_Schedule4 WHERE ODSC_Schedule4.Control#=Comments1130.ControlNo AND odsc_Schedule4.Acct# = '1130')
   
INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   LEFT JOIN Comments1130 ON ODSC_Schedule4.Control# = Comments1130.ControlNo AND Comments1130.ControlNo Is Null
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

DELETE Comments1130 WHERE SumAmt=0

SELECT * FROM Comments1130

END

 

by: jay-arePosted on 2004-01-08 at 13:44:59ID: 10075363

It is working.  The SumAmt is correct.  It's giving me the wrong date for each posting though.

So if there are two entries to Schedule4 like so:
8/17/03  2000 454593
12/22/03 -600  454593

Then it was using the more recent date.  Now the amounts are correct but its using the original posted date.  I think that was the reason for the nested query I was using.  Not sure if this is a big problem but it would be nice to have the accurate date as I use it for a "daysold" field.

 

by: jay-arePosted on 2004-01-08 at 13:45:42ID: 10075368

oh ok

let me try the new one  :)

 

by: jay-arePosted on 2004-01-08 at 13:46:55ID: 10075376

Don't forget to create indexes on the following fields

ODSC_Schedule4.Control#
Comments1130.ControlNo
odsc_Schedule4.Acct#

by executing the following statement in Query Analyzer

SET NOCOUNT OFF
IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_schedule4_control')
   DROP INDEX odsc_Schedule4.idx_schedule4_control
GO

CREATE INDEX idx_schedule4_control
   ON odsc_Schedule4 (Control#)
GO
IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_schedule4_acct')
   DROP INDEX odsc_Schedule4.idx_schedule4_acct
GO
CREATE INDEX idx_schedule4_acct
   ON odsc_Schedule4 (acct#)
GO

IF EXISTS (SELECT name FROM sysindexes
      WHERE name = 'idx_comment1130_controlno')
   DROP INDEX comment1130.idx_comment1130_controlno
GO
CREATE INDEX idx_comment1130_controlno
   ON comment1130(ControlNo)
GO


??  You've lost me there.  Can I do this inside the sproc or do I need to go in and setup the indexes before I use the new sproc?  

 

by: testnPosted on 2004-01-08 at 13:54:14ID: 10075432

you have to do it only once and for all :) don't have to put it in the stored proc.

 

by: jay-arePosted on 2004-01-08 at 13:54:58ID: 10075436

Not sure if I've done this right but I ran the indexing code you put up first in the query analzyer and it said:  The command(s) completed successfully.

Then I ran the datagrid with the new sproc.  The load time was just as slow as before, had the correct amounts, but is still using the wrong dates and stuff.  

 

by: jay-arePosted on 2004-01-08 at 14:00:42ID: 10075500

Everytime I load the page it writes out a whole new set of records.  So instead of 19, it's 38.  Keeps adding and adding.

 

by: testnPosted on 2004-01-08 at 14:25:44ID: 10075788

My bad....

it should be

INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   LEFT JOIN Comments1130 ON ODSC_Schedule4.Control# = Comments1130.ControlNo AND Comments1130.SumAmt Is Null
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

 

by: testnPosted on 2004-01-08 at 14:53:19ID: 10076007

you change this from

Dim SelectCommand1 As String = "SELECT Distinct [First Name], [Last Name], [Document Date], Reference#, Control#, Acct#, Description, SumAmt, CommentBox, ControlNo, DateDiff(""d"",GetDate(),""Document Date"") as daysold FROM odsc_schedule4 INNER Join Comments1130 on Control# = ControlNo Inner Join odsc_names on [Name ID] = ControlNo Where (ODSC_Schedule4.AutoID IN (Select MAX(ODSC_SChedule4.AutoID) From Odsc_Schedule4 Where ACCT# = '1130' Group By Control#)) ORDER BY daysold ASC"

to

Dim SelectCommand1 As String = "SELECT [First Name], [Last Name], [Document Date], Reference#, o.Control#, Acct#, Description, SumAmt, CommentBox, ControlNo, DateDiff(""d"",GetDate(),[Document Date]) as daysold
DateDiff(""d"",GetDate(),[Document Date]) as daysold FROM
odsc_schedule4 o
INNER JOIN
(SELECT Control#, MAX(AutoID) FROM ODSC_Schedule4 WHERE o.Acct# = '1130' GROUP BY Control#) a
ON
a.Control# = o.Control# AND a.AutoID = o.AutoID AND o.Acct# = '1130'
INNER JOIN
Comments1130 c
ON
o.Control# = c.ControlNo
Inner Join odsc_names on [Name ID] = ControlNo
"

remove all new lines stuff..... I wrapped it to make it easier to read.

 

by: jay-arePosted on 2004-01-09 at 08:31:36ID: 10081212

testn:  The new select statement is crazy.  Are you asigning alias's to it?  I'm guessing that's what the o's and a's are for?  I've never done this so I'd like to understand it.

I get this error when I load the page:

Exception Details: System.Data.SqlClient.SqlException: The column prefix 'o' does not match with a table name or alias name used in the query.

Source Error:


Line 189:                            New SqlCommand(SelectCommand1, myConnection)
Line 190:                            myConnection.Open()
Line 191:                           Adapter.Fill(objDataSet,"ODSC_Schedule4")
Line 192:                          
Line 193:    
 

Source File: c:\inetpub\wwwroot\ASPX\New\datagrid1130.aspx    Line: 191

 

by: jay-arePosted on 2004-01-09 at 09:20:10ID: 10081658

The stored procedure is still recreating each record every time it's executed.

Maybe I screwed it up somehow:

CREATE procedure usp_SumByControlNo1130
As
BEGIN

Update Comments1130
Set SumAmt = (Select Sum(Amount) From Odsc_Schedule4 Where Odsc_schedule4.Control# = Comments1130.ControlNo And Odsc_Schedule4.Acct# = '1130')
   
INSERT INTO Comments1130 (ControlNo, SumAmt)
   SELECT  Control#, Sum(Amount)
   FROM ODSC_Schedule4
   LEFT JOIN Comments1130 ON ODSC_Schedule4.Control# = Comments1130.ControlNo AND Comments1130.SumAmt Is Null
   WHERE odsc_Schedule4.Acct# = '1130'
   GROUP BY Control#
   HAVING Sum(Amount) <> 0

DELETE Comments1130 WHERE SumAmt=0


END
GO

 

by: jay-arePosted on 2004-01-12 at 09:19:20ID: 10096227

*crickets*

Hello?

 

by: jay-arePosted on 2004-02-03 at 13:34:30ID: 10265377

:(

The page actually times out now.  Can't even get it to load.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...