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

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

Related

How can I generate a random timestamp appended to getdate() in SQL Server?

The following sql select generates the current date and time:
select
Getdate() AS DueDate
which looks like:
2021-02-06 10:16:35.340
I'd like to use getdate() (or an equivalent alternative) to continue getting the current date but I'd like to randomize the time component. I am having trouble finding a workable solution within a select statement.
Any suggestions?
here is another way if you need to have random time for each row:
SELECT
DATEADD(SECOND ,RAND(CHECKSUM(NEWID())) * 86400,CONVERT(datetime,CONVERT(varchar(8),GETDATE(),112)))
FROM tablename
You can simply add another DATEADD around your expression. For example, using INFORMATION_SCHEMA:
SELECT DATEADD(MILLISECOND, RAND(ROW_NUMBER()OVER(ORDER BY C.ORDINAL_POSITION)) * 10000000, GETDATE())
FROM INFORMATION_SCHEMA.COLUMNS AS C
You can play around with the RAND() and ROW_NUMBER() functions to get the result you want. If you have a primary key with lots of gaps, that helps to randomize.

Ignore seconds and milliseconds FROM GETDATE() in SQL

I wanted to remove/ignore the seconds and milliseconds coming from GETDATE() SQL function.
When I executed,
SELECT GETDATE()
output will be like
2015-01-05 14:52:28.557
I wanted to ignore seconds and milliseconds from above output. What is the optimize and best way to do this?
I have tried to do this by typecasting like this:
SELECT CAST(FORMAT(GETDATE(),'yyyy-MM-dd HH:mm:0') AS datetime)
Is it is the correct and optimize way to do this?
I'd either use the DATEADD/DATEDIFF trick that Codo has shown or just cast it to smalldatetime1:
select CAST(GETDATE() as smalldatetime)
I'd avoid anything that involves round-tripping the value through a string.
1It may be appropriate, at this time, to change your schema to use this data type anyway, if seconds are always irrelevant.
Try this:
SELECT dateadd(minute, datediff(minute, 0, GETDATE()), 0)
The query uses the fact that DATEDIFF return the number of minutes between two dates, ignoring the smaller units. 0 is a fixed date in the past.
It can be easily adapted to other time units.
I think your way is fine if it works (looks like it should, but I haven't tested it.) There are lots of other possible approaches, too. Here's one:
select cast(convert(char(16), getdate(), 120) as datetime)

filter DateTime field with now as reference in WHERE clause

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.

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 get records after a certain time using SQL datetime field

If I have a datetime field, how do I get just records created later than a certain time, ignoring the date altogether?
It's a logging table, it tells when people are connecting and doing something in our application. I want to find out how often people are on later than 5pm.
(Sorry - it is SQL Server. But this could be useful for other people for other databases)
For SQL Server:
select * from myTable where datepart(hh, myDateField) > 17
See http://msdn.microsoft.com/en-us/library/aa258265(SQL.80).aspx.
What database system are you using? Date/time functions vary widely.
For Oracle, you could say
SELECT * FROM TABLE
WHERE TO_CHAR(THE_DATE, 'HH24:MI:SS') BETWEEN '17:00:00' AND '23:59:59';
Also, you probably need to roll-over into the next day and also select times between midnight and, say, 6am.
In MySQL, this would be
where time(datetimefield) > '17:00:00'
The best thing I can think would be: don't use a DateTime field; well, you could use a lot of DATEADD/DATEPART etc, but it will be slow if you have a lot of data, as it can't really use an index here. Your DB may offer a suitable type natively - such as the TIME type in SQL Server 2008 - but you could just as easily store the time offset in minutes (for example).
For MSSQL use the CONVERT method:
DECLARE #TempDate datetime = '1/2/2016 6:28:03 AM'
SELECT
#TempDate as PassedInDate,
CASE
WHEN CONVERT(nvarchar(30), #TempDate, 108) < '06:30:00' then 'Before 6:30am'
ELSE 'On or after 6:30am'
END,
CASE
WHEN CONVERT(nvarchar(30), #TempDate, 108) >= '10:30:00' then 'On or after 10:30am'
ELSE 'Before 10:30am'
END
Another Oracle method for simple situations:
select ...
from ...
where EXTRACT(HOUR FROM my_date) >= 17
/
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions050.htm#SQLRF00639
Tricky for some questions though, like all records with the time between 15:03:21 and 15:25:45. I'd also use the TO_CHAR method there.
In Informix, assuming that you use a DATETIME YEAR TO SECOND field to hold the full date, you'd write:
WHERE EXTEND(dt_column, HOUR TO SECOND) > DATETIME(17:00:00) HOUR TO SECOND
'EXTEND' can indeed contract the set of fields (as well as extend it, as the name suggests).
As Thilo noted, this is an area of extreme variability between DBMS (and Informix is certainly one of the variant ones).
Ok, I've got it.
select myfield1,
myfield2,
mydatefield
from mytable
where datename(hour, mydatefield) > 17
This will get me records with a mydatefield with a time later than 5pm.