24h/7d Time Periods TO 10h/5d Time Periods

May 4, 2006

I have to do alot of date calculations. For some calculations, I can use the datediff or dateadd function to get a Time Period between 2 dates.

Now for some dates I need to calculate the time between 2 dates BUT:

a week = 5 days starting from Monday to Friday
a day starts at 8AM and ends at 6PM (so a day is 10 hours)

You can probably calculate this manually but what about summer to winter hour and the month Februari when it has 29 days etc.

So I was thinking ... is it possible to calculate the Time Period for weeks with 24h a day / 7 days AND then transform that Time Period to a time period for weeks with 10h a day / 5 days ?

If anyone has an idea to solve this, either with functions or an other way, please let me know! Thanks

View 3 Replies


ADVERTISEMENT

A Report Different Time Periods

Jan 10, 2008

There are three tables Loans, CDs and Account.

I want to create a report based on above three tables
It looks like as follows;
















Program Summary

Yesterday/Current
MTD
Previous Month
YTD




Amount
Number
Amount
Number
Amount
Number
Amount
Number

Portfolio












Loans Commenced

$
#
$
#
$
#
$
#


Loans Closed

$
#
$
#
$
#
$
#


CDs Commenced

$
#
$
#
$
#
$
#


CDs Closed

$
#
$
#
$
#
$
#















Loan table - Amount, State
CD - Amount, State
Account - CommencedOnDate(date time), closeondate(date time)

Yesterday - Loans/CDs started yesterday(calander date..not last 24 hours)
MTD - " " First of this month to yesterday
Previous Month - " " during previous month
YTD - " " Loans/CDs started from 1 of this year to yesterday

Loan and cd states are Commenced and Closed

Based on this I have to create a report. But this time format seems to be really complex.
Can anyone help me to write the query pls?

View 1 Replies View Related

Selecting From Multiple Time Periods

Apr 11, 2008

Your help is greatly appreciated. How do you query each one of the following:

1) SELECT FieldValue WHERE DateTime is from 8:30AM - 12:00PM and 6:00PM - 9:30PM on Mondays thru Fridays (i.e. exclude Sat & Sun) for the whole month of January 2008.

2) SELECT FieldValue WHERE DateTime is from 9:30PM - 8:30AM on Mondays thru Fridays, AND ALL-DAY on Saturdays & Sundays for the whole month of January 2008.

Thank you in advance.

View 8 Replies View Related

Wrting A Query For A Report With Different Time Periods

Jan 10, 2008



There are three tables Loans, CDs and Account.

I want to create a report based on above three tables
It looks like as follows;
















Program Summary

Yesterday/Current
MTD
Previous Month
YTD




Amount
Number
Amount
Number
Amount
Number
Amount
Number

Portfolio












Loans Commenced

$
#
$
#
$
#
$
#


Loans Closed

$
#
$
#
$
#
$
#


CDs Commenced

$
#
$
#
$
#
$
#


CDs Closed

$
#
$
#
$
#
$
#















Loan table - Amount, State
CD - Amount, State
Account - CommencedOnDate(date time), closeondate(date time)

Yesterday - Loans/CDs started yesterday(calander date..not last 24 hours)
MTD - " " First of this month to yesterday
Previous Month - " " during previous month
YTD - " " Loans/CDs started from 1 of this year to yesterday

Loan and cd states are Commenced and Closed

Based on this I have to create a report. But this time format seems to be really complex.
Can anyone help me to write the query pls?

View 7 Replies View Related

Power Pivot :: Aggregating Time Periods In Cube-member / Cube-value Formulas?

Aug 23, 2015

I am just starting out using CUBEMEMBER/CUBEVALUE formulas in excel linked into a sql olap db - using this method for some custom reports where pivot tables are not suitable.
The time dimension values include Months, Quarters and Years and the CUBEMEMBER formulas like

=CUBEMEMBER("OLAPCUBE","[Time].[Time].[Year].&[2015].&[1].&[1]") work fine - 1st quarter 1st month etc.

Is there a straightforward notation to aggregate months or do I need to use a plus sign to add a number of CUBEMEMBER formulas together.In other words - Is there an easier way of for say jan to july 2015 totals than

=CUBEMEMBER("OLAPCUBE","[Time].[Time].[Year].&[2015].&[1]") + (CUBEMEMBER("OLAPCUBE","[Time].[Time].[Year].&[2015].&[2]")) + (CUBEMEMBER("OLAPCUBE","[Time].[Time].[Year].&[2015].&[3].&[7]"))

I haven't tested this but have assumed it works but a bit long and clumsy.

View 5 Replies View Related

Date Periods

Jun 20, 2007

Hi, this is my first post here, i'm working on a view wich I have to display the results by period.
1st period - Current month
2nd period - Last month
3rd period - Month before last
and so on.

How can I achieve this? of course I have a column wich has the date I want to use, I was thinking on semthing like:

case when DATEDIFF(M, TRXDATE, getdate()) <= 0 then ammount END as Period1
(TRXDATE and ammount are columns on my table)

Any ideas? would this work?

Thanks for your replies

View 2 Replies View Related

How To Compare Date Periods ?

Oct 10, 2005

Hi,
I need to compare 2 periods (start date / end date) in order to find out if the first period overlaps or in included in the second period.

any idea ???

thanks

View 14 Replies View Related

Number Of 'Periods' In A Date Range

Feb 10, 2006

Guys
Date brain killer - I have a startdate and enddate and need, for a given period length in months, to identify the number
of periods betwen the startdate and enddate
so for example

DECLARE @Periods TABLE
(
StartDate datetime,
Enddate datetime,
NumberOfMonthsInPeriod INT ,
TotPeriodsINT
)

-- Initial data
insert @Periods
(
StartDate ,
Enddate ,
NumberOfMonthsInPeriod ,
TotPeriods-- for this illustration, initialised to 0 but need to be UPDATEd as per detail below
)

select
'30-Sep-2005',
'10-Apr-2009',
1 -- 1 month period
0
union all
select
'30-Sep-2005',
'10-Apr-2009',
3 -- 3 month period
0
union all
select
'30-Sep-2005',
'10-Apr-2009',
6 -- 6 month period
0

The following rules regarding periods apply
Each 1 (NumberOfMonthsInPeriod) month period is as would be expected ie
01-Jan - 31 Jan
01-Feb - 28-Feb (ie 1st March - 1 day which would deal with leap years - dateadd(...)
and so on to December

Each 3 (NumberOfMonthsInPeriod) month period is one of the following 'bands' per year
01-Jan - 31-Mar
01-Apr - 30-Jun
01-Jul - 30-Sep
01-Oct - 31-Dec

Each 6 (NumberOfMonthsInPeriod) month period is one of the following
01-Jan - 30-Jun
01-Jul - 31-Dec

I need to derive TotPeriods as follows:

For the row where NumberOfMonthsInPeriod = 1, the first period ie the one the start date falls within is 01-Sep-2005 to 30-Sep-2005, second is 01-Oct-2005 - 31-Oct-2005 and so on until
last period ie the one the end datye falls within is 01-Apr-2009 - 30-Apr-2009, a TotPeriods value of 44

For the row where NumberOfMonthsInPeriod = 3, first period is 01-Jul-2005 to 30-Sep-2005, second is 01-Oct-2005 - 31-Dec-2005 and so on until
last period is 01-Apr-2009 - 30-Jun-2009, a TotPeriods value of 16

For the row where NumberOfMonthsInPeriod = 6, first period is 01-Jul-2005 to 31-Dec-2005, second is 01-Jan-2006 - 30-Jun-2006 and so on until
last period is 01-Jan-2009 - 30-Jun-2009, a TotPeriods value of 8

Hope this is clear and thanks in advance

View 3 Replies View Related

Comparing Two Date Periods For Overlapping

Nov 9, 2006

hi guys,

i have a booking table which has the following columns...

booking
-------------------------------------------
dCheckin (format 11/9/2006 12:00:00 AM)
dCheckout (format 11/11/2006 12:00:00 AM)

when a new booking is entered, we want to make sure that the period entered does not conflict with an existing record.

not sure how to go about building the query required. any help would be greatly appreciated.

mike

View 4 Replies View Related

Subtracting Periods That Are In YYYYMM Format?

Mar 28, 2014

I have a Column in my data that gives a financial period value in the YYYYMM format. i.e. an asset was re-valued in a particular period for example 201301. I need to find out the number(count) of periods(months) between another given period for example current period (201403) and the period provided in the table i.e. 201301.

Is this possible in the SQL Database?

View 2 Replies View Related

Grouping Data Into Periods For Reporting

Aug 17, 2007

Hi there.

I am working on a set of reports where I am summing/averaging data elements based on what period they are in. For example, the report output should look something like this:









Period
Sum

May '07
41

April '07
14

Q2 '07
55

March '07
36

February '07
28

January '07
22

Q1 '07
86

June '07
N/A

YTD '07
141

December '06
33

November '06
27

October '06
42

Q4 '06
102

September '06
58

August '06
84

July '06
52

Q3 '06
194

June '06
40

May '06
41

April '06
14

Q2 '06
95

March '06
67

February '06
38

January '06
N/A

Q1 '06
105

YTD '06
496


For each of the items I am summing, all I have is a datetime of when the event happened. This is a relational database (not a cube), so I am struggling with how to create the 'buckets' based on period. I think the best way is to dynamically create the buckets based on a given date. Is there a way in RS that it can do this bucketing for you?

Thanks, Mike

View 4 Replies View Related

Query/View: The 2 Newest Periods For Each Indicator

Mar 24, 2006

Hi,I'm working on a simple performance-program, where I need to extractinformation from the 2 newest periods for every performance-indicator- And from there calculate a trend between these results.The problem is, that I can't find a simple way to extract the 2 latestresults.The Table (Table1) looks like this:kpiIDperiodIDActualAcceleration23Acceleration54Speed1100Speed4200Speed7220Speed9180Weight122Weight332Weight721Weight1033If I want to extract the newest I use something like this (made it inMS Access, so the syntax might differ slightly from SQLServer):SELECT table1.kpiID, table1.periodID, table1.ActualFROM table1 WHERE table1.periodID = (SELECT max(t.periodID) fromtable1 as t WHERE t.kpiID=table1.kpiID);BUT - how how do I get the second-newest period as well?Preferably I would like the final result to be a View with thefollowing fields:kpiID, periodID_newest, Actual_newest, periodID_sec_newest,Actual_sec_newestAlternatively a View with 2 posts for each performace-indicator.Thanks in advanceRyan

View 10 Replies View Related

Format Masking For Creating Leading Periods

Dec 13, 2006

Is there an elegant way to fill the empty space leading a textbox in a table with periods, similar to a table of contents effect?

When I do not allow the textbox to grow and just append a long string of periods it looks fine in my report preview, but after I deploy everything appended after the primary field in that text box is missing?

My report has a lot of data to the right but it is collapsible so the fields to the left are a good distance away. This is why I am trying to include light visual aids that assist lining up data values. I am not stuck on the leading period idea but it seems the least cluttered.

Aaron

View 2 Replies View Related

Need SQL For Finding Gaps Comparing Two Sets Of Periods

Feb 22, 2008

Hi all,
I have two tables - Planning and Appointments:

Planning - contains a list of planned items. Used to define boundaries for a work day and defines based on type what can be done for each item.
Id,
TypeId - the type of the planned items

BeginTime DateTime - begin date and time of the planned item
EndTime DateTime - end date and time for the planned item

In the Planning table we can have as many records per day as we need:

1, First Meeting, 1 Jan 2008 09:00, 1 Jan 2008 11:00
2, First Meeting, 1 Jan 2008 11:00, 1 Jan 2008 12:00
3, First Meeting, 1 Jan 2008 13:00, 1 Jan 2008 15:00
4, First Meeting, 1 Jan 2008 15:00, 1 Jan 2008 18:00

Appointments - contanis a list with appointments
Id,

BeginTime DateTime
EndTime DateTime


1, 1 Jan 2008 09:00, 1 Jan 2008 09:30
2, 1 Jan 2008 10:00, 1 Jan 2008 11:00
3, 1 Jan 2008 11:00, 1 Jan 2008 11:30
4, 1 Jan 2008 14:00, 1 Jan 2008 15:30

What is needed?
What I need is to a find a way to compare the planned items with the appointments and to return all the periods for which a planned time exists:

Free planned time:
1, 1 Jan 2008 09:30, 1 Jan 2008 10:002, 1 Jan 2008 11:30, 1 Jan 2008 12:00
3, 1 Jan 2008 13:00, 1 Jan 2008 14:00
4, 1 Jan 2008 15:30, 1 Jan 2008 18:00

So, having two multitudes of periods,where the one specifies the planning templates and the other real used time, I need to find all the periods which can be used for another appointments.
I've tried several aproaches, but I always faced performance problems.

Thanks in advance.

View 1 Replies View Related

How To Compute Biweekly Periods When Date Is Passed In As Parameter

Oct 7, 2014

How can I compute the biweekly periods when a date is passed in as a parameter, for example if the user enters 9/12/2014 I should get:

Friday /2nd half9/12/2014
Saturday9/13/2014
Sunday9/14/2014
Monday9/15/2014
Tuesday9/16/2014
Wednesday9/17/2014
Thursday9/18/2014
Friday/1st half 9/19/2014
Friday/2nd half9/19/2014
Saturday9/20/2014
Sunday9/21/2014
Monday9/22/2014
Tuesday9/23/2014
Wednesday 9/24/2014
Thursday9/25/2014
Friday/1st half 9/26/2014

View 2 Replies View Related

SQL Server 2012 :: CTE To Return All Periods Between First And Last Transaction Date

Jan 21, 2014

I'm trying to create a cte to return a list of lots and every period between the first and last transaction date for each lot. I've gotten this far:

SELECTIntLotKey
,DATEPART(YYYY, StartDate)StartYear
,DATEPART(MM, StartDate)StartPeriod
,DATEPART(YYYY, EndDate)EndYear
,DATEPART(MM, EndDate)EndPeriod

[Code] ....

This gives me the following results:

IntLotKeyStartYearStartPeriodEndYearEndPeriod
271532013120135
28468201312201312
2846920131201312
2847020131201312
28472201312201312
593022013120131
593032013120131

Now what I need is something that looks like this:

LotKeyYearPeriod
2715320131
2715320132
2715320133
2715320134
2715320135

[Code] .....

Some lots may not have any transactions for some of the periods between the start and end dates but I need to report every period between the start and end period for each lot. I have a period table that I thought I could use but haven't come up with a way to get the results I'm after.

View 9 Replies View Related

Transact SQL :: Date Value Between One Of The Calendar Periods In Multiple Rows?

Aug 20, 2015

Question: How to determine if a date value was between one of the date periods that appear in multiple rows?

Background: We have a table of "license valid" periods, wherein each license can have one or more rows.  (As you know, a driver's license can be started, expired, renewed, suspended, reinstated, revoked, etc.)  Instead of of having a license activity table--from which valid license periods could be extrapolated--we store just the periods for which a license was valid.

My task is to take a list of licenses and specific dates and determine if each license was valid as of that date, returning either true or false.  What is the best way to accomplish this?

DECLARE @ValidityInQuestion TABLE (
LicenseID int
, DateValidityInQuestion date);

DECLARE @LicenseValidPeriods TABLE (
LicenseID int
, BeginDate date
, EndDate date);

[Code] ...

 How then do I query both tables in order to get the same result that results from the following query?

SELECT
12345 AS LicenseID
, '2015-01-15' AS DateValidityInQuestion
, 1 AS LicenseActive
UNION
SELECT
67890
, '2015-02-04'
, 0;

I assume I need to join on the LicenseID columns, but my understanding stops there.

View 4 Replies View Related

Power Pivot :: Format Fin Period So A 0 Is In Front Of Periods 0-9

Aug 12, 2015

I have a [Fin Period] column which outputs a number between 1 and 12 depending on the financial period. For numbers 0-9 this is output as a single digit. How can I format this so it places a 0 in front of these numbers but not in front of periods 10-12?

View 2 Replies View Related

T-SQL (SS2K8) :: Create Periods Transaction Dates And Make Them Columns

Sep 4, 2014

I have a simple script where I want to pull GLAcct, GLDesc and Amounts by Period. I want my results to look like attached snip.

I tried playing around with the dates; however, I'm receiving errors. Just to note that when I ran for 07/01/14 - 07/31/14 with the transaction date in where clause I was able to retrieve the correct results. Now I want to expand to get a view set up for the whole year....automation!

select
gl_account.id as GLAcct,
gl_account.descr as GLDesc,
sum(gl_ledger.amount_n) as Net
from gl_account

[Code] ....

View 9 Replies View Related

Recovery :: How To Perform Server Database Backup Retention Periods

Sep 22, 2015

For the best practice I issued full SQL Server database, differential and transaction log backups.  I have setup a process to backup to local disks and then also copy the files to a centralized set of storage.  On a weekly basis the centralized file system is backed up to a tape backup device. I know I can get data off of the tapes, but that process is time consuming, not well tested from my perspective and I am not in control of the overall process.  Can you offer some recommendations from a SQL Server backup retention perspective?

View 6 Replies View Related

Analysis :: MDX To Filter For Completed Periods Only (part Of Annualized Calculation)

Sep 9, 2015

I have been following the tutorial/blog post HERE to create an annualization (or "run rate") of my Gross Amount measure.  What I want to do now is exclude any period that is not "complete".  

For example, if today is 9/9 then Q3 is not complete - only Q1 and Q2 are complete.  And if I'm looking at it monthly then January through August are complete, but September is not.

Cells B5 and D5 look exactly as I expect and want them to be. On row 6 below under each "Gross Annualized" value I have basically just put the formula for what it's actually doing.

What I would like to see in the blue cell is $67,211,697,268 - essentially the most recent annualization for a completed period. The annualization for Q3 is misleading because the quarter has not yet completed.  There's $16b in Q1 and $17b in Q2, so the measly $78m in Q3 (yellow cell) is dragging the annualization down significantly. Even worse, the Gross Amount for Q4 is being treated as a $0.00, which is further dragging down the "2015 Gross Annualized" amount in blue. In a T-SQL average calculation, for example, I think the green cell would be treated as NULL rather than $0.  That's kind of the behavior I want.

So I would like to do two things:

Create a calculation (probably just a 0 or 1 flag) that indicates whether the current period is complete or not.  Again, using 9/9/2015 as an example, Q2 would be complete but Q3 would not be. And August would be complete, but September would not. Make the blue cell show $67,211,697,268 - an annualization based on completed quarters only.

For whatever it's worth here is the current calculation for Gross Annualized.

CREATE MEMBER CURRENTCUBE.[Measures].[Gross YTD]
AS AGGREGATE(
YTD([Pay Date].[Calendar].CurrentMember)
,[Measures].[Gross Amount]),
FORMAT_STRING = "Currency",
VISIBLE = 0;

[Code] .....

View 2 Replies View Related

SQL Server 2014 :: Change Daily Info To Weekly Periods In Pivot Report

Sep 25, 2015

I create a report base on categories and sales of goods. Now I have Daily Info about all Products.

But I Need to present this report base on weekly periods. in pivotal format.

I family with pivotal format but change between daily report and weekly report is ambiguous for me.

View 3 Replies View Related

Power Pivot :: LY Sales - Function Throws Error When Selecting Periods In Different Years

May 21, 2015

I have created data model where I'm taking several sources of Point of Sale data (multiple retailers) and combing them using Power Pivot and a custom calendar. We get data retailer direct, which is mostly in weeks, and data from IRI which is in four week buckets. This does not allow me to use the date intelligence DAX functions. I'm brand new to DAX and my experience starts and ends with Excel. (Diagram view and link to file to come after account verification) .

The DAX code for calculating LY Sales is:

=
CALCULATE (
    [Sales $],
    FILTER (
        ALL ( dCalendar ),
        dCalendar[IRIYearNumber]
            = VALUES ( dCalendar[IRIYearNumber] ) - 1

[Code] ....

The filters are to prevent items not on the item table from showing on the report, and the customer filter is to prevent all the sales being rolled together as and extra line (with blank customer) on the report. 

The error happens when I select two periods that are in different years. When I select the 13 periods on 2014 all is well. But when I add a period from 2015 it throws the error below;

ERROR - CALCULATION ABORTED: Calculation error in measure 'dProducts'[LY Sales $]: A table of multiple values was supplied where a single value was expected. 

View 5 Replies View Related

How To Convert UTC Time (retrieved From SQL) To Local Time In Reporting Services Based On Time Zone

Aug 7, 2007



Hi all,

I have created a report in SSRS 2005 which is being viewed by users from different Time Zones.

I have a dataset which has a field of type datetime (UTC). Now I would like to display this Date according to the User Time Zone.

For example if the date is August 07, 2007 10:00 AM UTC,

then I would like to display it as August 07, 2007 03:30 PM IST if the user Time Zone is IST.


Similarly for other Time Zones it should display the time accordingly.

Is this possible in SSRS 2005?

Any pointers will be usefull...

Thanks in advance
sudheer racha.

View 5 Replies View Related

SQL 2012 :: Accurate Sorting Data Each Time With Millions Of Records Without Time Field?

Apr 25, 2014

Sample Table

USE [Testing]
GO
/****** Object: Table [dbo].[Testing] Script Date: 4/25/2014 11:08:18 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[Code] ....

It seems to work fine with one million records.

Each primary key is unique, but the begindate is non-unique, and i guess even if i use datetime2 and add nanoseconds, from what i have read, there is a chance that i could have a duplicate datetime since the date is imported via XML from multiple sources.

View 7 Replies View Related

SQL Server 2014 :: Gathering Stored Procedure Execution Time In Real Time?

Jun 11, 2015

Is there a way to keep track in real time on how long a stored procedure is running for? So what I want to do is fire off a trace in a stored procedure if that stored procedure is running for over like 5 minutes.

View 5 Replies View Related

Integration Services :: Exclude Time In Date Time Variable In SSIS For Loop?

Oct 22, 2015

I am trying to load previous days data at 3 am via a SSIS job.

The Date variable is initiated as DATEADD("dd",-1, GETDATE()) in the for loop.

Now, as this job runs at 3 am, and I set the variable as GETDATE() - 1, it excluded the data from 12 am to 3 am in the resultset as Date is set as YYYY-MM-DD 03:00:00:000 I need this to be set as YYYY-MM-DD 00:00:00:000

How can i do this? 

View 2 Replies View Related

Transact SQL :: Update Time Portion Of DateTime Field With Time Parameter

Oct 3, 2015

I hope to update a DateTime column value with a Time input parameter.  Poor attempt below but it looks like the @ApptTime param is coming in as 10:45:00.0000000 and I might have an existing @SendOnDate as: 2015-10-05 07:00:00.000...I hope to end up with 2015-10-05 10:45:00.000

ALTER PROCEDURE [dbo].[SendEditUPDATE]
@QuePoolID int=null
,@ApptTime time(7)
,@SendOnDate datetime

[code]...

View 14 Replies View Related

It Takes A Long Time To Insert The First Record Each Time When The Program Start

Dec 15, 2006

I am using VS2005 (VB) to develop a PPC WM5.0 Program. And I am using SQLCE 3.0. My PPC Hardware is in 400MHz.

The question is when the program try to insert the first record into sdf database after each time the program started. It takes a long time. Does anyone know why and how can I fix it?

I will load the whole database into a dataset when the program start and do all the "Insert", "Update", "Delete" in this dataset and fill it into database after each action.

        cn.Open()
        sda = New SqlCeDataAdapter(SQL, cn) 'SQL = Select * From Table
        scb = New SqlCeCommandBuilder(sda) 
        sda.Update(dataset)
        cn.Close()

I check the sda.update(), it takes about 0.08s for filling one record into database normally. But:

1. Start the PPC Program

2. Load DB into dataset

3. Create a ONE new record in dataset

4. Fill back to DB

When I take this four steps everytime, the filling time is almost 1s or even more!

Actually, 0.08s is just a normal case. Sometimes, it still takes over 1s to filling back a dataset which only inserted one record when the program is running. (Even all inserted records are exactly the same in data jsut different in the integer key)

 However, when I give up the dataset and using the following code:

            cn.Open()
            Dim cmd As New SqlCeCommand(SQL, cn) ' I have build the insert SQL before (Insert Into Table values(XXXXXXXXXXXXXXX All field)

           cmd.CommandType = CommandType.Text
            cmd.ExecuteNonQuery()
            cn.Close()
            StartTime = Environment.TickCount

 I found that it is still the same that the first inserted record takes more time, but just about 0.2s. And the normal insert time is around 0.02s. It is 4 times faster!!!

View 1 Replies View Related

Transact SQL :: Converting 24hrs Time To 12 Hours Time Query Format?

Apr 21, 2015

SELECT 
    CONVERT(VARCHAR(10),attnc_chkin_dt,101) as INDATE,
    CONVERT(VARCHAR(10),attnc_chkin_dt,108) as TimePart
FROM pmt_attendance

o/p
indate   04/18/2015
time part :17:45:00

I need to convert this 17:45:00 to 12 hours date format...

View 8 Replies View Related

Problem With Getdate() In Transaction Takes The Insert Time Instead Of The Commit Time

Nov 12, 2007

Hi,

We need to select rows from the database that have been recently inserted/updated. We have a main primary table (COMMIT_TEST) and a second update table (COMMIT_TEST_UPDATE). The update table contains the primary key and a LAST_UPDATE field which is a datetime (to tell us when an update occurred). Triggers on the primary table are used to populate the update table.

If we insert or update the primary table in a transaction, we would expect that the datetime of the insert/update would be at the commit, however it seems that the insert/update statement is cached and getdate() is executed at the time of the cache instead of the commit. This causes problems as we select rows based on LAST_UPDATE and a commit may occur later but the earlier insert timestamp is saved to the database and we miss that update.

We would like to know if there is anyway to tell the SQL Server to not execute the function getdate() until the commit, or any other way to get the commit to create the correct timestamp.

We are using default isolation level. We have tried using getdate(), current_timestamp and even {fn Now()} with the same results. SQL Queries that reproduce the problem are provided below:


/* Different functions to get current timestamp €“ all have been tested to produce the same results */
/*
SELECT GETDATE()
GO
SELECT CURRENT_TIMESTAMP
GO
SELECT {fn Now()}
GO
*/
/* Use these statements to delete the tables to allow recreate of the tables */
/*
DROP TABLE COMMIT_TEST
DROP TABLE COMMIT_TEST_UPDATE
*/
/* Create a primary table and an UPDATE table to store the date/time when the primary table is modified */
CREATE TABLE dbo.COMMIT_TEST (PKEY int PRIMARY KEY, timestamp) /* ROW_VERSION rowversion */
GO
CREATE TABLE dbo.COMMIT_TEST_UPDATE (PKEY int PRIMARY KEY, LAST_UPDATE datetime, timestamp ) /* ROW_VERSION rowversion */
GO
/* Use these statements to delete the triggers to allow reinsert */
/*
drop trigger LOG_COMMIT_TEST_INSERT
drop trigger LOG_COMMIT_TEST_UPDATE
drop trigger LOG_COMMIT_TEST_DELETE
*/
/* Create insert, update and delete triggers */
create trigger LOG_COMMIT_TEST_INSERT on COMMIT_TEST for INSERT as
begin
declare @time datetime
select @time = getdate()

insert into COMMIT_TEST_UPDATE (PKEY,LAST_UPDATE)
select PKEY, getdate()
from inserted
end
GO
create trigger LOG_COMMIT_TEST_UPDATE on COMMIT_TEST for UPDATE as
begin
declare @time datetime
select @time = getdate()

update COMMIT_TEST_UPDATE
set LAST_UPDATE = getdate()
from COMMIT_TEST_UPDATE, deleted, inserted
where COMMIT_TEST_UPDATE.PKEY = deleted.PKEY
end
GO
/* In our application deletes should never occur so we don€™t log when they get modified we just delete them from the UPDATE table */
create trigger LOG_COMMIT_TEST_DELETE on COMMIT_TEST for DELETE as
begin
if ( select count(*) from deleted ) > 0
begin
delete COMMIT_TEST_UPDATE
from COMMIT_TEST_UPDATE, deleted
where COMMIT_TEST_UPDATE.PKEY = deleted.PKEY
end
end
GO
/* Delete any previous inserted record to avoid errors when inserting */
DELETE COMMIT_TEST WHERE PKEY = 1
GO
/* What is the current date/time */
SELECT GETDATE()
GO
BEGIN TRANSACTION
GO
/* Insert a record into the primary table */
INSERT COMMIT_TEST (PKEY) VALUES (1)
GO
/* Simulate additional processing within this transaction */
WAITFOR DELAY '00:00:10'
GO
/* We expect at this point that the date is written to the database (or at least we need some way for this to happen) */
COMMIT TRANSACTION
GO
/* get the current date to show us what date/time should have been committed to the database */
SELECT GETDATE()
GO
/* Select results from the table €“ we see that the timestamp is 10 seconds older than the commit, in other words it was evaluated at */
/* the insert statement, even though the row could not be read with a SELECT as it was uncommitted */
SELECT * FROM COMMIT_TEST
GO
SELECT * FROM COMMIT_TEST_UPDATE


Any help would be appreciated, we understand we could make changes to the application/database to approximate what we need, but all the solutions have identified suffer from possible performance issues, or could still lead to missing deals (assuming the commit time is larger than some artifical time window).

Regards,

Mark

View 8 Replies View Related

DB Engine :: Time Testing Azure Point In Time Database Restores?

Sep 21, 2015

I need to do a time test for restoring an Azure SQL database from a point in time. Can I automate this through PowerShell.

View 3 Replies View Related

SQL 2012 :: Converting Time String In Temp Table To Military Time Then Cast As Integer?

Dec 26, 2014

I need to take a temporary table that has various times stored in a text field (4:30 pm, 11:00 am, 5:30 pm, etc.), convert it to miltary time then cast it as an integer with an update statement kind of like:

Update myTable set MovieTime = REPLACE(CONVERT(CHAR(5),GETDATE(),108), ':', '')

how this can be done while my temp table is in session?

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved