filter DateTime field with now as reference in WHERE clause - sql

I am trying to build a vb.net application with a where clause to filter data using a DateTime field.
My table contains 5 fields and more than 10000 rows. I wanna use a DateTime field to find all the rows older than 7 years from now.
But this script will be re-used many times. So I don't wanna use this kind of where clause cause I don't wanna need to modify the where clause every time I wanna run the application :
select * from myTable WHERE myDateTimeField < '2006-09-07 00:00:00.000'
I'd like to find a way to write a where clause like this :
select * from myTable WHERE myDateTimeField "is older than 7 years from NOW"
I don't use VB.net very often (as you can see), so this thing is really bugging me

Just make use of DateTime:
Dim dateTime As DateTime
dateTime = DateTime.Now.AddYears(-7);
When you're building your SQL string just call ToString on your date (you can obviously format it however you need):
dateTime.ToString("MM/dd/yyyy");

SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETDATE())
That is if the data in the myDateTimeField is in the same local time zone of the sql server.
If your data is in UTC (which it often should be), then use:
SELECT * FROM myTable WHERE myDateTimeField < DATEADD(YEAR, -7, GETUTCDATE())

i think better would be provided you have SQL Server
strQuery = "select * from myTable WHERE myDateTimeField
<= DATEADD(YEAR, -7, GETDATE())"

What you are looking for is a DSL for datetime. Check out this blog post to get some ideas.
http://leecampbell.blogspot.com/2008/11/how-c-30-helps-you-with-creating-dsl.html
Good Luck
P.S.
If you need help translating it into vb.net just submit a comment.

Related

Is there an equivalent to sysdate-1/24 in SQL server?

I've tried looking around for this but I can't find an answer that seems to work with the code I'm using. Basically, the below query searches on any result from the current date. I'm trying to make it so it will search only on the last hour.
In oracle I could do this using sysdate-1/24, is there a simple equivalent within SQL server? Bearing in mind I'm already using cast to get the current sysdate.
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(convert(varchar(10), getdate(), 110) as datetime)
and m_record_server is not null
You can use:
getdate() - 1.0/24
SQL Server allows you to use such arithmetic on datetime.
The more common way would be:
dateadd(hour, -1, getdate())
In your query, you do not need to cast to a string at all:
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= getdate() - 1.0/24 and m_record_server is not null;
If you want the date that was there one hour ago (which seems to be the intent of the code, if not the rest of the question):
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(getdate() - 1.0/24 as date) and m_record_server is not null;

Informix SQL Compare DateTime value on Where Statement

I have a datetime field called entrytimestamp, with content of the field is for example: 2014-01-07 16:20:00. I would like to query all the data that has entrytimestamp after 09:00:00 o'clock, regardless what date it was.
I have a prototype query:
select *
from trading
where to_char(entrytimestamp, "%H%M%S") >= "090000"
But I think it is logically a mistake, because it will compare the text string, not the sequence value. What is the right way to do it?
Use the EXTEND() function to extract the time part:
select *
from mytable
where extend(entrytimestamp, hour to second) > '09:00:00'
I dont know if it performs well,
but you could compare directly with the time portion of the datetime,
i think a cast here should perform pretty fast (just cuts off the date)
select *
from (select getdate() as mydatetime) as data
where cast(mydatetime as time) > cast('09:00:00' as time)
EDIT, just noticed this was for Informix SQL, so not sure it works then, Sorry

how to remove time from datetime

The field DATE in the database has the following format:
2012-11-12 00:00:00
I would like to remove the time from the date and return the date like this:
11/12/2012
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.
just use, (in TSQL)
SELECT convert(varchar, columnName, 101)
in MySQL
SELECT DATE_FORMAT(columnName, '%m/%d/%Y')
I found this method to be quite useful. However it will convert your date/time format to just date but never the less it does the job for what I need it for. (I just needed to display the date on a report, the time was irrelevant).
CAST(start_date AS DATE)
UPDATE
(Bear in mind I'm a trainee ;))
I figured an easier way to do this IF YOU'RE USING SSRS.
It's easier to actually change the textbox properties where the field is located in the report. Right click field>Number>Date and select the appropriate format!
SELECT DATE('2012-11-12 00:00:00');
returns
2012-11-12
Personally, I'd return the full, native datetime value and format this in the client code.
That way, you can use the user's locale setting to give the correct meaning to that user.
"11/12" is ambiguous. Is it:
12th November
11th December
For more info refer this: SQL Server Date Formats
[MM/DD/YYYY]
SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 101) from tbl
[DD/MM/YYYY]
SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 103) from tbl
Live Demo
TSQL
SELECT CONVERT(DATE, GETDATE()) // 2019-09-19
SELECT CAST(GETDATE() AS DATE) // 2019-09-19
SELECT CONVERT(VARCHAR, GETDATE(), 23) // 2019-09-19
In mysql at least, you can use DATE(theDate).
You may try the following:
SELECT CONVERT(VARCHAR(10),yourdate,101);
or this:
select cast(floor(cast(urdate as float)) as datetime);
Use this SQL:
SELECT DATE_FORMAT(date_column_here,'%d/%m/%Y') FROM table_name;

how to use like and between in where clause in same statement?

Im trying to find a set of results in a database based on dates. The dates are stored as varchars in the format dd/mm/yyyy hh:mm:ss.
What i would like to do is search for all dates within a range of specified dates.
For example i tried:
SELECT * FROM table_name
WHERE fromDate BETWEEN LIKE '%12/06/2012%' AND LIKE '%16/06/2012%'
Is something like this possible or is there a better way of doing this type of statement, because so far i have had little success?
I'm using Microsoft SQL server 2008.
Peter
Since your date values also include time, you can't use BETWEEN. The only safe way to do this is:
SELECT <cols> FROM dbo.table_name
WHERE CONVERT(DATE, fromDate, 103) >= '20120612'
AND CONVERT(DATE, fromDate, 103) < '20120617';
But as Martin noticed, you'll never be able to use an index on that column, so this will always perform a full table scan.
If you really, really want to use BETWEEN, converting to DATE is the only safe way to do so (well, or trimming the time off in other, less efficient ways):
SELECT <cols> FROM dbo.table_name
WHERE CONVERT(DATE, fromDate, 103) BETWEEN '20120612' AND '20120616';
But for consistency reasons I recommend against between even in that case.
Try This
SELECT * FROM table_name
WHERE Convert(Date,fromDate,103)
BETWEEN '20120612' AND '20120616'
The best solution is to store your varchars as DateTime in the database.
Second best is to convert then to dates in the select (as the other answers just indicates so I am not going to give the example)
The following works fine for me. Try this:
SELECT *
FROM [MABH-Desi-Dera].[dbo].[Order]
WHERE (CONVERT(nvarchar,[Order_ID]) BETWEEN '200622%' AND '200623%')
Here the Order_IDs start with some Date:
hi man this is not a rocket science bro
just make a logic like
Blockquote
SELECT * FROM table_name
WHERE fromDate BETWEEN '2021-05-01 12:00:00' AND '2021-05-01 23:59:00'
Blockquote
it will work I stuck too but it helps. i was also trying make a logic like u

Date without the time

I'm working with SQL Server 2005.
I have a column called purchase_time of type datetime. How do I select this column with the time part - just the date.
Thanks,
Barry
EDIT:
Would it be safe to get the datetime and split it via Python on the first space, or is this format locale dependant?
In versions < 2008 (which, based on other comments to some of the answers, I believe you are running), the most efficient way is to keep it as a datetime type and use date math to avoid string conversions.
SELECT DATEADD(DAY, DATEDIFF(DAY, '20000101', purchase_time), '20000101')
FROM dbo.table;
EDIT
If you want the date only for display purposes, not for calculations or grouping, that is probably best handled at the client. You can do it in SQL simply by saying:
SELECT dt = CONVERT(CHAR(10), purchase_time, 120)
FROM dbo.table;
In SQL Server 2008 you can use the newly added date type:
select convert(date, purchase_time) from TableName
Update:
In versions prior to SQL 2008, I used the following solution for this problem:
select convert(datetime, convert(int, convert(float, purchase_time)))
from TableName