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
Related
I faced a problem with a SQL query. I have a table with 10 fields.
I need to create a query, which gets date by field ProductionYear(int) between 2 variables #startDate(int) and #endDate(int). Both of these variables are unnecessary. And I need to build a SQL query with following conditions:
If(#endDate = 0)
Select Id from MyTable where ProductionYear > #startDate
else
Select Id from MyTable where ProductionYear BETWEEN #startDate and #endDate.
How can I build a query with those conditions?
You can incorporate this into a single query:
Select Id
from MyTable
where ProductionYear >= #startDate and
(ProductionYear <= #endDate or #endDate = 0);
Your two queries are inconsistent on whether #startDate is included. BETWEEN includes the comparison values, but > does not.
If you want #startDate to also be optional:
Select Id
from MyTable
where (ProductionYear >= #startDate or #startDate = 0) and
(ProductionYear <= #endDate or #endDate = 0);
Some additional comments. Calling a "year" a "date" is confusing. Your parameters should probably be called #startYear and #endYear.
These queries are going to result in full table scans of your table. This is probably not a big deal, because the granularity is by year. If the granularity were more refined, you might want to use an index. In that case, perhaps the best approach is dynamic SQL.
you can try by using case when
Select Id from MyTable
where ProductionYear BETWEEN (case when #startDate>#endDate then #endDate
else #startDate end) and
(case when #startDate>#endDate then #startDate else #endDate end)
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);
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?
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)
Well this is my case: I have an input date X (dd-mm-yyyy), and I want to count the number of days between it with the year part is changed into current year and today's date in SQL. I t comes with the following condition, after the year is changed temporarily: (Here's my current idea of the logic)
- If date X is earlier than today, then difference = datediff(X,now), with the X year is current year
- If date X is later than today, then difference = datediff(X,now), with the X year is one year before
Sample case:
1st case: The input date is 6-6-1990. Today (automatically generated) is 22-8-2011. Then the difference will be = datediff(6-6-2011,22-08-2011)
2nd case: The input date is 10-10-1990. Today (automatically generated) is 22-8-2011. Then the difference will be = datediff(10-10-2010,22-08-2011)
Any idea how to do this in SQL (in SQL Server)? Or is there any other more simple alternatives for this problem? I'd also like this to be done in the query and not using a stored procedure or function
Sorry if there's already a similar question, I just don't know the exact keyword for this problem :( if there's a question like this previously, feel free to direct me there.
Thanks in advance
Here is the implementation (if I understood the logic you need correctly):
USE YourDbName
GO
CREATE FUNCTION YearPartDiff (#date datetime)
RETURNS int
AS
BEGIN
DECLARE #dateCurrentYear datetime
SET #dateCurrentYear = DATEADD(year, YEAR(GETDATE()) - YEAR(#date), #date)
DECLARE #result int
IF #dateCurrentYear < GETDATE()
SET #result = ABS(DATEDIFF(day, #dateCurrentYear, GETDATE()))
ELSE
SET #result = ABS(DATEDIFF(day, DATEADD(year, -1, #dateCurrentYear), GETDATE()))
RETURN(#result)
END
GO
And the example of usage:
USE YourDbName
GO
DECLARE #someDate datetime
SET #someDate = '2011-06-06'
SELECT dbo.YearPartDiff(#someDate) /*returns 77*/
SET #someDate = '2010-10-10'
SELECT dbo.YearPartDiff(#someDate) /*returns 316*/
Basically, #Andrei's solution, but in a single statement:
SELECT
DayDiff = DATEDIFF(
DAY,
DATEADD(YEAR, CASE WHEN LastOcc > GETDATE() THEN -1 ELSE 0 END, LastOcc),
GETDATE()
)
FROM (
SELECT LastOcc = DATEADD(YEAR, YEAR(GETDATE()) - YEAR(#InputDate), #InputDate)
) s
This seems to do the job
SELECT DATEDIFF(DAY, CONVERT(DATETIME, N'2011-06-06'), CONVERT(DATETIME, N'2011-08-22'))
So the basic syntax is
SELECT DATEDIFF(DAY, CONVERT(DATETIME, N'yyyy-mm-dd'), CONVERT(DATETIME, N'yyyy-mm-dd '))
Alternatively, you can use GETDATE() instead of the string for today's date
I have used "SELECT DATEDIFF( D, "+myDate+", GETDATE())" in my code, on SQL Server 2005. It works for me. The value myDate of course would be the DateTime input value.
you should try this query:
create table #T (inp_date datetime)
insert #T values ('06-06-1990')
insert #T values ('08-22-1990')
insert #T values ('10-10-1990')
--select * from #T
select inp_date, GETDATE(),
CASE
WHEN DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE()),inp_date) <= GETDATE()
THEN DATEDIFF(dd,DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE()),inp_date),GETDATE())
ELSE DATEDIFF(dd,DATEADD(yy,DATEDIFF(yy,inp_date,GETDATE())-1,inp_date),GETDATE())
END
from #T