Sybase get today result, two way comparison - sybase

I don't know how to test the performance of these two way of getting what i want.
select *
from table
where column like '%'+left(getdate(),11)+"%
select *
from table
where
DATEPART (DD, column) = DATEPART (DD, GETDATE())
AND DATEPART (MM, column) = DATEPART (MM, GETDATE())
AND DATEPART (YY, column) = DATEPART (YY, GETDATE())

Typically in SQL you can just loop through executing the statement however many times and calculating the time to execute for each statement. Do this a few times to be sure and compare the results.
declare #startTime datetime
declare #endTime datetime
declare #execution BIGINT
SET #execution = 0
set #startTime = GETDATE()
while (#execution < 1000000)
begin
--TestSyntax goes here
SET #execution = #execution + 1
end
set #endTime = GETDATE()
SELECT DATEDIFF(ms, #endTime, #startTime) AS 'TimeToExecute'
Also know, string comparisons are typically slower in all languages.

Related

How to subtract two date as datetime2 format in Sql Server 2008

How can I create a method to subtract two dates and this is equal to in real date as format datetime2(7) in sql server 2008.
For example ,I create this method:
Delete from TblMessage
Where MDateTime<((SELECT TOP (1)MDateTime FROM TblMessage ORDER BY MDateTime DESC)- ('2013-10-04 16:47:56.0000000'))
but it is not working .I want to result of subtract two date like this:
MDateTime1:2013-10-05 16:47:56.0000000
MDateTime2:2013-09-04 16:47:56.0000000
Result:2013-01-01 00:00:00.0000000
Result=MDateTime1-MDateTime2
How can I do this. Thanks...
Perhaps you are looking for this?
select DATEADD( day, datediff(day,GETDATE(), getdate() - 10), GETDATE() ) ;
DATEDIFF(dayofyear,MDateTime1,MDateTime2) AS Result
http://msdn.microsoft.com/en-us/library/ms189794.aspx
DECLARE
#DATE1 DATETIME = '2013-10-05 16:47:56.000',
#DATE2 DATETIME = '2013-09-04 17:37:42.000',
#DATEDIFF AS INT,
#BASEDATE DATETIME;
-- USE WHAT EVER DATE YOU WISH TO BE YOUR BASE DATE
SET #BASEDATE = '1/1/1900';
SET #DATEDIFF = DATEDIFF(SECOND, #DATE2, #DATE1);
SELECT #DATE1,#DATE2,#DATEDIFF, DATEADD(SECOND,#DATEDIFF,#BASEDATE)
Thus a scalar function could be created like this...
CREATE FUNCTION dbo.sf_GetMeasureDate
(
#EndDate DATETIME,
#StartDate DATETIME,
#BaseDate DATETIME
)
RETURNS DATETIME
AS
BEGIN
DECLARE #DATEDIFF AS INT
SET #DATEDIFF = DATEDIFF(SECOND, #StartDate, #EndDate);
Return DATEADD(SECOND,#DATEDIFF,#BASEDATE)
END
GO
Then within you regular SELECT statement you can call the function as such.
SELECT dbo.sf_GetMeasureDate('2013-10-05 16:47:56.000','2013-09-04 17:37:42.000','1/1/1900')
or within an existing query:
SELECT dbo.sf_GetMeasureDate([fld1],[fld2],'1/1/1900')

SQL Server : random date in specific range (including random hours, minutes,...)

I would like to create a random date for a SQL Server update query. I found a lot examples for random days or something similar but I couldn't find something which creates a random date with random date, hours, minutes, seconds AND milliseconds.
This is what I use to create the date randomly but it always gives me 00 as hour, minute, seconds and milliseconds and I don't know how I can randomize them as well.
This is my query:
declare #FromDate date = GETDATE()-2
declare #ToDate date = GETDATE()-1
UPDATE ACCOUNTS
SET dateFinished=
dateadd(day, rand(checksum(newid())) * (1 + datediff(day, #FromDate, #ToDate)), #FromDate)
This is how I'd do it:
Work out the number of seconds between from and to
Get a random number between zero and the number of seconds
Add that random number to the FromDate
Finally randomise the number of milliseconds
DECLARE #FromDate DATETIME = DATEADD(DAY, -2, GETDATE())
DECLARE #ToDate DATETIME = DATEADD(DAY, -1, GETDATE())
DECLARE #Seconds INT = DATEDIFF(SECOND, #FromDate, #ToDate)
DECLARE #Random INT = ROUND(((#Seconds-1) * RAND()), 0)
DECLARE #Milliseconds INT = ROUND((999 * RAND()), 0)
SELECT DATEADD(MILLISECOND, #Milliseconds, DATEADD(SECOND, #Random, #FromDate))
declare #FromDate dateTIME = '2014-01-01'
declare #ToDate dateTIME = '2014-12-31'
select top 100 dateadd(day,rand(checksum(newid()))*(1+datediff(day, #FromDate, #ToDate)), #FromDate) FROM Tabled(give your table name)
SELECT dateaddDATEADD(second,
second, (rand()*60+1),
DATEADD(minute,
(rand()*60+1) ,
DATEADD(day,
(rand()*365+1),
DATEADD(year,
-1,
getdate()))) )

How do I calculate total minutes between start and end times?

How do I calculate total minutes between start and end times? The Start/End times columns are nvarchar and I am declaring them as datetime. I'm not sure if that is my first step or not, I am new to SQL and to declaring.
The final goal is to take Total Minutes, subtract Lunch and Recess (both are minutes) and then multiply by 5 to get total instructional minutes for the week per school.
DECLARE #StartTime datetime, #Endtime datetime
SELECT --[School]
[GradeLevel]
,[StartTime]
,[EndTime]
,(#Endtime - #StartTime) AS 'TotalMinutes'
,[Lunch]
,[Resess]
,[Passing]
FROM [dbo].[StartEndTimes]
Current Output:
GradeLevel StartTime EndTime TotalMinutes Lunch Resess Passing
2-5 7:50 14:20 NULL 20 10 NULL
K-5 7:45 14:20 NULL 20 10 NULL
K-5 7:50 14:20 NULL 20 10 NULL
Maybe something like this is what you want?
select (datediff(minute, starttime, endtime) -lunch -recess) * 5 AS TotalInstruct
from YourTable
If you want to sum it up for all rows then try:
select sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
If you want to get the number of hours per school you would have to include the schoolfield in the query and use it in the group byclause, and then the query becomes this:
select school, sum((datediff(minute, starttime, endtime) -lunch -recess) * 5) AS TotalInstruct
from YourTable
group by school
Sample SQL Fiddle for the above queries.
If all you want is to find the difference between two dates then you can use DATEDIFF function (http://msdn.microsoft.com/en-us/library/ms189794.aspx)
Example:
DECLARE #startdate datetime2
SET #startdate = '2007-05-05 12:10:09.3312722';
DECLARE #enddate datetime2 = '2007-05-04 12:10:09.3312722';
SELECT DATEDIFF(MINUTE, #enddate, #startdate);
If however your values are in string format you need to convert them prior to passing them to the DATEDIFF function.
Example:
DECLARE #starttexttime nvarchar(100)
SET #starttexttime = '7:50'
DECLARE #starttime datetime2
SET #starttime = CONVERT(datetime2, #starttexttime, 0)
DECLARE #endtexttime nvarchar(100)
SET #endtexttime = '17:50'
DECLARE #endtime datetime2
SET #endtime = CONVERT(datetime2, #endtexttime, 0)
SELECT DATEDIFF(MINUTE, #starttime, #endtime);

Show 0 if null in query

I am running a sql query that is omitting the day if the return count is 0. I want my query to return the day and a 0 count if the the count is 0. Snare I have is that if 0 were sold for the day, the day is omitted from my return results.
SELECT ISNULL([day],0) As [day], COUNT(ISNULL(Sold,0)) As [Sold]
FROM productionInfo
You're drawing information from a single table, productionInfo. If productionInfo has no rows with that date information (because there are no widgets sold on that date), how does it know what dates to use?
You might want to look at using a Numbers Table to get a row for each day of the month/year, then join that to productionInfo so you have a day value available, even if there was no production that day.
This will give you a dates table:
CREATE FUNCTION dbo.DatesTable (#startDate DATETIME, #endDate DATETIME)
RETURNS #retTable TABLE (DateValue DATETIME)
AS
BEGIN
DECLARE #currentDate DATETIME
SET #currentDate = #startDate
WHILE (DATEDIFF(dd, #currentDate, #endDate) >= 0)
BEGIN
INSERT INTO #retTable VALUES (#currentDate)
SET #currentDate = DATEADD(dd, 1, #currentDate)
END
RETURN
END
Then your query will look like:
SELECT dt.DateValue AS [day], COUNT(Sold) AS [Sold]
FROM dbo.DatesTable('2-1-2014', '2-10-2014') dt
LEFT JOIN productionInfo pi ON pi.day = dt.DateValue
GROUP BY dt.DateValue

SQL Server - Generate date field data in where clause

My query is
Select * from Orders
where ordersdate Between '2013-10-10 00:00:00.00' and '2013-10-10 23:59:59.997'
I need to run this query on daily basis and it should be previous day dates. so how to generate dates in above format is what im struggling with.
Select *
from Orders
where ordersdate >= cast(dateadd(d, -1, getdate()) as date)
and ordersdate < cast(getdate() as date)
Instead of the additonal time you can use >= yesterday's date and < today.
DECLARE #StartDate DATETIME, #EndDate DATETIME
/* set the end date to midnight of the previous day */
SET #EndDate = CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 121), 121)
/* set the start date to 1 day previously (thereby getting midnight to midnight) */
SET #StartDate = DATEADD(day, -1, #EndDate)
/* you could use between, but orders placed at midnight might be counted twice (on subsequent day reports) */
Select * from Orders where ordersdate Between #StartDate AND #EndDate
/* or you could use >= and < to guarantee that a order placed at midnight will only be counted once */
Select * from Orders where ordersdate >= #StartDate AND ordersdate < #EndDate
select *
from orders
where datediff(d, ordersdate, getdate()) = 1
/edit/
As per Jason Musgrove comment - such query is easy to write and understand, but depend on rows count may become quite inefficent.
taking a slightly different approach (but probably not as good as Arvo's Answer) and there are quicker ways to perform the cast
select *
from orders
where cast(ordersdate as varchar(11)) = cast( dateadd(dd,-1,getdate()) as varchar(11) )

Resources