Given Date parameter is considered as Date Time parameter - sql

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)

Related

Can I use like and between clauses at the same time in SQL Server

I have some data stored in SQL Server which contains dates (date datatype). I am currently using a BETWEEN clause to filter my records in dates range, something like this ...
SELECT
*
FROM
Report
WHERE
ReportDate BETWEEN '2016-08-01' AND '2017-08-01'
Is it possible to use BETWEEN and LIKE clause at the same time or something close to that so that whenever a user doesn't specify any dates he/she would be able to pull all the reports? So far the query below
SELECT
*
FROM
Report
WHERE
ReportDate BETWEEN '' AND ''
doesn't show any records at all. Is there a way of doing this ..?
Use NULL with a parameter... if no value is given for #startDate and #endDate then the default will be NULL for these parameters, and the second WHERE condition would be met, returning all records.
create proc myProc(#startDate datetime = null, #endDate datetime = null)
as
SELECT * FROM Report
WHERE
(ReportDate BETWEEN #startDate AND #endDate)
or
(#startDate is null and #endDate is null)
Also, if your field is a DATETIME then this blog by Aaron is well worth your read.
Also, this method means the user has to enter both or neither of the parameters. If that's not what you'd want just let us know.
I think the correct logic would be:
SELECT r.*
FROM Report r
WHERE (ReportDate >= #startDate OR #startDate IS NULL) AND
(ReportDate <= #endDate OR #endDate IS NULL);
This works when only one of the values is NULL.
Note:
I would go with Aaron Bertrand's advice and really use:
SELECT r.*
FROM Report r
WHERE (ReportDate >= #startDate OR #startDate IS NULL) AND
(ReportDate < DATEADD(day, 1, #endDate) OR #endDate IS NULL);

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?

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

Best way to compare dates without time in SQL Server

select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
I want to compare date without time
Is above query is ok? or other better solution you suggest
I am using SQL Server 2005
Date saved in UTC format on server
Users against this data belongs different timezone
Simple Cast to Date will resolve the problem.
DECLARE #Date datetime = '04/01/2016 12:01:31'
DECLARE #Date2 datetime = '04/01/2016'
SELECT CAST(#Date as date)
SELECT CASE When (CAST(#Date as date) = CAST(#Date2 as date)) Then 1 Else 0 End
Don't use convert - that involves strings for no reason. A trick is that a datetime is actually a numeric, and the days is the integer part (time is the decimal fraction); hence the day is the FLOOR of the value: this is then just math, not strings - much faster
declare #when datetime = GETUTCDATE()
select #when -- date + time
declare #day datetime = CAST(FLOOR(CAST(#when as float)) as datetime)
select #day -- date only
In your case, no need to convert back to datetime; and using a range allows the most efficent comparisons (especially if indexed):
declare #when datetime = 'Feb 15 2012 7:00:00:000PM'
declare #min datetime = FLOOR(CAST(#when as float))
declare #max datetime = DATEADD(day, 1, #min)
select * from sampleTable where DateCreated >= #min and DateCreated < #max
SELECT .......
FROM ........
WHERE
CAST(#DATETIMEVALUE1 as DATE) = CAST(#DATETIMEVALUE2 as DATE)
The disadvantage is that you are casting the filter column.
If there is an index on the filter column, then, since you are casting, the SQL engine can no longer use indexes to filter the date more efficiently.
Description
Don't convert your Date to a varchar and compare because string comparisson is not fast.
It is much faster if you use >= and < to filter your DateCreated column.
If you have no parameter (like in your sample, a string) you should use the ISO Format <Year><Month><Day>.
Sample
According to your sample
DECLARE #startDate DateTime
DECLARE #endDate DateTime
SET #startDate = '20120215'
SET #endDate = DATEADD(d,1,#startDate)
SELECT * FROM sampleTable
WHERE DateCreated >= #startDate AND DateCreated < #endDate
More Information
MSDN - DATEADD (Transact-SQL)
Use 112 CONVERT's format
select *
from sampleTable
where
CONVERT(VARCHAR(20),DateCreated,112)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),112)
or
if your sql server version 2008+ use DATE type
select * from sampleTable
where CONVERT(DATE,DateCreated)
= CONVERT(DATE,CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME))
declare #DateToday Date= '2019-10-1';
print #DateToday;
print Abs(datediff(day, #DateToday,CAST('oct 1 2019 7:00:00:000PM' AS DATETIME))) < 3
this is compare whin 3 days.
i test this on SQL Server 2014, it works.
select * from sampleTable
where date_created ='20120215'
This will also compare your column with the particular date
without taking time into account

SQL Stored Procedure to get Date and Time

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);