Solved

Example of how to do a SQL Server YTD Summary from a Table

Posted on 2004-08-18
9
392 Views
Last Modified: 2012-06-27
Hello Gurus,

This is urgent.

I need a (Best Practice) example of a function on how to do a YTD Summary from a SQL Server Table from an Asp.net web form using VB.  I will then need to place them into 3 variables: YtdHrs, YtdQty and Ytd(OnOrder)
The query I would use would be:

SELECT Sum(Hrs), Sum(Qty), Sum(OnOrder) From Orders Where EnterDate > #12/31/2003#

(I'm not sure if my date syntax is correct. Please correct me if its wrong)

Of particular importance to me is how to extract the information from the returned dataset and placing them into the variables.

Thank you!

Ted
0
Comment
Question by:tcalbaz
  • 6
  • 2
9 Comments
 
LVL 17

Expert Comment

by:AerosSaga
Comment Utility
Try this: SELECT Sum(Hrs) AS Hours, Sum(Qty) AS Quantity, Sum(OnOrder) As OnOrder From Orders Where EnterDate > '12/31/2003'

Then create your dataset from it and bind it to a datagrid, etc.  you will be able to reference the values using the standard datagrid terminologyr:
eg....
dg.items("Hours")
dg.items("Quantity")
dg.items("OnOrder")

Regards,

Aeros
0
 
LVL 25

Expert Comment

by:nauman_ahmed
Comment Utility
'Set the value of  and SQLConnection SQLDataAdapter
strSQL = "SELECT Sum(Hrs) AS Hours, Sum(Qty) Quantity, Sum(OnOrder) OnOrder From Orders Where EnterDate > #12/31/2003#"
MySQLDataAdapter.Fill(strSQL,"YTD_SUMMARY")

if (MySQLDataAdapter.Tables["YTD_SUMMARY"].Rows.Count >  0) then
   Dim dt As DataTable = MySQLDataAdapter.Tables["YTD_SUMMARY"]
   Dim dr As DataRow = dt.Rows[0]
   Response.Write("Hours: " & dr["Hours"])
   Response.Write("Quantity: " & dr["Quantity"])
   Response.Write("OnOrder: " & dr["OnOrder"])
end if

HTH, :)

Best, nauman
0
 
LVL 1

Author Comment

by:tcalbaz
Comment Utility
Nauman,
I think your example comes close to what I need to do.  Below is my the actual function I am constructing ased on your idea.  But it is stopping at my Adapter Reference.  Any Suggestions?
Thank You

Ted

-----------------------------------------------------------
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        'Set the value of  and SQLConnection SQLDataAdapter
        Dim MyDataSet As DataSet
        MyDataSet = New DataSet("aNewDataSet")

        Dim MyAdapter As SqlClient.SqlDataAdapter
        Dim MyConnect As SqlClient.SqlConnection = New SqlClient.SqlConnection(ConfigurationSettings.AppSettings("SQLDB_Test"))
        Dim StrSQL As String
        StrSQL = "SELECT Sum(Hrs) AS Hours, Sum(LT) AS LostTime, Sum(DL) AS DaysLost From TBLEHS620 Where EnterDate > #12/31/2003#"

        MyAdapter.Fill(MyDataSet)   <<<<<<<<<<<<<ERROR: Object reference not set to an instance of an object.
        Dim dt As DataTable = MyDataSet.Tables(0)
        Dim dr As DataRow = dt.Rows(0)

        If (MyDataSet.Tables(0).Rows.Count > 0) Then
            Me.txtHrs.Text = dr("Hours")
            Me.txtLostTime.Text = dr("LostTime")
            Me.txtDaysLost.Text = dr("DaysLost")
        Else
            Me.txtHrs.Text = 0
            Me.txtLostTime.Text = 0
            Me.txtDaysLost.Text = 0
        End If

    End Sub
-----------------------------------------------------------
0
 
LVL 25

Expert Comment

by:nauman_ahmed
Comment Utility
Change  Dim MyDataSet As New DataSet

-Nauman
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 25

Expert Comment

by:nauman_ahmed
Comment Utility
oops sorry, I was wrong. I have the following in C#. Let me do it in VB for more clarity:

private SqlConnection sqlConnection;
private SqlDataAdapter sqlDataAdapter;
private SqlCommand sqlCommand;
sqlConnection.Open();
DataSet ds = new DataSet();
sqlCommand = new SqlCommand();
sqlCommand.CommandText = SQLCommand;
sqlDataAdapter = new SqlDataAdapter(SQLCommand,sqlConnection);
sqlDataAdapter.Fill(ds,TableName);

0
 
LVL 25

Expert Comment

by:nauman_ahmed
Comment Utility
'Set the SQLConnection
Dim MYDataAdapter As SQLDataAdapter
Dim MyDataSet As New DataSet
Dim MySQLCommand As new SQLCommand
MySQLCommand.CommandText = "SELECT Sum(Hrs) AS Hours, Sum(LT) AS LostTime, Sum(DL) AS DaysLost From TBLEHS620 Where EnterDate > #12/31/2003#"

MyDataAdapter = new SQLDataAdapter(SQLComamnd,MySQLConnection)
MyDataAdapter.Fill(MyDataSet,"YTD_SUMMARY")

Please verify if this is working.....

Best, Nauman
0
 
LVL 25

Accepted Solution

by:
nauman_ahmed earned 500 total points
Comment Utility
Also to not confuse the readers: the C# code I have is written as the following function that returns a dataset. tcalbaz you can use the same approach so that you dont have to define the data access layer again and again. Actually I have defined a whole separate class for just Data Access. I call it DatabaseManagement and whenever I need to get the db data, I call it in the following way:

DataSet ds = new DataSet();
DatabaseManagment dbManagement = new DatabaseManagement();
string strSQL = "SELECT * FROM CUSTOMERS";
ds = dbManagement.GetRecords(strSQL,"CUSTOMERS");
DataTable dt = ds.Tables["CUSTOMERS"];
.
.
.
.
//or for a more quick approach....
DataTable dt = dbManagement.GetRecords(strSQL,"CUSTOMERS").Tables["CUSTOMERS"];


This is the function I have defined in the class:

public DataSet GetRecords(string SQLCommand,string TableName)
            {
                  try
                  {
                        sqlConnection.Open();
                        DataSet ds = new DataSet();
                        sqlCommand = new SqlCommand();
                        sqlCommand.CommandText = SQLCommand;
                        sqlDataAdapter = new SqlDataAdapter(SQLCommand,sqlConnection);
                        sqlDataAdapter.Fill(ds,TableName);
                        
                        return ds;
                  
                  }
                  catch(Exception ex)
                  {
                        throw ex;
                  }
                  finally
                  {
                        sqlConnection.Close();

                  }
                  
            }

Make your life easier dude.....;)

-Nauman
0
 
LVL 1

Author Comment

by:tcalbaz
Comment Utility
Nauman,
Thanks you for your assistance getting me on the right track.
Here is the final function completed:

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim Lastyr As String

        'Year to Date Summary Function
        Dim myQuery As String
        Lastyr = CStr(Now.Year - 1)
        myQuery = "SELECT Sum(Hrs) AS Hours, Sum(LostTime) AS LostTime, Sum(DaysLost) AS DaysLost From TBLEHS620_2 "
        myQuery = myQuery & " WHERE (DateEntered > CONVERT(DATETIME, '" & Lastyr & "-12-31 23:59:59', 102))"

        Dim conn As New SqlClient.SqlConnection(ConfigurationSettings.AppSettings("SQLDB_Test"))
        conn.Open()
        Dim ds As New DataSet
        Dim adapter As New SqlClient.SqlDataAdapter
        Dim MyCmd As SqlClient.SqlCommand
        adapter.SelectCommand = New SqlClient.SqlCommand(myQuery, conn)
        adapter.Fill(ds)
        Dim dt As DataTable = ds.Tables(0)
        Dim dr As DataRow = dt.Rows(0)
        If (ds.Tables(0).Rows.Count > 0) Then
            Me.txtHrs.Text = dr("Hours")
            Me.txtLostTime.Text = dr("LostTime")
            Me.txtDaysLost.Text = dr("DaysLost")
        Else
            Me.txtHrs.Text = 0
            Me.txtLostTime.Text = 0
            Me.txtDaysLost.Text = 0
        End If

    End Sub
---------------------------------------------
All the best

Ted
0
 
LVL 25

Expert Comment

by:nauman_ahmed
Comment Utility
Thanks ted :) I am glad that my solution worked for you....;) But remember .net is all about object oriented....Always think of reusing the code.....

Cheers, Nauman
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 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

8 Experts available now in Live!

Get 1:1 Help Now