SQL Stored Procedure to get Date and Time - sql

I wish to create a stored procedure which can retrieve the datetime less than or greater than current sys date.. in my table,startdate and enddate has the value as 'datetime'
How do I get details between startdate and enddate in SQL stored procedure?
thanks in advance

eg:
SELECT *
FROM MyTable
WHERE DATEDIFF ('d',mydatefield ,getdate() ) < 3
gets within 3 days

Considering this table definitionCREATE TABLE [dbo].[Dates](
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL
)
I assume that if you pass a date you want to know which rows satisfy the condition: startDate < date < EndDate. If this is the case you can use the query: select *
from Dates
where convert(datetime, '20/12/2010', 103) between StartDate and EndDate;
A stored procedure could look like: ALTER PROCEDURE [dbo].[GetDataWithinRange]
#p_Date datetime
AS
BEGIN
SELECT *
from Dates
where #p_Date between StartDate and EndDate;
END

It sounds like you're trying to filter data in a table based on a date range. If this is the case (I'm having some trouble understanding your question), you'd do something like this:
select *
from MyTable m
where m.Date between #DateFrom and #DateTo
Now, I'm assuming your filtering dates are put into the variables #DateFrom and #DateTo.

There are two things:
1> To get todays date we can write
SET #today_date = GETTDDT();
2> To get Current time we can us ethe following query:
SET #today_time = (SELECT
digits(cast(hour(current time) as decimal(2,0)))||
digits(cast(minute(current time) as decimal(2,0)))||
digits(cast(second(current time) as decimal(2,0)))
FROM sysibm/sysdummy1);

Related

SQL search between 2 dates in SQL

I've got a database that needs to display records between 2 dates.
At the moment I've got a form with 2 text boxes on - one for datefrom and one for dateto.
My plan was to format and store the values from these text boxes as global variables
DateFrom = Format(Me.DateFrom, "yyyy/mm/dd")
DateTo = Format(Me.DateTo, "yyyy/mm/dd")
that I cam then pass into a passthrough query with this criteria for field called dateCollected
HAVING (((Collections.DateCollected) str_to_date(datefrom, ā€˜%y/%m/%dā€™) and str_to_date(dateto, ā€˜%y/%m/%dā€™)) AND ((dbo.udfRawHazPropsList([ConsignmentNoteNumber],[ewc_code])) Is Not Null))
However, no matter what I try I can't get this to work. Any ideas as to a solution would be much appreciated!
You can get it by two ways:
1. If your sp variable of date type-
DECLARE #StartDate DATE = '2020-07-23',
#EndDate DATE = '2020-07-27'
SELECT * from TableName
WHERE CreatedON between #StartDate and #EndDate --First Way
SELECT * from TableName
WHERE CreatedON >= #StartDate and CreatedON <#EndDate --Second Way
SELECT * from TableName
WHERE CreatedON between CONVERT(varchar,#StartDate,6)
and CONVERT(varchar,#EndDate,6) --Third Way
2. If your sp have Varchar Variable type-
DECLARE #StartDate1 VARCHAR(50) = '2020-07-23',
#EndDate1 VARCHAR(50) = '2020-07-27'
SELECT * FROM TableName
WHERE CreatedON between CAST(#StartDate1 AS DATE)
and CAST(#EndDate1 AS DATE) --First Way
SELECT * from TableName
WHERE CreatedON >= CAST(#StartDate1 AS DATE)
and CreatedON < CAST(#EndDate1 AS DATE) --Second Way
SELECT * from TableName
WHERE CreatedON between CONVERT(varchar,Cast(#StartDate1 AS date),6)
and CONVERT(varchar,Cast(#EndDate1 AS date),6) --Third Way
In Third way in both, you can change the value to get the different format.
CONVERT(varchar,Cast(#EndDate1 AS date),6)
Change Third Value to get different format if you need.

Slowly changing dimension by date only

I have a database table using the concept of data warehousing of slowly changing dimension to keep track of old versions.
So, I implemented it with the Log Trigger mechanism.
My table is like this:
CREATE TABLE "T_MyTable" (
"Id" INT NOT NULL DEFAULT NULL,
"Description" NVARCHAR(255) NULL DEFAULT NULL )
and I created an hystory table
CREATE TABLE "T_MyTableHistory" (
"Id" INT NOT NULL DEFAULT NULL,
"Description" NVARCHAR(255) NULL DEFAULT NULL,
StartDate DATETIME,
EndDate DATETIME )
Then, with a trigger like this, I get the history:
CREATE TRIGGER TableTrigger ON T_MyTable FOR DELETE, INSERT, UPDATE AS
DECLARE #NOW DATETIME
SET #NOW = CURRENT_TIMESTAMP
UPDATE T_MyTableHistory
SET EndDate = #now
FROM T_MyTableHistory, DELETED
WHERE T_MyTableHistory.Id = DELETED.Id
AND T_MyTableHistory.EndDate IS NULL
INSERT INTO T_MyTableHistory (Id, Description, StartDate, EndDate)
SELECT Id, Description, #NOW, NULL
FROM INSERTED
And, to query the history table, I use
SELECT Id, Description
FROM T_MyTableHistory
WHERE #DATE >= StartDate
AND (#DATE < EndDate OR EndDate IS NULL)
Now, my question is this: my customer will actually query the history table by date only (i.e. without the time of the day), so I need to get the record version at that date.
I thought about two options:
change the trigger (how?) to record only one "history" record per date.
keep the trigger as-is, recording all the changes in the database (including date and time), but then query the history table to get the latest version of a particular date (how?)
My feeling is that the second option is easier to implement, otherwise the trigger could become complicated (INSERT or UPDATE, depending on the presence of the history record for current date).
I'd need some help in choosing the right direction, and I'd like to have an example of the SQL query needed, in the chosen option.
I agree with your second opinion.
It is good to save date along with time. While filtering data based on date use
CONVERT() function to make sure that DATE only got compared. Also, When client enter a single date, If records have same start and end date
they will not be in your filter so use Date >= StartDate and Date <= EndDate not (>= ,<)
DECLARE #Date AS DATETIME
SET #Date = '2013-07-30'
SELECT TOP 1 Id, Description
FROM T_MyTableHistory
WHERE CONVERT(VARCHAR(20), #DATE, 103)
>= CONVERT(VARCHAR(20), StartDate, 103)
AND (CONVERT(VARCHAR(20), #DATE, 103)
< CONVERT(VARCHAR(20), EndDate, 103) OR EndDate IS NULL)
ORDER BY StartDate DESC
At the end, I came up with this query:
SELECT Id, Description
FROM T_MyTableHistory
WHERE ( DateAdd(day, datediff(day,0, #MyDate), 0) >= StartDate ) AND
(( DateAdd(day, datediff(day,0, #MyDate), 0) < EndDate ) OR ( EndDate IS NULL ))
This should be faster than varchar<->datetime conversion, and it should also be locale-independent.
By the way, this query should not need the TOP 1 and the ORDER BY clauses, since the function
DateAdd(day, datediff(day,0, #MyDate)
automatically returns the selected date, with "midnight" time (e.g. 20141215 00:00:00), so records with the same date are automatically cut out of the results.
References:
How to return the date part only from a SQL Server datetime datatype
Best approach to remove time part of datetime in SQL Server

Converting YYYYMM format to YYYY-MM-DD in SQL Server

I need to perform a query on a large table that has a datetime column that is indexed.
We need to query the data for a range from a month (at a minimum) to multiple months.
This query would be executed from Cognos TM1 and the input would be a period like YYYYMM. My question is - how to convert the YYYYMM input to a format that can be used to query that table (with the index being used).
Let's say if the input is
From Date: '201312'
To Date: '201312'
then, we need convert the same to 'between 01-12-2013 and 31-12-2013' in the query
Since we need this to be hooked up in Cognos TM1, so would not be able to write a procedure or declare variables (TM1 somehow does not like it).
Thanks in advance for your reply.
I would do something like this:
create procedure dbo.getDataForMonth
#yyyymm char(6) = null
as
--
-- use the current year/month if the year or month is invalid was omitted
--
set #yyyymm = case coalesce(#yyyymm,'')
when '' then convert(char(6),current_timestamp,112)
else #yyyymm
end
--
-- this should throw an exception if the date is invalid
--
declare #dtFrom date = convert(date,#yyyymm+'01') -- 1st of specified month
declare #dtThru date = dateadd(month,1,#dtFrom) -- 1st of next month
--
-- your Big Ugly Query Here
--
select *
from dbo.some_table t
where t.date_of_record >= #dtFrom
and t.date_of_record < #dtThru
--
-- That's about all there is to it.
--
return 0
go
Suppose you are getting this value of YYYYMM in a varchar variable #datefrom .
You can do something like
DECLARE #DateFrom VARCHAR(6) = '201201';
-- Append '01' to any passed string and it will get all
-- records starting from that month in that year
DECLARE #Date VARCHAR(8) = #DateFrom + '01'
-- in your query do something like
SELECT * FROM TableName WHERE DateTimeColumn >= #Date
Passing Datetime in a ansi-standard format i.e YYYYMMDD is a sargable expression and allows sql server to take advantage of indexes defined on that datetime column.
here is an article written by Rob Farley about SARGable functions in SQL Server.
Try this...
declare #startdate date,#endate date
select #startdate =convert(date,left('201312',4)+'-'+right('201312',2)+'-01')
select #endate= DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, #startdate) + 1, 0))
select convert(date,#startdate,102) startdate,convert(date,#endate,102) endate
In the datasource of your TM1 Turbo Integrator process, you can use parameters in the SQL query. E.g. you could take this SQL query:
SELECT Col1, Col2
FROM Table
WHERE Col1 = 'Green'
AND Col2 < 30
In TM1, to parameterise this, you would create two parameters e.g. P1 and P2 and put them in the query:
SELECT Col1, Col2
FROM Table
WHERE Col1 = '?P1?'
AND Col2 < ?P2?

Given Date parameter is considered as Date Time parameter

I'm writing a stored procedure in sql!
I have to get records in the particular date.
I am using this query:
Declare #FromDate datetime
set #FromDate = '06/02/2014'
select * from Table where Date = #FromDate
Actually, in the Database there are 10 records in that date, but it is showing only two records because the #FromDate is taking like this 06/02/2014 00:00:00.000
If I write the query like this it means it works correctly!
select * from Table
where Date between '2014-08-28 00:00:00.000' and '2014-08-28 23:59:59.999'
How to solve this? I need to get all the records in that particular date.
Please help me !
If #FromDate is of data type datetime and Table.Date is also of data type datetime then:
Declare #FromDate datetime = '2014-06-02';
Select Table.Date
From Table
Where Table.Date >= #FromDate And Date < DateAdd(day, 1, Table.Date)
Above, we create an inclusive lower boundary (anything equal to or later than 2014-06-02) and an exclusive upper boundary (anything earlier than 2014-06-03), but with a variable defined just once. So, effectively the query checks 2014-06-02 <= FromDate < 2014-06-03.
If you convert DateTime to Nvarchar your issue would be solved.
Try this query:
Declare #Date datetime='2014-08-28 00:00:00.000'
select * from Table
where CONVERT(nvarchar(20),Date,105) = CONVERT(nvarchar(20),#Date,105)

greater than and less than equals to in sql?

how can i use greater than equal to and less than equal to instead of using between in SQL
I'm checking for date variable in sql
i tried like this.
Date between coalesce(#fromDate,Date) and coalesce(#toDate,Date)
but if user does not enter any of date (fromDate or toDate)
so that I need to convert above condition in greater than equal to and less than equal to
please help in syntax in sql.
thanks
IF #fromDate IS NULL
BEGIN
SET #fromDate = '1900-01-01';
END;
IF #toDate IS NULL
BEGIN
SET #toDate = '2099-01-01';
END;
SELECT things
FROM table
WHERE date_field BETWEEN #toDate AND #fromDate;
This code will essentially give you an arbitrarily large range to check which should give you reasonable performance and return all results (assuming that's what you want when neither value is supplied).
This code can be shortened to:
SELECT things
FROM table
WHERE date_field BETWEEN Coalesce(#toDate, '1900-01-01') AND Coalesce(#fromDate, '2099-01-01');
But I kept the verbose version to illustrate.
Try this
SELECT Date FROM TableName WHERE Date > #fromDate AND Date < #toDate
SELECT *
FROM dbo.Account AS a
WHERE 1 = 1
AND (
#toDate IS NULL
OR a.CreateDate <= #toDate
)
AND (
#fromDate IS NULL
OR a.CreateDate >= #fromDate
)
Please note the 1 = 1 is only there to make the conditions clear and is by no means needed.
This should be what the where clause would look like.
Where
Date >= #fromDate
And
Date <= #toDate