Getdate() and getutcdate()
HI,
I'm just wondering to know the difference between below
Select getdate()
2014-02-21 11:43:08.607
select GETUTCDATE()
2014-02-21 16:43:08.607
Why is the result is different and what is the difference between both?
getutcdate() giving as 4:43 feb 21st 2014 which is not yet.. Just wondering what is the difference between them?
Thanks.
GETUTCDATE() returns the current UTC time (Universal Coordinated Time); you should know this standard. Google it! Decades ago, this was called “Greenwich Mean Time” or “Zulu Time”; the Google articles will explain it. If you have a self-adjusting clock,
it looks for a time signal broadcast by NIST and other agencies.
GETDATE() is a 1970's Sybase function that got the local time from the particular Unix system clock (that is why we have those silly 3 decimal places in the seconds field). We do not use it any more. We have the ANSI/ISO Standard CURRENT_TIMESTAMP
along with DATE, TIME and DATETIME2(n) data type. This last one is the MS version of the ANSI/ISO Standard TIMESTAMP(n) construct.
The current local time is also called lawful time if it includes time zone value with DST (daylight Saving Time).
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL
Similar Messages
-
Getdate() and time comparison
Hi all, I've SBO and I'm trying to create a query, based on OQUT table, showing DocNum WHEN time of creation of the offer is less then 15 minutes than System time. I'm trying to compare DocTime and the time extracted with getdate() but I'm not able to do it. I think it's a problem of data type.
Is there anybody who can help me?
Thanks in advanceHi Federico,
You're correct, it's not possible to directly use DocTime for date comparisons because it's held as an integer value and not a DateTime value. You can do a little conversion though. Have a look here:
Re: GetDate() in query generator doesn' return the time!
Kind Regards,
Owen -
How to get current month from filename and bulk insert from text file into table?
I set up some dynamic SQL to help my bulk copy data from a text file to a table. This works fine for files that come in every day; I get the previous day’s data, based on the file name that’s placed
in the folder. That’s why I’m using the ‘-1’. The dates will look like this: '20140131', so I'm using type 112.
declare @fullpath1 varchar(1000)
select @fullpath1 = '''\\system.local\ms\london\FTP\' + convert(varchar, getdate()-1, 112) + '_INDEXPRICES_EOM.SPC'''
declare @cmd1 nvarchar(1000)
print (@cmd1)
select @cmd1 = 'bulk insert [dbo].[SB_Monthly] from ' + @fullpath1 + ' with (FIELDTERMINATOR = ''\t'', FIRSTROW = 5, LASTROW = 675, ROWTERMINATOR=''0x0a'')'
print(@cmd1)
exec (@cmd1)
I think the syntax will be somewhat similar to this:
YEAR(date_column)=YEAR(getdate()) AND MONTH(date_column)=MONTH(getdate())
I’m not totally sure how to incorporate that into my current syntax.
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.I tried a couple versions of this.
Declare @StartDate Date, @EndDate Date
Select @StartDate = convert(varchar, getdate()-28, 112), @EndDate = convert(varchar, getdate()-1, 112)
BEGIN
declare @fullpath1 varchar(1000)
select @fullpath1 = '''\\ms\london\FTP\' + ''' between ''' + Convert(Varchar(10), @StartDate, 101) + ''' and ''' + Convert(Varchar(10), @EndDate, 101) + '''_SP.SPC'''
declare @cmd1 nvarchar(1000)
print (@cmd1)
select @cmd1 = 'bulk insert [dbo].[SPBMI_Monthly] from ' + @fullpath1 + ' with (FIELDTERMINATOR = ''\t'', FIRSTROW = 5, LASTROW = 675, ROWTERMINATOR=''0x0a'')'
print(@cmd1)
exec (@cmd1)
END
Here’s the string:
bulk insert [dbo].[SPBMI_Monthly] from '\\ms\london\FTP\' between '02/03/2014' and '03/02/2014'_SP.SPC' with (FIELDTERMINATOR = '\t', FIRSTROW = 5, LASTROW = 675, ROWTERMINATOR='0x0a')
The error message I keep getting is:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'between'.
Msg 319, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
I feel like I’m already pushing this thing to the limit.
Maybe this last part isn’t possible.
Knowledge is the only thing that I can give you, and still retain, and we are both better off for it. -
Calculating CPI and SPI based on Costs Only - No Hours
Sometimes on our projects, our vendors provide a SOW in dollars, no hours and our internal customers work on projects as needed, also only assigning a dollar value to their efforts without hours. Based on the calculations for CPI (EV/AC) and SPI (EV/PV),
you need to assign work (hours) to tasks with dates as well as the costs. I am just curious as to if anyone knows of a way for Project 2007 to calc CPI and SPI on generic resources (cost) by just updating the actual dollars spent.Hi,
I have tried to put together some scripts that may help you. The sql script may need to be improved and be protected against errors, null values etc.
declare @AC float, @PV float, @EV float, @TPC float,@ProjectUID uniqueidentifier
Select @ProjectUID =''
select @AC=SUM(abd.AssignmentActualCost), @PV=SUM(ISNULL(abd.AssignmentBaseline0Cost,0)) from MSP_EpmAssignmentByDay_UserView abd
inner join MSP_EpmAssignment_UserView a on abd.AssignmentUID=a.AssignmentUID
inner Join msp_epmproject p on a.projectuid=p.projectuid
inner Join msp_epmresource r on a.resourceuid=r.resourceuid
where r.ResourceType in (25,26) and abd.TimeByday <= getdate() and a.Projectuid=@ProjectUID
select @TPC=SUM(ISNULL(abd.AssignmentBaseline0Cost,0)) from MSP_EpmAssignmentByDay_UserView abd
inner join MSP_EpmAssignment_UserView a on abd.AssignmentUID=a.AssignmentUID
inner Join msp_epmproject p on a.projectuid=p.projectuid
inner Join msp_epmresource r on a.resourceuid=r.resourceuid
where r.ResourceType in (25,26) and a.Projectuid=@ProjectUID
select @EV=(ProjectPercentCompleted*@TPC)/100 from MSP_epmProject_userview where ProjectUID=@ProjectUID
select @EV/@AC as CPI, @PV/@EV as CPI
Hope this helps
Paul -
Problem with SLQ Date and Daylight Saving Time
Hi everybody!
It seems, that when I have a date in the database, which falls on start of the daylight saving period, it is converted to the previous date.
Example: '2001-10-13' will become '2001-10-12' after doing a date = rs.getDate() and then converting back using date.toString().
This caused a lot of trouble because the date value is part of an unique key constraint!
Currently I wrote a wrapper method, which obtains the date as string and converts this one into a date by setting the hours to 12:00.
Does anybody know a straighter way to avoid the conversion?Because the default time zone is using day light saving time. To remove this feature, reset your default time zone at the very beginning of your program:
TimeZone.setDefault( new SimpleTimeZone( TimeZone.getDefault().getRawOffset(), TimeZone.getDefault().getID() ); -
I am trying to return results between a year or 365 days. I need to run this at any time and return a year prior. I'm not getting any results? Any help? THX!
SELECT
NAME.ID,
Activity.UF_2,
Name.FIRST_NAME,
Name.LAST_NAME,
Name.EMAIL,
Activity.TRANSACTION_DATE
FROM
Activity INNER
JOIN Name
ON Activity.ID
= Name.ID
Where
activity.TRANSACTION_DATE
BETWEEN
CAST(CAST(DATEADD(DAY,
-365,
GETDATE())
AS
DATE)
AS
DATETIME)
AND
DATEADD
(SECOND,
-1,
DATEADD(DAY,
1,
CAST(CAST(DATEADD(DAY,
-365,
GETDATE())
AS
DATE)
AS
DATETIME)))
and Activity.UF_1
=
'a'
and Activity.UF_2
=
'NAT'Where activity.TRANSACTION_DATE >= DATEADD(YEAR, -1, GETDATE()) AND activity.TRANSACTION_DATE < GETDATE()
-
10 customer and 10 employed sales
Hi experts,
I would like sorting
1. consumer sales and
2. employed sales
only for the 10 best every day how to make a query,
because the existing Query Engadget incompatible with the existing results on the sales analysis
SELECT top 10 T0.Cardcode,max(T0.CardName) as 'Customer',Sum(T0.doctotal) as 'Total Shopping' from dbo.ORDR T0
WHERE Month(T0.DocDate) = Month(GetDate()) AND Year(T0.DocDate) = Year(GetDate())
Group by T0.Cardcode
Order by Sum(T0.doctotal) desc
ThanksHello.. Good Morning Expert
Gordun thank you for answering my question
Your query has been working but goordun .. sorry, I mean really that there are 2 questions ..
A) Customer
B) Salesman..
so get 2 Query
A) Customer
SELECT top 10 T0.Cardcode,max(T0.CardName) as 'Customer',Sum(T0.doctotal) as 'Total Shopping' from dbo.ORDR T0
WHERE Month(T0.DocDate) = Month(GetDate()) AND Year(T0.DocDate) = Year(GetDate())
Group by T0.Cardcode
Order by Sum(T0.doctotal) desc
B) Salesman
SELECT top 10 T0.Cardcode,max(T0.CardName) as 'Customer',Sum(T0.doctotal) as 'Total Shopping' from dbo.ORDR T0
WHERE Month(T0.DocDate) = Month(GetDate()) AND Year(T0.DocDate) = Year(GetDate())
Group by T0.Cardcode
Order by Sum(T0.doctotal) desc
I want to get the updates ..
example ...
I execute the date 10 years 9 months 2009
will display like this
A)
Customer/ vendor code || customer || Total day|| DAY || shoping this month || ToTal Shopping
123456 || LILA || 31 || 9 || 4,291,050.00|| 5,844,472,759.15
B)
Salesman || Totalday || DAY || Shopping this month || ToTal Shopping
mercy || 31 || 9 || 7,020,392.00 || 194,243,452.00
thx... -
SQL Server 2000 database GETDATE() default for field
I have a SQL Server 2000 database where the createDate field
has a default value of GETDATE() and the data type is datetime. It
is inserting the date just fine, but I do not want to capture the
time along with the date. I only want the date to be entered. How
can I accomplish this? Thanks!IF you only wanted to store the date, then yes you would use
that as the column default value.
createDate datetime default convert(datetime,
convert(varchar, getDate(), 102), 102)
However, as paross1 cautioned be sure you understand you will
only be capturing the date from now on. If you change your mind
later, and decide you need both the created date and time, you will
be seriously out of luck. A safer choice might be to keep the date
and time, and use convert in your queries instead. -
Dear Forums,
If i want to get this report ;
Item Code / Qty Sales (accumulate this month) / Days (how many days till this month) / Total days in this month
eg . April 21
542514 / 2.563 / 21 / 30
can any one show me the query? thanksThe "Union" is to list the all the items which has stock >0 and items not in Invoice
SET ARITHABORT OFF SET ANSI_WARNINGS OFF
SELECT T0.ItemCode, T0.Dscription,T1.OnHand, convert(varchar,SUM(T0.BaseQty*T1.NumInSale)) AS 'Qty Sales',DAY(GetDate()) as 'Days',
Case WHEN Month(GetDate()) in (1,3,5,7,8,10,12) THEN 31 WHEN Month(GetDate()) in (2,4,6,9,11) THEN 30 ELSE 28 END AS 'Total days'
,convert (varchar,(t1.onhand/(SUM(T0.BaseQty*T1.NumInSale)/DAY(GetDate())* Case WHEN Month(GetDate()) in (1,3,5,7,8,10,12) THEN 31 WHEN Month(GetDate()) in (2,4,6,9,11) THEN 30 ELSE 28 END)))AS 'TURN OVER IN MONTH'
FROM DBO.INV1 T0 INNER JOIN DBO.OITM T1 ON T0.ItemCode = T1.ItemCode
WHERE Month(T0.DocDate) = Month(GetDate()) AND Year(T0.DocDate) = Year(GetDate())
GROUP BY T0.ItemCode,T0.Dscription,T1.OnHand
union
SELECT T1.ItemCode, T1.itemname,T1.OnHand, '' AS 'Qty Sales',DAY(GetDate()) as 'Days',
Case WHEN Month(GetDate()) in (1,3,5,7,8,10,12) THEN 31 WHEN Month(GetDate()) in (2,4,6,9,11) THEN 30 ELSE 28 END AS 'Total days'
,'No Sales' AS 'TURN OVER IN MONTH'
FROM DBO.OITM T1
WHERE T1.ITEMCODE NOT IN (SELECT ISNULL(ITEMCODE,0) FROM INV1)
AND T1.ONHAND>0
GROUP BY T1.ItemCode,T1.itemname,T1.OnHand
ORDER BY 1
Please let me know whether out is correct. If so i will try to include the A/R Credit Memo also -
DATEADD excluding weekends and holidays
select getdate(),dateadd(day,15,Getdate())
THis gets me today and 15 days from now. However I need 15 business days. I need to exclude weekends and holidays in here so that is looks like this.
where fulldate between getdate() and dateadd(day,15,Getdate())
I have a dim table for dates and have an isholiday = 0 or 1. I just can't figure out how to include this in the DATEADD expression.Hi,
try this link
http://www.sqlservercentral.com/Forums/Topic1247790-391-1.aspx
Hope will help you,
Questo post è fornito "così com'è". Non conferisce garanzie o diritti di alcun tipo. Ricorda di usare la funzione "segna come risposta" per i post che ti hanno aiutato a risolvere il problema e "deseleziona
come risposta" quando le risposte segnate non sono effettivamente utili. Questo è particolarmente utile per altri utenti che leggono il thread, alla ricerca di soluzioni a problemi similari. ENG: This posting is provided "AS IS"
with no warranties, and confers no rights. Please remember to click "Mark as Answer" on the post that helps you, and to click "Unmark as Answer" if a marked post does not actually answer your question. Please Vote This As
Helpful if it helps to solve your issue. This can be beneficial to other community members reading the thread. -
Add Row Number and use it to calculate other column
Hi,
I have below query which I am using to generate a report.
Select (count(I.Colour)*3) as TotLitres, (count( distinct P.description)) as NumOfMachine,
(count(I.Colour)*3)/(count( distinct P.description)) as AverageLiter,
DATEName(MONTH,ShipDate) + ' ' + convert(varchar,DATEPART(year, shipDate)) as [Loaded Date],
(count(I.Colour)*3)+ ((count(I.Colour)*3)/(count( distinct P.description)))* 4 as FutureSales
from DATATab I inner join Inktab P on I.SerialNum =P.SerialNum
where
I.Colour in ('Cyan','Magenta','Yellow','Black','Light Cyan','Light Magenta','Light Yellow','Light Black','Orange','White','Matte Black')
and I.ShipDate between dateadd(YY,-1,getdate()) and dateadd(YY,-1,dateadd(mm,6,getdate()))
group by DATEPART(year, shipDate),DATEName(MONTH,ShipDate),DATEPART(MONTH, shipDate)
order by DATEPART(year, shipDate),DATEPART(MONTH, shipDate)
Now I want to add two more columns to my select statement.
1. Row count
2. AverageLiter * Row count
Can someone please guide me on how i can achive that.
Thanks in advance .select *,(v.Row*v.AverageLiter) as Calculatedvalue from (
Select ROW_NUMBER()
OVER (ORDER BY [CreateDate]) AS Row, (count(I.Colour)*3) as TotLitres, (count( distinct P.description)) as NumOfMachine,
(count(I.Colour)*3)/(count( distinct P.description)) as AverageLiter,
DATEName(MONTH,ShipDate) + ' ' + convert(varchar,DATEPART(year, shipDate)) as [Loaded Date],
(count(I.Colour)*3)+ ((count(I.Colour)*3)/(count( distinct P.description)))* 4 as FutureSales
from DATATab I inner join Inktab P on I.SerialNum =P.SerialNum
where
I.Colour in ('Cyan','Magenta','Yellow','Black','Light Cyan','Light Magenta','Light Yellow','Light Black','Orange','White','Matte Black')
and I.ShipDate between dateadd(YY,-1,getdate()) and dateadd(YY,-1,dateadd(mm,6,getdate()))
group by DATEPART(year, shipDate),DATEName(MONTH,ShipDate),DATEPART(MONTH, shipDate)
order by DATEPART(year, shipDate),DATEPART(MONTH, shipDate) ) v
please mark as answered if it helps :) -
How to remove and add plotted data?
In my code below I would like to add two buttons and by clicking on a button("Remove") it will remove one by one plotted data,and plot it back by clicking on the button("Add") such as the examples:
Full data plotted by running the class
Now by a single click on a Remove button last data point disappear
another click and again last data point disappear, and so on
The inverse operation would be performed by clicking on "Add" button: each click will add back a data point
import javafx.application.Application;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.EventHandler;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
public class XYMove extends Application {
BorderPane pane;
XYChart.Series series1 = new XYChart.Series();
SimpleDoubleProperty rectinitX = new SimpleDoubleProperty();
SimpleDoubleProperty rectX = new SimpleDoubleProperty();
SimpleDoubleProperty rectY = new SimpleDoubleProperty();
@Override
public void start(Stage stage) {
final NumberAxis xAxis = new NumberAxis(12, 20, 1);
double max = 12;
double min = 3;
max *= (1+((double)3/100));
min *= (1-((double)3/100));
final NumberAxis yAxis = new NumberAxis(min, max, 1);
xAxis.setAnimated(false);
yAxis.setAnimated(false);
yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis) {
@Override
public String toString(Number object) {
return String.format("%2.0f", object);
final LineChart<Number, Number> lineChart = new LineChart<Number, Number>(xAxis, yAxis);
lineChart.setCreateSymbols(false);
lineChart.setAlternativeRowFillVisible(false);
lineChart.setAnimated(false);
lineChart.setLegendVisible(false);
series1.getData().add(new XYChart.Data(1, 3));
series1.getData().add(new XYChart.Data(2, 8));
series1.getData().add(new XYChart.Data(3, 6));
series1.getData().add(new XYChart.Data(4, 7));
series1.getData().add(new XYChart.Data(5, 5));
series1.getData().add(new XYChart.Data(6, 6));
series1.getData().add(new XYChart.Data(7, 4));
series1.getData().add(new XYChart.Data(8, 7));
series1.getData().add(new XYChart.Data(9, 6));
series1.getData().add(new XYChart.Data(10, 7));
series1.getData().add(new XYChart.Data(11, 6));
series1.getData().add(new XYChart.Data(12, 7));
series1.getData().add(new XYChart.Data(13, 6));
series1.getData().add(new XYChart.Data(14, 12));
series1.getData().add(new XYChart.Data(15, 10));
series1.getData().add(new XYChart.Data(16, 11));
series1.getData().add(new XYChart.Data(17, 9));
series1.getData().add(new XYChart.Data(18, 10));
pane = new BorderPane();
pane.setCenter(lineChart);
Scene scene = new Scene(pane, 800, 600);
lineChart.getData().addAll(series1);
stage.setScene(scene);
scene.setOnMouseClicked(mouseHandler);
scene.setOnMouseDragged(mouseHandler);
scene.setOnMouseEntered(mouseHandler);
scene.setOnMouseExited(mouseHandler);
scene.setOnMouseMoved(mouseHandler);
scene.setOnMousePressed(mouseHandler);
scene.setOnMouseReleased(mouseHandler);
stage.show();
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_PRESSED) {
rectinitX.set(mouseEvent.getX());
else if (mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED || mouseEvent.getEventType() == MouseEvent.MOUSE_MOVED) {
LineChart<Number, Number> lineChart = (LineChart<Number, Number>) pane.getCenter();
NumberAxis xAxis = (NumberAxis) lineChart.getXAxis();
double Tgap = xAxis.getWidth()/(xAxis.getUpperBound() - xAxis.getLowerBound());
double newXlower=xAxis.getLowerBound(), newXupper=xAxis.getUpperBound();
double Delta=0.3;
if(mouseEvent.getEventType() == MouseEvent.MOUSE_DRAGGED){
if(rectinitX.get() < mouseEvent.getX()&& newXlower >= 0){
newXlower=xAxis.getLowerBound()-Delta;
newXupper=xAxis.getUpperBound()-Delta;
else if(rectinitX.get() > mouseEvent.getX()&& newXupper <= 22){
newXlower=xAxis.getLowerBound()+Delta;
newXupper=xAxis.getUpperBound()+Delta;
xAxis.setLowerBound( newXlower );
xAxis.setUpperBound( newXupper );
rectinitX.set(mouseEvent.getX());
public static void main(String[] args) {
launch(args);
}Thanks!I would use an ObservableList (probably backed by a LinkedList) of XYChart.Data to store the collection of "deleted" data points. Create the buttons as usual; your "Remove" button's event handler should remove the last element of the series and add it to the first element of the deleted items data points. The "Add" button should remove the first element of the deleted data points and add it to the end of the series. You can bind the "disable" property of the remove and add button to Bindings.isEmpty(series1.getData()) and Bindings.isEmpty(deletedDataPoints), respectively.
Something like
ObservableList<XYChart.Data<Number, Number>> deletedDataPoints = FXCollections.observableList(new LinkedList<XYChart.Data<Number, Number>>());
removeButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
deletedDataPoints.add(0, series1.getData().remove(series1.getData().size()-1));
addButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
series1.getData().add(deletedDataPoints.remove(0));
removeButton.disableProperty().bind(Bindings.isEmpty(series1.getData()));
addButton.disableProperty().bind(Bindings.isEmpty(deletedDataPoints));The other approach would be to use a separate List for all the data points, and keep an integer variable storing the number of data points displayed. Your "remove" button would decrement the number displayed, and your "add" button would increment the number displayed. Both would also call
series1.getData().setAll(allDataPoints.sublist(0, numberOfDisplayedPoints));You might even be able to make the numberOfDisplayedPoints an IntegerProperty and bind the data property of the series to it in a nice way. This approach probably doesn't perform as well as the previous approach (using a stack of deleted points), because you are not directly giving the chart as much detailed information about what has changed.
Both approaches get problematic (in the sense that you need to carefully define your application logic, and then implement it) if the underlying data has the potential to change. -
Date difference in Days,hours minutes and seconds.
Hi All,
I have two date Suppose one is getdate() and other one is gatedate() +1 .I have to show the difference, currently I used a datediff in the stored proc which just shows the difference of the days :( but i need to show the difference in days:hours:minutes:seconds if possible.
its a countdown with the current date. Like the two fields are sale_start_date and sale_end_date. Hope i am clear.
Please let me know ASAP thanks in advance.Can anyone help me?all help is great help.
Say the difference of
12/6/2007 7:00:00 AM, 12/8/2007 8:00:00 AM as 2 days 1:00:00)
Thanks
NOne of the problems of using DATEDIFF when dealing with either seconds or milliseconds is that this function will result in execution errors if the start and end dates span then entire domain of possible dates. Below is an alternative that seems to work over the entire date domain. A couple of things to note:
1. This select converts the days and seconds of each date into BIGINT datatypes to avoid the overflow error
2. This select uses a CROSS APPLY operator; in this case I chose CROSS APPLY to suggest the possibility of converting this select into an inline table function.
I suspect that if you dig around this forum and the net that you will find a better routine, but here is yet another alternative:
declare @test table
( startDate datetime, endDate datetime)
insert into @test values
('6/1/9', getdate()),
('6/9/9 15:15', '6/10/9 19:25:27.122'),
('6/9/9 15:15', '6/10/9 13:25:27.122'),
('6/9/9', '6/10/9 00:00:01'),
('1/1/1760', '12/31/2999')
select
startDate,
endDate,
[Days],
[Hours],
[Minutes],
[Seconds]
from @test
cross apply
( select
cast((endSecond - startSecond) / 86400 as integer) as [Days],
cast(((endSecond - startSecond) % 86400) / 3600 as tinyint) as [Hours],
cast(((endSecond - startSecond) % 3600) / 60 as tinyint) as [Minutes],
cast((endSecond - startSecond) % 60 as tinyint) as [Seconds]
from
( select
86400 * cast(convert(integer, convert(binary(4),
left(convert(binary(8), startDate),4))) as bigint)
+ cast(convert(integer, convert(binary(4),
right(convert(binary(8), startDate),4)))/300 as bigint)
as startSecond,
86400 * cast(convert(integer, convert(binary(4),
left(convert(binary(8), endDate),4))) as bigint)
+ cast(convert(integer, convert(binary(4),
right(convert(binary(8), endDate),4)))/300 as bigint)
as endSecond
) q
) p
/* -------- Sample Output: --------
startDate endDate Days Hours Minutes Seconds
2009-06-01 00:00:00.000 2009-06-22 08:28:36.670 21 8 28 36
2009-06-09 15:15:00.000 2009-06-10 19:25:27.123 1 4 10 27
2009-06-09 15:15:00.000 2009-06-10 13:25:27.123 0 22 10 27
2009-06-09 00:00:00.000 2009-06-10 00:00:01.000 1 0 0 1
1760-01-01 00:00:00.000 2999-12-31 00:00:00.000 452900 0 0 0
(5 row(s) affected)
EDIT:
I based the routine more-or-less on Thilla's reply.
Kent Waldrop -
PowerShell and SQL Server Trigger
I had the following trigger written but apparently our IT department has not set up server/account or whatever needs to be done to use SQL Server's DB Mail.
ALTER TRIGGER [dbo].[Faxiles_Trigger]
ON [dbo].[DummyFQF]
AFTER INSERT
AS
BEGIN
DECLARE @tableHTML NVARCHAR(MAX) ;
SET @tableHTML =
N'<H1>Fax Error Report</H1>' +
N'<table border="1">' +
N'<tr><th>[FileID]</th>
<th>[FaxID]</th>
<th>[FilePath]</th></tr>' +
CAST ( (
SELECT
td=T1.[FileID],' ',
td=T1.[FaxID],' ',
td=T1.[FilePath],' '
FROM
FaxQueueFiles as T1
INNER JOIN
FaxQueue as T2
ON
T1.[FaxID] = T2.[FaxID]
WHERE
T2.[DateAdded] between Dateadd(hour,-1,GETDATE()) and Getdate()
AND
T1.[FilePath] NOT LIKE 'C:\%'
FOR XML PATH('tr'), TYPE
) AS NVARCHAR(MAX) ) +
N'</table>' ;
EXEC msdb.dbo.sp_send_dbmail
@recipients='[email protected]',
@subject = 'Fax Error Report',
@body = @tableHTML,
@body_format = 'HTML';
END
How can I instead make the trigger envoke/call a powershell script that can perform the same query and send an e-mail?
Apparently we do have e-mail functionality for our scripts, so that part I can just copy/paste from a pre-existing script. What I don't know how to do (since I am brand new to powershell scripting) is save the results of a query into a HTML-f0rmatted table
as the body of the e-mail like I did with SQL.
Thanks in advance for any assistance you can provide.
# Connect to the database.
$dbConnSites = New-Object System.Data.SqlClient.SqlConnection("Data Source=localhost;Initial Catalog=Main;Integrated Security=SSPI");
# Open database connection.
$dbConnSites.Open();
# Query String
$dbQry_BadTIFs = "
SELECT
T1.[FileID], T1.[FaxID], T1.[FilePath]
FROM
Main.FaxQueueFiles as T1
INNER JOIN
FaxQueue as T2
ON
T1.FaxID = T2.FaxID
WHERE
T2.[DateAdded] between DATEADD(hour,-1,GETDATE()) and GETDATE()
AND
T1.[FilePath] NOT LIKE 'C:\%'
# Create an SQL Command to execute the above query using the database connection object
$dbGetBadTIFs = New-Object System.Data.SqlClient.SqlCommand(dbQry_BadTIFs, $dbConnSites);
# Reader object to read the results of the executed SQL Command
$dbGetBadTIFsReader = $dbGetBadTIFs.ExecuteReader();
# Loop through the results of GetBadTIFs
while ($dbGetBadTFIsReader.Read())
# Close all the database connections
$dbConnSites.Close();
The above code is what I've come up with so far.... So within my while loop I presume the E-mail will some how be generated?
Should I declare a new string object and concatenate within the loop?
# Start the HTML Table for the e-mail
$str_EmailBody = "
<H1>Fax Error Report<H1>
<TABLE border=`"1`">
<TR>
<TH>[FileID]</TH>
<TH>[FaxID]</TH>
<TH>[FilePath]</TH>
</TR>
</TABLE>
# Loop through the results of GetBadTIFs
# to fill out the HTML Table
while ($dbRdr_GetBadTIFs.Read())
$str_EmailBody += "???";
# Finish the HTML Table for the e-mail
$str_EmailBody += "
</TR>
</TABLE>";
-Nothing to see. Move along.Hi Blacksaibot,
If you want to query the sql cmd and send eamil with the result, please refer this script, to save the result of the query, plrease try to create a sql datatable:
PowerShell Display Table In HTML Email
If I have any misunderstanding, please let me know.
Best Regards,
Anna -
Dates and forms with JDBC - there must be a better way...
Hi,
I have a backing bean (CustomerBean) extended from class Customer that talks to a DOA for access to a JDBC pooled resource.
I am having trouble getting an elegant solution for getting dates in and out of the DB using JSF forms.
My Customer class defines the date as java.sql.Date - passing that through to the form gives errors during validation. The work around I managed to get working is for the CustomerBean to have a method that converts a java.util.Date to a java.sql.Date.
public void setStartDate(java.util.Date startDate) {
if (startDate == null)
super.setStart(null);
else
super.setStart(new java.sql.Date(startDate.getYear(),startDate.getMonth(),startDate.getDate()));
and
public java.util.Date getStartDate() {
return super.getStart();
using:
<h:outputLabel value="Start"/>
<h:inputText id="startDate" value="#{customerBean.startDate}" required="false">
<f:convertDateTime pattern="dd/MM/yyyy"/>
</h:inputText>
<h:message for="startDate" styleClass="message"/>
the super property 'start' is a java.sql.Date. The line that bothers me is:
super.setStart(new java.sql.Date(startDate.getYear(),startDate.getMonth(),startDate.getDate()));
it uses deprecated constructor. (java.sql.Date(int year, int month, int day);
Where should I be looking for a more elegant solution? (GregorianCalendar? Anything else?)
Thanks in advance,
- DavidThanks...
I did it this way:
Customer.java has...
private java.sql.Date start;
and getters and setters...
CustomerBean.java extends Customer, has no field but the getters and setters...
public java.util.Date getStartDate() {
return super.getStart();
public void setStartDate(java.util.Date startDate) {
if (startDate == null)
super.setStart(null);
else
super.setStart(new java.sql.Date(startDate.getTime()));
seems to work and my customer has it's dates as sql dates (that way I only convert dates when I actually need them updateable on screen rather than each read of a customer record from the DB.)
To display the date I use
<h:outputText value="#{customerBean.startDate}">
<f:convertDateTime dateStyle="full"/>
</h:outputText>
To edit it, I use
<h:inputText id="startDate" value="#{customerBean.startDate}" required="false">
<f:convertDateTime dateStyle="short"/>
</h:inputText>
Is this a valid or recommended way?
- David
Maybe you are looking for
-
Error "there was a problem connecting to the server" came up when trying to scant to email on my Chromebook via the clouds. Was working. prior to being shut down for a week while on vacation. I can scan to a ssd chip and get to PC that way. I pr
-
Hi ,, Can any one explain me ,,if you select date of price determination as "GR date".. what exctly this price determination takes place. As per my understanding ,, it will pick the latest price available in purchase order at the time of GR .,, ie,,
-
Can't restore nor can I turn off my iPod
HELP! My iPod is connected since last night to my laptop and I keep getting an error saying could not be restore 0xE800006B. Also it is impossible to turn off my iPod so I have to leave it connected to my laptop so that I don't drain the battery. My
-
Hi, I want to include two fields of custom infotype in dynamic selection of LDB so that they are handeled automatically by LDB while selection. can anyone tell me how to achieve the same? Thanks -Aleria
-
Hi, like datagrid in dotnet,is it possible to add selectbox in cfgrid and also capturing events of selectbox. Advance Thanks,