Showing posts with label dates. Show all posts
Showing posts with label dates. Show all posts

Tuesday, March 27, 2012

Calling store procedure in Report throu VB

Dears
How to call store procedure in Crystal Report through VISUAL BASIC. i have Sp which has 3 parameters one is string others are dates parameter ,
how to to in the visual basic coding.
can any one help me passing paramerters .
Thanks
AnnuFor Vb 6:

Get rs (Recordset) calling stored procedure with parameters

After:

Dim report As CRAXDRT.report

Set report = crystal.OpenReport(App.Path & _
IIf(Right(App.Path, 1) = "\", "", "\") & _
s_Rpt & GetAdditionalNamePart(s_Rpt) & ".rpt") 'OPEN REPORT

report.Database.LogOnServerEx _
"crdb_odbc.dll", _
c_Settings.GetVal(CRYSTALDSN), _
c_Settings.GetVal(DBNAME), _
c_User.Name, _
c_User.Password, , _
c_Db.ConnectionStr
report.DiscardSavedData 'CLEARS REPORT SO WE WORK FROM RECORDSET
report.Database.SetDataSource rs 'LINK REPORT TO RECORDSET

Load frmReport
'ShowSendButton s_Rpt, frmReport.crV, frmReport.cmdSend

'crV - crystal viewer control
frmReport.crV.ReportSource = report 'LINK VIEWER TO REPORT
frmReport.crV.ViewReport

Best,

ika|||This is using VB 6 and CR 8.5 with RDC...

You can get your data from the Stored Proc through ADO and then pass the ADO recordset to Crystal:

'dsrReport is the name of your dsr file
Dim Report As New dsrReport

Set cmdData = New ADODB.Command
Set rsData = New ADODB.Recordset
cmdData.ActiveConnection = cnConnection
cmdData.CommandText = "sp_StoredProcName"
cmdData.CommandType = adCmdStoredProc
cmdData.Parameters.Refresh
cmdData.Parameters("@.Param1") = strParam1
cmdData.Parameters("@.Param2") = dtmParam2
cmdData.Parameters("@.Param3") = dtmParam3

'Required for RecordCount to return an accurate count
rsData.CursorType = adOpenDynamic
rsData.CursorLocation = adUseClient
rsData.Open cmdData

If Not rsData.EOF Then
Report.DiscardSavedData
Report.Database.SetDataSource rsData, 3, 1
End Ifsql

Saturday, February 25, 2012

Calendar Table

I am trying to get all dates starting from June 20 , 2004 to yesterday but
the table includes today's that (which i dont want).
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < GetDate()
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END@.day is not < GETDATE() until it hits the next day (because of the time
component). You need to remove the time component from GETDATE() somehow.
I have done so in the example below:
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate(),112))
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END
Keith
"Asim" <Asim@.discussions.microsoft.com> wrote in message
news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
>I am trying to get all dates starting from June 20 , 2004 to yesterday but
> the table includes today's that (which i dont want).
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < GetDate()
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END|||Thankyou very much..
"Keith Kratochvil" wrote:
> @.day is not < GETDATE() until it hits the next day (because of the time
> component). You need to remove the time component from GETDATE() somehow.
> I have done so in the example below:
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate(),112))
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END
>
> --
> Keith
>
> "Asim" <Asim@.discussions.microsoft.com> wrote in message
> news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
> >I am trying to get all dates starting from June 20 , 2004 to yesterday but
> > the table includes today's that (which i dont want).
> >
> > DECLARE @.Tmp TABLE (DOM smalldatetime)
> > DECLARE @.day smalldatetime
> > DECLARE @.DOM smalldatetime
> >
> > SET @.day = 'June 20, 2004'
> >
> > WHILE @.day < GetDate()
> > BEGIN
> > INSERT INTO @.Tmp
> > SELECT @.day as DOM
> > SET @.Day = @.Day + 1
> > END
>
>

Calendar Table

I am trying to get all dates starting from June 20 , 2004 to yesterday but
the table includes today's that (which i dont want).
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < GetDate()
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END@.day is not < GETDATE() until it hits the next day (because of the time
component). You need to remove the time component from GETDATE() somehow.
I have done so in the example below:
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate
(),112))
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END
Keith
"Asim" <Asim@.discussions.microsoft.com> wrote in message
news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
>I am trying to get all dates starting from June 20 , 2004 to yesterday but
> the table includes today's that (which i dont want).
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < GetDate()
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END|||Thankyou very much..
"Keith Kratochvil" wrote:

> @.day is not < GETDATE() until it hits the next day (because of the time
> component). You need to remove the time component from GETDATE() somehow.
> I have done so in the example below:
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate
(),112))
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END
>
> --
> Keith
>
> "Asim" <Asim@.discussions.microsoft.com> wrote in message
> news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
>
>

Calendar Table

I am trying to get all dates starting from June 20 , 2004 to yesterday but
the table includes today's that (which i dont want).
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < GetDate()
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END
@.day is not < GETDATE() until it hits the next day (because of the time
component). You need to remove the time component from GETDATE() somehow.
I have done so in the example below:
DECLARE @.Tmp TABLE (DOM smalldatetime)
DECLARE @.day smalldatetime
DECLARE @.DOM smalldatetime
SET @.day = 'June 20, 2004'
WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate(),112))
BEGIN
INSERT INTO @.Tmp
SELECT @.day as DOM
SET @.Day = @.Day + 1
END
Keith
"Asim" <Asim@.discussions.microsoft.com> wrote in message
news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
>I am trying to get all dates starting from June 20 , 2004 to yesterday but
> the table includes today's that (which i dont want).
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < GetDate()
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END
|||Thankyou very much..
"Keith Kratochvil" wrote:

> @.day is not < GETDATE() until it hits the next day (because of the time
> component). You need to remove the time component from GETDATE() somehow.
> I have done so in the example below:
> DECLARE @.Tmp TABLE (DOM smalldatetime)
> DECLARE @.day smalldatetime
> DECLARE @.DOM smalldatetime
> SET @.day = 'June 20, 2004'
> WHILE @.day < CONVERT(datetime,CONVERT(char(8),GetDate(),112))
> BEGIN
> INSERT INTO @.Tmp
> SELECT @.day as DOM
> SET @.Day = @.Day + 1
> END
>
> --
> Keith
>
> "Asim" <Asim@.discussions.microsoft.com> wrote in message
> news:090F9AA5-BF5D-44C4-9405-96D6D7276493@.microsoft.com...
>
>

Calendar recurring events logic

I'm having a calendar feature developed whereby users can add recurring
events. These recurring events can have start and end dates, meaning they
will recur only within a date range. For instance, user A creates an event
that recurs every Tuesday, from 1/1/05 - 3/2/06.
The developer has decided that it would be good to have another table that
stores each individual recurring event in a separate record. His logic is
that this will help with the display of calendar months. His logic is, if
the application has to dynamically iterate through every event record in the
database and logically map out which days have recurrence, that it would not
be good for performance.
My take though, is that if one recurring event can literally add in 10,000
records, then that's even worse.
What are your thoughts on the proper way to implement this?
Hi
It has always been hard to suggest for design issues,because you and only
you know exactly the business requrements.
CREATE TABLE Req_Events
(
EventId INT NOT NULL PRIMARY KEY,
UserId INT NOT NULL FOREIGN KEY --Users Table,
StartDate DATETIME NOT NULL,
EndDate DATETIME NOT NULL --you can create here a check constraints that
enddate must be less than startdate
)
"Shabam" <chalupa@.yomama-nospam.com> wrote in message
news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an
event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in
the
> database and logically map out which days have recurrence, that it would
not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>
|||Hi
From my perspective.
Create and entry for each occurrence in the main table, and link all the
occurrences together with an occurrence ID. This will enable the user to
remove a single occurrence (like an event that falls on a public holiday that
nobody would attend), without upsetting any logic. This may sound expensive,
but when you query for a specific user "Give me the events between today and
Sunday", it is a single query to a single table with a between operator. No
complicated logic to find out if there is a recurring event in the pile too.
An occurrence can also be changed. If a meeting moved from tomorrow onwards
to a new time, the old records for events that have occurred in the past
remain, and only the records dated tomorrow and later would be updated with
the new time. History can't change.
An occurrence is just a quick UI way for a user to do something that is
repetitive. It should not be handled in a different manner, compared to a
single event, in a DB just because of this. Separating Presentation and Data
logic.
Regards
Mike
"Shabam" wrote:

> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in the
> database and logically map out which days have recurrence, that it would not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>
|||> From my perspective.
> Create and entry for each occurrence in the main table, and link all the
> occurrences together with an occurrence ID. This will enable the user to
> remove a single occurrence (like an event that falls on a public holiday
that
> nobody would attend), without upsetting any logic. This may sound
expensive,
> but when you query for a specific user "Give me the events between today
and
> Sunday", it is a single query to a single table with a between operator.
No
> complicated logic to find out if there is a recurring event in the pile
too.
> An occurrence can also be changed. If a meeting moved from tomorrow
onwards
> to a new time, the old records for events that have occurred in the past
> remain, and only the records dated tomorrow and later would be updated
with
> the new time. History can't change.
> An occurrence is just a quick UI way for a user to do something that is
> repetitive. It should not be handled in a different manner, compared to a
> single event, in a DB just because of this. Separating Presentation and
Data
> logic.
Sounds fine, but what the system will allow many users to set up their own
calendars. If a user sets up an event that literally has 1000 individual
recurrences, then it won't take many users to bloat the database to an
unacceptable level wouldn't it? Also, the thought of a user clicking a
single button that generates 1000 records just doesn't seem right to me.
|||sp_msforeachdb 'EXEC sp_helpfile'
Note that sp_msforeachdb is not documented, not supported etc. Also, if you don't like the result
structure, you can easily change that by taking the source for from sp_helpfile and write your own
version that presents the information in a way that you like it.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Shabam" <chalupa@.yomama-nospam.com> wrote in message news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in the
> database and logically map out which days have recurrence, that it would not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>
|||Oops. Replied to wrong thread. Please ignore.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in message
news:e17lkG24EHA.2592@.TK2MSFTNGP09.phx.gbl...
> sp_msforeachdb 'EXEC sp_helpfile'
> Note that sp_msforeachdb is not documented, not supported etc. Also, if you don't like the result
> structure, you can easily change that by taking the source for from sp_helpfile and write your own
> version that presents the information in a way that you like it.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Shabam" <chalupa@.yomama-nospam.com> wrote in message news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
>

Calendar recurring events logic

I'm having a calendar feature developed whereby users can add recurring
events. These recurring events can have start and end dates, meaning they
will recur only within a date range. For instance, user A creates an event
that recurs every Tuesday, from 1/1/05 - 3/2/06.
The developer has decided that it would be good to have another table that
stores each individual recurring event in a separate record. His logic is
that this will help with the display of calendar months. His logic is, if
the application has to dynamically iterate through every event record in the
database and logically map out which days have recurrence, that it would not
be good for performance.
My take though, is that if one recurring event can literally add in 10,000
records, then that's even worse.
What are your thoughts on the proper way to implement this?Hi
It has always been hard to suggest for design issues,because you and only
you know exactly the business requrements.
CREATE TABLE Req_Events
(
EventId INT NOT NULL PRIMARY KEY,
UserId INT NOT NULL FOREIGN KEY --Users Table,
StartDate DATETIME NOT NULL,
EndDate DATETIME NOT NULL --you can create here a check constraints that
enddate must be less than startdate
)
"Shabam" <chalupa@.yomama-nospam.com> wrote in message
news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an
event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in
the
> database and logically map out which days have recurrence, that it would
not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>|||Hi
From my perspective.
Create and entry for each occurrence in the main table, and link all the
occurrences together with an occurrence ID. This will enable the user to
remove a single occurrence (like an event that falls on a public holiday that
nobody would attend), without upsetting any logic. This may sound expensive,
but when you query for a specific user "Give me the events between today and
Sunday", it is a single query to a single table with a between operator. No
complicated logic to find out if there is a recurring event in the pile too.
An occurrence can also be changed. If a meeting moved from tomorrow onwards
to a new time, the old records for events that have occurred in the past
remain, and only the records dated tomorrow and later would be updated with
the new time. History can't change.
An occurrence is just a quick UI way for a user to do something that is
repetitive. It should not be handled in a different manner, compared to a
single event, in a DB just because of this. Separating Presentation and Data
logic.
Regards
Mike
"Shabam" wrote:
> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in the
> database and logically map out which days have recurrence, that it would not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>|||> From my perspective.
> Create and entry for each occurrence in the main table, and link all the
> occurrences together with an occurrence ID. This will enable the user to
> remove a single occurrence (like an event that falls on a public holiday
that
> nobody would attend), without upsetting any logic. This may sound
expensive,
> but when you query for a specific user "Give me the events between today
and
> Sunday", it is a single query to a single table with a between operator.
No
> complicated logic to find out if there is a recurring event in the pile
too.
> An occurrence can also be changed. If a meeting moved from tomorrow
onwards
> to a new time, the old records for events that have occurred in the past
> remain, and only the records dated tomorrow and later would be updated
with
> the new time. History can't change.
> An occurrence is just a quick UI way for a user to do something that is
> repetitive. It should not be handled in a different manner, compared to a
> single event, in a DB just because of this. Separating Presentation and
Data
> logic.
Sounds fine, but what the system will allow many users to set up their own
calendars. If a user sets up an event that literally has 1000 individual
recurrences, then it won't take many users to bloat the database to an
unacceptable level wouldn't it? Also, the thought of a user clicking a
single button that generates 1000 records just doesn't seem right to me.|||sp_msforeachdb 'EXEC sp_helpfile'
Note that sp_msforeachdb is not documented, not supported etc. Also, if you don't like the result
structure, you can easily change that by taking the source for from sp_helpfile and write your own
version that presents the information in a way that you like it.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Shabam" <chalupa@.yomama-nospam.com> wrote in message news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
> I'm having a calendar feature developed whereby users can add recurring
> events. These recurring events can have start and end dates, meaning they
> will recur only within a date range. For instance, user A creates an event
> that recurs every Tuesday, from 1/1/05 - 3/2/06.
> The developer has decided that it would be good to have another table that
> stores each individual recurring event in a separate record. His logic is
> that this will help with the display of calendar months. His logic is, if
> the application has to dynamically iterate through every event record in the
> database and logically map out which days have recurrence, that it would not
> be good for performance.
> My take though, is that if one recurring event can literally add in 10,000
> records, then that's even worse.
> What are your thoughts on the proper way to implement this?
>
>|||Oops. Replied to wrong thread. Please ignore.
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Tibor Karaszi" <tibor_please.no.email_karaszi@.hotmail.nomail.com> wrote in message
news:e17lkG24EHA.2592@.TK2MSFTNGP09.phx.gbl...
> sp_msforeachdb 'EXEC sp_helpfile'
> Note that sp_msforeachdb is not documented, not supported etc. Also, if you don't like the result
> structure, you can easily change that by taking the source for from sp_helpfile and write your own
> version that presents the information in a way that you like it.
> --
> Tibor Karaszi, SQL Server MVP
> http://www.karaszi.com/sqlserver/default.asp
> http://www.solidqualitylearning.com/
>
> "Shabam" <chalupa@.yomama-nospam.com> wrote in message news:WfGdnY8zBunyxFzcRVn-3g@.adelphia.com...
>> I'm having a calendar feature developed whereby users can add recurring
>> events. These recurring events can have start and end dates, meaning they
>> will recur only within a date range. For instance, user A creates an event
>> that recurs every Tuesday, from 1/1/05 - 3/2/06.
>> The developer has decided that it would be good to have another table that
>> stores each individual recurring event in a separate record. His logic is
>> that this will help with the display of calendar months. His logic is, if
>> the application has to dynamically iterate through every event record in the
>> database and logically map out which days have recurrence, that it would not
>> be good for performance.
>> My take though, is that if one recurring event can literally add in 10,000
>> records, then that's even worse.
>> What are your thoughts on the proper way to implement this?
>>
>

Friday, February 24, 2012

Calendar Control and Database Connection

Hi,
I m trying to implement a calendar, where you can select certain dates and view list of events for that day. The list is generated from database. I found a script on the web that is quite similar to what i want to achieve. I tried to run this script, however I get an exeption saying:

An error has occurred while establishing a connection to the server. ... error: 40 - Could not open a connection to SQL Server)

This is the code:
SqlConnection mycn;
SqlDataAdapter myda;
DataSet ds = new DataSet();
DataSet dsSelDate;
String strConn;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
strConn = "Data Source=localhost;Initial Catalog=pubs";

mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM EventsTable", mycn);
myda.Fill(ds, "Table"); //This where I get the exeption
}

protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["EventDate"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["EventDate"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = System.Drawing.Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}

private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from EventsTable where EventDate='" +
Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0)
{
DataGrid1.Visible = false;
}
else
{
DataGrid1.Visible = true;
DataGrid1.DataSource = dsSelDate;
DataGrid1.DataBind();
}
}


Can some one tell me what is wrong with the code.
Thank You

WATCH THIS SPACE

I resolve the issue by correcting the connection string within the strCon.

WATCH THIS SPACE

Calendar Control

Is there a way to use calendar controls to select dates. I have a
report that requires a start date and an end date as parameters. I
would rather have a date selector then have the user type in the dates.
thanksIt will be in SQL 2005, otherwise you need to put an html page in front of
the report to do this
--
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
<jeffj924@.gmail.com> wrote in message
news:1126119866.508176.4670@.g44g2000cwa.googlegroups.com...
> Is there a way to use calendar controls to select dates. I have a
> report that requires a start date and an end date as parameters. I
> would rather have a date selector then have the user type in the dates.
> thanks
>

Sunday, February 19, 2012

calculation with dates challenge

I have a start and end datetime field and a field with the lunchbreak in
minutes. Now I need to find out the number of hours and minutes (HH:mm) this
person has worked.
endtime - starttime - lunchbreak and formatted in HH:mm.
Suggestions on how to go about this in Reporting services ?
PeterPeter,
You will want to do the following:
1) Do a 'DateDiff' and convert the endtime-starttime into minutes
e.g. DateDiff(m, Date1, Date2)
2) Do simple math to subtract the lunch break (if not in minutes, then
convert)
3) Divide the answer by 60 to get your hours
4) Take total minutes minus (60*hours) and this is your remainder minutes
5) format as desired.
if you require more info (ie, how to do date diff, or write it) let me know.
Michael
"Peter De Rop" wrote:
> I have a start and end datetime field and a field with the lunchbreak in
> minutes. Now I need to find out the number of hours and minutes (HH:mm) this
> person has worked.
> endtime - starttime - lunchbreak and formatted in HH:mm.
> Suggestions on how to go about this in Reporting services ?
> Peter

Thursday, February 16, 2012

Calculating time elapsed (weekdays only)

What is the best way to calculate time elapssed between two dates and factor
in wdays only (exclude Saturday and Sunday).
Example:
Friday Jan 28th at 10pm thru Monday Jan 31st at 2am should calculate to 4
hours.
Friday Jan 21st at 10pm thru Monday Jan 31st at 2am should calculate to 124
hours
Thanks in advance,
MarkOn Mon, 31 Jan 2005 15:56:42 -0500, Mark Andrews wrote:

>What is the best way to calculate time elapssed between two dates and facto
r
>in wdays only (exclude Saturday and Sunday).
>Example:
>Friday Jan 28th at 10pm thru Monday Jan 31st at 2am should calculate to 4
>hours.
>Friday Jan 21st at 10pm thru Monday Jan 31st at 2am should calculate to 124
>hours
>Thanks in advance,
>Mark
>
Hi Mark,
Use DATEDIFF to find the total number of hours between the two dates.
Use a calendar table to find the number of non-workdays between the two
dates, multiply by 24 and subtract.
Why should I consider using an auxiliary calendar table? www.aspfaq.2519
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||See if this helps:
How do I count the number of business days between two dates?
http://www.aspfaq.com/show.asp?id=2453
Why should I consider using an auxiliary calendar table?
http://www.aspfaq.com/show.asp?id=2519
AMB
"Mark Andrews" wrote:

> What is the best way to calculate time elapssed between two dates and fact
or
> in wdays only (exclude Saturday and Sunday).
> Example:
> Friday Jan 28th at 10pm thru Monday Jan 31st at 2am should calculate to 4
> hours.
> Friday Jan 21st at 10pm thru Monday Jan 31st at 2am should calculate to 12
4
> hours
> Thanks in advance,
> Mark
>
>

Tuesday, February 14, 2012

Calculating Length of Service Categories based on Start Dates

Ok, so I've been struggling with the logic behind this one for a while, so I thought I'd ask you guys for some ideas :)

Basically, I have the following table structure
Employee(employee_number, continuous_start_date, ...)

The problem lies in working out a summary of service categories (0-6months, 7-12months, 13-24, 25+).
I can work out the length of service in months with the following code

SELECT DateDiff(mm, continuous_start_date, GetDate()) AS 'Service in months'
FROM employee

So the first stage is to summarise the length of service into groups as mentioned above.

Then the final stage is working out how many people are in each group!

Hope I have given enough information - and please do not post a full solution - just some hints on how to get the desired result ;)

Thanks later, and in advance :p
-GeorgeVHi George

I would create a table with upper and lower month limits for each of the bands, and proobably a name for each band. Create an join to this table on your calculated "monthsInService" field using the between operator.

Robert would then be your mothers brother.|||Nice suggestion Poots, but I'm aiming to get this in a single query (so, CASE statements, or an array-type thing?) :p

I am struggling with getting the results into groups at the moment - I've kind hit a brick wall - wondering if it's quicker to climb, go under, walk round, etc :p Not sure what's the best way to my destination (or if it even is!)|||My suggestion works fine as a sinlge statement. Why wouldn't it?

Reasons not to use a case statement:
http://weblogs.sqlteam.com/jeffs/archive/2006/02/10/9002.aspx|||Hmm, you make a good point!
So, let's asy I make a table ServiceCategory(Unique_Identifier, Lower_Limit, Upper_Limit, Limit_Description (and possibly Sort_Order?))

Would I join to my table like this:

FROM Employee e
INNER JOIN ServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit

Apologies, I'm trying to get the logic right before creating a new table (they don't really like people creating new tables - hence my single query approach)

Thanks Poots :)|||Yes.

Personally I wouldn't bother with a surrogate key because I can't see it ever serving any purpose. But that's just me - a minor matter. :)

I presume you are comfy with the sums part?|||BTW - I presume there is no end of service date in the table? If not you will need to account for that in your expression...|||two stars for poots on this thread -- one for suggesting the join to a range table, and another for advising against the surrogate key

nice job

:)|||Thank you Rudy. Makes up for the couple of cock ups I made in the last SQL threads we shared in common :)|||Surrogate key is automatically generated by our HR system, I know it's not needed ;) But still, good catch!

As for the sums bit - I'll have to get back to you after I've played some more - thanks for the suggestions, going to ask (yes, sadly I have to ask when I'm playing with the HR system... :s) to create my new table now :)|||Ah - I see. You can develop this using a table variable until you are happy it works great then submit the create table script to them once you are 100% confident.|||Table variable?
And I have still never written a create table script - I have only ever used Enterprise Manager (HR system is on 2K)...

This might give me an oppurtunity to have a go - I'll be back with an attempt soon ;)|||This is a template I use. Find & replace the placeholders. See if it helps:

IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N't_name') BEGIN
DROP TABLE dbo.t_name
END

CREATE TABLE dbo.t_name
(
c_name INT NOT NULL CONSTRAINT df_t_name_c_name DEFAULT 0
, CONSTRAINT pk_t_name PRIMARY KEY CLUSTERED (c_name) WITH (FILLFACTOR = 80)
, CONSTRAINT ix_t_name_c_name_u_nc UNIQUE NONCLUSTERED (c_name) WITH (FILLFACTOR = 80)
, CONSTRAINT ck_t_name_c_name CHECK (c_name BETWEEN 1 AND 10)
, CONSTRAINT fk_t_name_other_t_name FOREIGN KEY (c_name) REFERENCES other_t_name (c_name) ON DELETE CASCADE
)
GO|||How's this for an attempt? :)

CREATE TABLE ServiceCategory
(
Lower_Limit numeric,
Upper_Limit numeric,
Limit_Description char(16),
Sort_Order numeric
)

INSERT
INTO ServiceCategory(Lower_Limit, Upper_Limit, Limit_Description, Sort_Order)
VALUES (0, 6, '0 to 6 months', 1)

SELECT *
FROM ServiceCategory|||Oh and my full solution:

SELECT Count(s.Limit_Description) AS 'Total'
,s.Limit_Description
FROM pwa_master.Employee e
INNER JOIN ServiceCategory s
ON DateDiff(mm, e.continuous_start_date, GetDate()) BETWEEN s.Lower_Limit AND s.Upper_Limit
GROUP
BY s.Limit_Description, s.Sort_Order
ORDER
BY s.Sort_Order

Thank you :D|||That's fine. Not so sure about the description now (none key column dependancies - maybe I am just a fuss pot). I think TINYINT is probably sufficient - numeric is a bit overkill. Inner join removes anyone not accounted for in the range table. There is no end date right? Add some NOT NULLS into your table definition (all columns).

All the above is picky - good job.|||Hmm, well it did suddenly occur to me that there are a whole 3 null values in the system (which slipped through the net before the field was made mandatory...) but if I flag them up to HR it will be dealt with ;)

As for my top range, not sure what to put, I currently have a rediculous value of 1200 (100 years service... yeah, right ;))
So this covers everyone (other than the three silly nulls from above)... It's not pretty, but it works... Suggestions welcomed with open arms! :)

Should I drop the desc, just not sure what to do instead (want to be able to display a description of each range)... Hmm...|||I think a "forever" date is ok in this instance.

I might just be being too picky re your desciption field. The problem of course is second normal form and if you end up changing your bands. If you drop the desc you can create a view something like:

SELECT
Lower_Limit, Upper_Limit,
CAST(Lower_Limit AS VARCHAR()) + ' to ' + CAST(Upper_Limit AS VARCHAR()) + ' months' AS Limit_Description,Sort_Order
FROM dbo.ServiceCategory


HTH|||I tried that, but was getting conversion errors... Was thinking of Cast/convert statements as a fix :D (I was actually really close!)

I like being picky, so I want to also sort out my "forever" limit, as you put it, but I'm not exactly sure how...|||Nah - an absurdly high value in there is fine. That is what I would do. You could leave it null and then use COALESCE() in your join but I prefer having a value in there myself since there is no time when you will want it to count as a NULL.

I'll ask one last time (maybe you have spotted this and didn't bother answering) - are there leaving dates in the staff table? If not then I presume it is current staff only?

None of you lower limits are the same as your upper limits are they? (for example row two does not start at 6 but at 7).|||SELECT Limit_Description
,CAST(Lower_Limit AS VARCHAR) +
(CASE WHEN Sort_Order = (SELECT Max(Sort_Order) FROM ServiceCategory)
THEN '+'
ELSE ( + ' to ' + CAST(Upper_Limit AS VARCHAR))
END) + ' months'
AS Limit_Description
FROM ServiceCategory

:cool: hehe|||Employee table is a view on the people table, based on termination date being empty/null/blank/etc. (EDIT: and the continuous_start_date being greater than or equal to today)

As for my limits:
0 6
7 12
13 24
25 60
61 1200|||Looks to me that you are all sorted then :)|||Yippee :D
Now I have to make this into a sproc written in FoxPro and I'm done ;)
Roll on our new HR system!

Thanks for all your help mate :beer:|||Ooh, one little thing while I'm here:

ALTER TABLE ServiceCategory DROP COLUMN Limit_Description

Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near 'Limit_Description'.

Any ideas? I'm completely stumped here...|||Annoyingly, the keyword COLUMN in this case causes an error. ALTER TABLE DROP... always drops a column - no need for the key word.|||I don't think I follow - I've tried:
ALTER TABLE ServiceCategory DROP Limit_Description
Which causes errors, "not a constraint"...

ALTER TABLE DROP ServiceCategory.Limit_Description
More errors...
*eek*|||Beg your pardon - I'm thinking of add :rolleyes:

Something wot I wrote for our more junior developers:

USE tempdb
go

BEGIN TRAN
--SET UP----------------
--Make sure the db is clean
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me') BEGIN
DROP TABLE dbo.delete_me
END

IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me_too') BEGIN
DROP TABLE dbo.delete_me_too
END

--This table is pretty irrelevent - just used for a foreign key constraint example.
--If it did not exist the code would error.
CREATE TABLE dbo.delete_me_too
(
my_other_col VARCHAR(10)
, CONSTRAINT pk_delete_me_too PRIMARY KEY CLUSTERED (my_other_col) WITH (FILLFACTOR = 80)
)
GO

--This is the table we will alter.
CREATE TABLE dbo.delete_me
(
my_col INT
)
GO
--SET UP----------------

--COLUMNS----------------
--Add a column. NOTE - no COLUMN key word.
ALTER TABLE dbo.delete_me
ADD my_new_col VARCHAR(10)

--remove a colimn
ALTER TABLE dbo.delete_me
DROP COLUMN my_new_col

--Alter a column
ALTER TABLE dbo.delete_me
ALTER COLUMN my_col VARCHAR(10) NOT NULL
Go
--COLUMNS----------------

--CONSTRAINTS----------------
--Add a primary key
ALTER TABLE dbo.delete_me
ADD CONSTRAINT pk_delete_me PRIMARY KEY CLUSTERED (my_col) WITH (FILLFACTOR = 80)

--Add a unique constraint (note - a unique constraint is enforced as an index so you can
--either add a unique constraint or create a unique index.
ALTER TABLE dbo.delete_me
ADD CONSTRAINT ix_delete_me_my_col_u_nc UNIQUE NONCLUSTERED (my_col) WITH (FILLFACTOR = 80)

--Add a check constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT ck_delete_me_my_col CHECK (my_col NOT LIKE '%[0-9]%')

--Add a foreign key constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT fk_delete_me_delete_me_too FOREIGN KEY (my_col) REFERENCES delete_me_too (my_other_col) ON DELETE CASCADE

--Add a default constraint
ALTER TABLE dbo.delete_me
ADD CONSTRAINT df_delete_me_my_col DEFAULT 'default val' FOR my_col

--NOTE - there is no ALTER constraint syntax. You must drop the constraint and then
--add the constraint with the new settings. You can, however, user ALTER INDEX syntax
--for changing indexes. Check BoL for ALTER INDEX for more information.
--Drop the constraints. NOTE - the syntax is the same for all of them.
--You don't *have* to use the CONSTRAINT key word when dropping constraints.
ALTER TABLE dbo.delete_me
DROP CONSTRAINT df_delete_me_my_col

ALTER TABLE dbo.delete_me
DROP fk_delete_me_delete_me_too

ALTER TABLE dbo.delete_me
DROP ck_delete_me_my_col

ALTER TABLE dbo.delete_me
DROP CONSTRAINT ix_delete_me_my_col_u_nc

ALTER TABLE dbo.delete_me
DROP CONSTRAINT pk_delete_me
--CONSTRAINTS----------------

--Clean up
IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me') BEGIN
DROP TABLE dbo.delete_me
END

IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N'delete_me_too') BEGIN
DROP TABLE dbo.delete_me_too
END

ROLLBACK TRAN|||--remove a colimn
ALTER TABLE dbo.delete_me
DROP COLUMN my_new_col

Why won't this work :(|||You mean the code I posted does not work? Execute the whole thing I posted - it should work fine.|||What I meant was: Your syntax matched my syntax... and mine didn't work

*confused*|||Almost but not quite.

Qualify your table name with the schema.
Check there is nothing after the statement.
Double check you have spelt the table and column names correctly.
Check you are executing in the right database.|||You may also want to check if the column to be dropped is not in any FK relationships (the heartbreak would be too much for the database, you know), check constraint, computed columns, indexes, glee clubs, etc..|||Just came back here to reference some code

IF EXISTS (SELECT NULL FROM sys.tables WHERE name = N't_name') BEGIN
DROP TABLE dbo.t_name
END

But when I run

SELECT NULL FROM sys.tables WHERE name = N'tServiceCategory'

I get:
Server: Msg 208, Level 16, State 1, Line 1
Invalid object name 'sys.tables'.

Any ideas?|||i will never understand why people write a script that says "if this thing exists, drop this thing"

duh, just drop it

if it existed, then it won't exist after you drop it

and if it didn't exist, it still won't

easy-peasy

:cool:|||Ah, but when I run the SQl in FoxPro I get an error, which means I must have a logical test to see if it's there or not. But then again, the temp table idea has pretty much gone out the window thanks to Sir Poots (thanks!) it was just a matter of intrigue ;)|||i will never understand why people write a script that says "if this thing exists, drop this thing"

duh, just drop it

if it existed, then it won't exist after you drop it

and if it didn't exist, it still won't

easy-peasy

:cool:... but it causes an error.

sys.tables is a SQL 2005 thing. You need... erm...

...
dbo.sysobjects ...
where type = N'U'
...

if memory serves|||*tips cap* thank you kindly sir.
your memory is correct :)|||Reasons not to use a case statement:
http://weblogs.sqlteam.com/jeffs/archive/2006/02/10/9002.aspx

Thx Mr Flump :)

This was so helpful and informative, it's kept me out of the forum for 2 days.
I've redisgned 4 tables so far.|||... but it causes an error. which you ignore

allow me to illustrate:

you: please drop table such-and-such
database: yes sir
you: now please create table such-and-such
database: yes sir

you: please drop table such-and-such
database: but table such-and-such doesn't exist!!! oh, woe!!!!
you: now please create table such-and-such
database: yes sir|||that tactic is fine for one-offs, but if you are automating script execution in a production environment, you don't want to have to dig through a bunch of false alarms to see if something failed. I don't anyway.|||but it isn't a "failure"

what, you can't write a procedure with try/catch logic in sql server? and choose to ignore?you should be able to write a stored proc to do pretty much whatever you want, including ignoring a message when you know it can be ignored

and a proc is the only thing that i would allow in production

if i were a dba, that is ;)|||but it isn't a "failure"

what, you can't write a procedure with try/catch logic in sql server? and choose to ignore?you should be able to write a stored proc to do pretty much whatever you want, including ignoring a message when you know it can be ignored

and a proc is the only thing that i would allow in production

if i were a dba, that is ;)

try/catch doesn't cut it, because then you'd have to filter out the errors you choose to ignore (the "object doesn't exist" error in this case) and let the others bubble up. much easier to check if it exists before dropping.

frankly I'm surprised you suggested this. using try/catch as a flow control mechanism is bad form. I don't know about sql, but on other languages it's a very expensive way to do things. catching an exception isn't cheap in C++ and C#. Exceptions should be exceptional, not the rule. That's why they are called exceptions.|||which you ignore

allow me to illustrate:

you: please drop table such-and-such
database: yes sir
you: now please create table such-and-such
database: yes sir

you: please drop table such-and-such
database: but table such-and-such doesn't exist!!! oh, woe!!!!
you: now please create table such-and-such
database: yes sirBut the red text is so unaesthetically pleasing :)

Seriously though - the suggestion of TRY ... CATCH is really just another flavour of the same solution. You need one TRY ... CATCH per object because you can't have the code skip the dropping of other objects after the first execption. The only way I could see your suggestion working without it being at least as verbose as an existance check is if SQL had the equivelent of ON ERROR RESUME NEXT - which is of course the spawn of the devil(http://weblogs.sqlteam.com/jeffs/archive/2006/06/06/10093.aspx) ;)

I don't share Jezamine's philosophical objections to using TRY ... CATCH. I'm not too fussed about efficiency with schema creation scripts and I don't have a big problem with handling errors rather than avoiding them if it makes sense to do so. EDIT: in fact you might remember a question I posted regarding a similar issue a few years back when I asked for advice on the check for existence of a record before inserting Vs insert anyway and ignore the primary key violation. I just don't see the advantage of your method over checking if it exists.

I also might add that I have a load of snippets in SQLPrompt that I can call up with a couple of key strokes so I don't even have to spend extra time typing :D|||Thx Mr Flump :)

This was so helpful and informative, it's kept me out of the forum for 2 days.
I've redisgned 4 tables so far.Thanks I... copied and pasted the link myself you know. Here is another one from my extensive library:
http://www.sqljunkies.com/WebLog/amachanic/archive/2006/02/16/18123.aspx|||I'm afraid I disagree with your methods Rudy...
Ignoring errors sounds like a real bad habit to me!
In this instance I couldn't have done that anyway - what with the 3rd party interface to come - it sees an error and it cries.

Even saying that, when I was using query analyzer it hated the fact that my tables didn't exist when it tried to drop them - the last thing you need is for a user to get scared because an error occurs - just means more support calls for me to deal with "No dear, that error doesn't matter" is not what they want to hear, and leads them to think other problems are less severe also.

Rhubar, rhubarb, rhubarb...

Where was I? Oh yeah, the extra 2 lines of code are nothing compared to the amount of hassle that is produced from leaving them out.|||Hi, this post is very informative; however I would like some specific information. If someone can help me then please send me a private message. Best Regards,|||Hi, this post is very informative; however I would like some specific information. If someone can help me then please send me a private message. Best Regards,

Hi shahzadmasih,

Why not ask your question here, so we can all continue to benefit?

Mark|||As above...
This is a public forum - why not share your questions with everyone? :)|||Speaking for this shop, we prefer having the "if exists then drop" syntax for two reasons:
1) We have recently begun employing a group of offshore folks to do the actual running of the scripts. Having fewer errors for them to deal with makes their life (and consequently ours) easier.
2) We are debating going to an automatic script deployment system. If we do that, all errors would have to be caught, and probably inspected, evaluated, and a some pages of documentation sent to the end user detailing why the deployment got mucked up halfway through the deployment.

Still, if you are sitting at the console and doing this yourself, with no other people looking over your shoulder, then the "if exists then drop" syntax is perfectly valid. It is just when you have to deal with a range of skills that it becomes a problem.|||2) We are debating going to an automatic script deployment system. If we do that, all errors would have to be caught, and probably inspected, evaluated, and a some pages of documentation sent to the end user detailing why the deployment got mucked up halfway through the deployment.

that's exactly the kind of thing I meant in my earlier post by "automating script execution in a production environment".

Throwing errors unnecessarily, or using TRY/CATCH to eat them, would be a disaster for such a system.

Calculating Hours with Overlapping Times

All,

I have a table with start and end dates/times in it, and would like to
be able to calculate the number of hours represented, accounting for
overlapping records.

Note that I am looking for an answer on HOW to do this--I don't
necessarily need it to be written for me (although it would not go
unappreciated!).

CREATE TABLE [dbo].[session_temp] (
[session_pk] [int] IDENTITY (1, 1) NOT NULL ,
[date_start] [smalldatetime] NULL ,
[date_end] [smalldatetime] NULL
) ON [PRIMARY]
GO

--These values make a very simplistic example,
--as they only represent one
--session,so using min and max would work in this case,
--but would not work if there
--were multiple sessions involved.

--hopefully you get the idea of what I am going for:

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:30pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 10:45pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/4/04 11pm')

INSERT INTO session_temp
VALUES('4/4/04 9 pm','4/5/04 2am')

--the query I am looking to write would return "5"
--the one below obviously does not do what I am looking for
SELECT
SUM(CAST(DATEDIFF(ss,date_start,date_end) AS NUMERIC(8,2))/3600)
FROM
session_temp

Thanks very much for any insight.

Phil

--
Check out my poker-only weblog at:
http://www.livejournal.com/users/chicago_phil/
Download my session-tracking spreadsheet at:
http://www.geocities.com/fibby70/"Phil Sandler" <psandler70@.hotmail.com> wrote in message news:3c5d9515.0405121055.44f6c18a@.posting.google.c om...
> All,
<snip>
>
> Thanks very much for any insight.
> Phil

How about this?

Select
date_start,
max( cast( datediff(ss, date_start, date_end ) as numeric(8,2))/3600 )
from
session_temp
group by date_start ;

--
Paul Horan[TeamSybase]|||"Phil Sandler" <psandler70@.hotmail.com> wrote in message
news:3c5d9515.0405121055.44f6c18a@.posting.google.c om...
> All,
> I have a table with start and end dates/times in it, and would like to
> be able to calculate the number of hours represented, accounting for
> overlapping records.
> Note that I am looking for an answer on HOW to do this--I don't
> necessarily need it to be written for me (although it would not go
> unappreciated!).
>
> CREATE TABLE [dbo].[session_temp] (
> [session_pk] [int] IDENTITY (1, 1) NOT NULL ,
> [date_start] [smalldatetime] NULL ,
> [date_end] [smalldatetime] NULL
> ) ON [PRIMARY]
> GO
> --These values make a very simplistic example,
> --as they only represent one
> --session,so using min and max would work in this case,
> --but would not work if there
> --were multiple sessions involved.
> --hopefully you get the idea of what I am going for:
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10:30pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10:45pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 11pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/5/04 2am')
> --the query I am looking to write would return "5"
> --the one below obviously does not do what I am looking for
> SELECT
> SUM(CAST(DATEDIFF(ss,date_start,date_end) AS NUMERIC(8,2))/3600)
> FROM
> session_temp
>
> Thanks very much for any insight.
> Phil
> --
> Check out my poker-only weblog at:
> http://www.livejournal.com/users/chicago_phil/
> Download my session-tracking spreadsheet at:
> http://www.geocities.com/fibby70/

I assume that in addition to overlapping periods there might also be
gaps, for example, a period from 9AM to 10AM and then from 11AM
to 12PM should yield 2 hours with a 1 hour gap between 10AM and 11AM.

An approach would be to find the time from the earliest start datetime
to the latest end datetime and then subtract all gap lengths from this
amount.

CREATE TABLE Periods
(
start_period SMALLDATETIME NOT NULL,
end_period SMALLDATETIME NOT NULL,
CHECK (start_period < end_period),
PRIMARY KEY (start_period, end_period)
)

CREATE VIEW PeriodGaps (start_period, end_period)
AS
SELECT MAX(P1.end_period), P2.start_period
FROM Periods AS P1
INNER JOIN
Periods AS P2
ON P1.start_period < P2.start_period
GROUP BY P2.start_period
HAVING MAX(P1.end_period) < P2.start_period

-- Sample data
INSERT INTO Periods (start_period, end_period)
VALUES ('9AM', '10:30AM')
INSERT INTO Periods (start_period, end_period)
VALUES ('9:30AM', '11:30AM')
INSERT INTO Periods (start_period, end_period)
VALUES ('1:30PM', '3:00PM')
INSERT INTO Periods (start_period, end_period)
VALUES ('3:30PM', '5:00PM')

-- Note that SMALLDATETIME values are to the minute
SELECT ((SELECT COALESCE(DATEDIFF(MINUTE,
MIN(start_period),
MAX(end_period)), 0)
FROM Periods) -
(SELECT COALESCE(SUM(DATEDIFF(MINUTE,
start_period,
end_period)), 0)
FROM PeriodGaps)) / 60.0 AS duration_in_hrs

duration_in_hrs
5.500000

--
JAG|||psandler70@.hotmail.com (Phil Sandler) wrote in message news:<3c5d9515.0405121055.44f6c18a@.posting.google.com>...
> All,
> I have a table with start and end dates/times in it, and would like to
> be able to calculate the number of hours represented, accounting for
> overlapping records.
> Note that I am looking for an answer on HOW to do this--I don't
> necessarily need it to be written for me (although it would not go
> unappreciated!).
>
> CREATE TABLE [dbo].[session_temp] (
> [session_pk] [int] IDENTITY (1, 1) NOT NULL ,
> [date_start] [smalldatetime] NULL ,
> [date_end] [smalldatetime] NULL
> ) ON [PRIMARY]
> GO
> --These values make a very simplistic example,
> --as they only represent one
> --session,so using min and max would work in this case,
> --but would not work if there
> --were multiple sessions involved.
> --hopefully you get the idea of what I am going for:
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10:30pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 10:45pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/4/04 11pm')
> INSERT INTO session_temp
> VALUES('4/4/04 9 pm','4/5/04 2am')
> --the query I am looking to write would return "5"
> --the one below obviously does not do what I am looking for
> SELECT
> SUM(CAST(DATEDIFF(ss,date_start,date_end) AS NUMERIC(8,2))/3600)
> FROM
> session_temp
>
> Thanks very much for any insight.
> Phil
> --
> Check out my poker-only weblog at:
> http://www.livejournal.com/users/chicago_phil/
> Download my session-tracking spreadsheet at:
> http://www.geocities.com/fibby70/

Here's a stored procedure that I have created to do what you need:
/* This stored procedure combines any overlapping time segments into
a single segment in the temporary table #CombinedTime. Only non-
overlapping segements of time exist in this table. It then returns the
total hours for all these remaining segments.

Assumptions:
1. Date_Start <= Date_End
2. Date_Start, and Date_End are not null

Usage:
DECLARE @.Total_Hours AS INT

EXEC @.Total_Hours = CombinedTime

PRINT @.Total_Hours
*/
CREATE PROCEDURE CombinedTime AS

DECLARE
@.Date_Start AS SMALLDATETIME,
@.Date_End AS SMALLDATETIME,
@.Total_Hours AS INT

/* Create temporary table to contain combined information.
*/
CREATE TABLE #CombinedTime (
Date_Start SMALLDATETIME NOT NULL ,
Date_End SMALLDATETIME NOT NULL
)

/* Use a cursor to get every record from Session_Temp */
DECLARE Time_Cursor CURSOR FOR
SELECT Date_Start, Date_End
FROM Session_Temp
ORDER BY Date_Start ASC

OPEN Time_Cursor
FETCH NEXT FROM Time_Cursor INTO @.Date_Start, @.Date_End
WHILE (@.@.FETCH_STATUS != -1)
BEGIN
/* Update an existing record in the temporary table if Date_Start is
within the bounds of an existing record, and the Date_End is outside */
UPDATE #CombinedTime
SET Date_End = @.Date_End
WHERE @.Date_Start BETWEEN Date_Start AND Date_End
AND @.Date_End > Date_End

/* Insert a record that falls completely outside previous ranges */
INSERT INTO #CombinedTime
(Date_Start, Date_End)
SELECT @.Date_Start, @.Date_End
WHERE NOT EXISTS (SELECT 1
FROM #CombinedTime
WHERE @.Date_Start < Date_End)

FETCH NEXT FROM Time_Cursor INTO @.Date_Start, @.Date_End
END /* WHILE */

CLOSE Time_Cursor
DEALLOCATE Time_Cursor

/* Get the total hours from the non-overlapping segments */
SELECT @.Total_Hours = SUM(DATEDIFF(HH, Date_Start, Date_End))
FROM #CombinedTime

DROP TABLE #CombinedTime

RETURN @.Total_Hours
GO

Sunday, February 12, 2012

Calculating Dates

I'm not sure if this is possible or not.

I have two date fields that I want to show the difference between. However I have another table linked with this report that has the calendar date and marks each date with a number 1 if it's a work day, number 2 if it's a weekend, number 3 if it's a holiday etc. Does anyone know of a way that I can show the difference between date1 and date2 for each record counting only the work days?

Please help!!
Thanks,
Babs827So just count the number of 1s in the other table between the two dates, e.g. in a subreport.|||What database you are using? Because in MySQL there's a function DATEDIFF which will solve your problem|||Really? MYSQL's DateDiff knows about his rules for holidays etc?
Wow!
:) :) :)|||Not exactly that way but you can create a table for holidays then make a views. MySQL can determine the date if it's saturday or sunday. Now you can use the Crystal for making a function.

What database you are using?

Calculating Dates

I have a table in my sql server that calculates renewal dates for me, that date is based on the final suit date. The table has the ssn, and the FinalSuitDate its in a one to many relationship with the employeetable.

the Finalsuit table is suppose to calculate the renewal dates(which I'm trying to do in a query) my original expression in access was using dateserial FirstRenewal: DateSerial(Year([FINALSUITDONE])+2,Month([FINALSUITDONE])+1,Day([FINALSUITDONE])=30), but sql does not recognize that.

For Example

If the Finalsuit is 12/01/2000
then the renewal would be 12/31/2002
the renewal are to be done on the last day of the month and two years from the finalsuit date. Problems is I'm having problems doing this in sql servers query?

Can someone out there help pleaseI think I've got the syntax right on this, but I just had a beer so can't be (hic) sure:

dateadd(day, -1, convert(char(10), dateadd(month, 25, [FINALSUITDONE]), 120)+'-01')

Adds 25 months to [FINALSUITDONE] to get the month FOLLOWING the month you want. Then CONVERTS to the first day of that month, and the subtracts 1 day to get that last day of the month 24 months (2 years) from the date you started with.|||thank you for replying, but it gave me an error message saying "your entry can not be converted to a valid datetime entry"

So frustrated

thank you for trying to help though I sure do appreciate it.
back to the books|||do this SELECT CAST(FINALSUITDONE AS DATETIME) FROM table. See if that gives you an error. If it does, you need to find out whatever entry is not a proper datetime and fix it before anything you do like this will work.|||No, do this:

1) Wait 2 hours after drinking a beer before posting any forum answers.
2) Post the correct syntax:

dateadd(day, -1, convert(char(7), dateadd(month, 25, [FINALSUITDONE]), 120)+'-01')

...should have use "convert(char(7)..." instead of "convert(char(10)..." :o|||hmmmmmmmm, IT'S BRIIIIIILIANT.|||Brilliant!|||Thank you so much Blindman for your help, I was really starting to get stressed out. By the way your very funny, I'll take your advice and have a couple of beers.

Wish I had your knowledge, still working towards it|||What a drunken genious

We have a lot of them here ... :D

Calculating and storing alternative calender/dates

Hi Engine room.

I want to automatically populate an alternative date column with hijri (Arabic) dates. So I will have two date columns in my datawarehouse table, one is for gregorian dates, the other for the equivalent in Hijri - a bilingual date system if you like. Now I guess I could do it in the SSI ETL tool and use Julian Dates, but the problem is storing the resulting value. - what data type should I use for hijri dates?

The dates can be input by the user in either format, which means the alternate date has to be populated.

Eventually I hope to make a bilingual system, I don't understand the user-defined types or how to define them, but I suspect they could be used in someway to help. Why am I doing this? - well eventually I hope to populate a cube for analysis and deliver a dual-language-dashboard using the new CTP3 stuff.

Any suggestions on how I can make this dual-date system? - with a view to making a bilingual system eventually.

adv(thnx)ance..Mark.

HijriCalendar is one of the Calendars defined in the .NET FCL(framewor. class library) so you can use either DateTime or INT to store it. The actual calulation start with MSDN Middleeast to see if code exist for it if not you have to look for code to do it. The links below will take you in the right direction.

http://authors.aspalliance.com/aspxtreme/sys/globalization/HijriCalendarClass.aspx

http://www.microsoft.com/globaldev/getWR/steps/wrg_clndr.mspx

http://www.microsoft.com/middleeast/msdn/