Change a datetime2 column to date - sql

I'm trying to convert a column in SQL Server Express from a datetime2(7) format to a date format.
I have tried convert, a number of different ways with brackets and parenthesis but I'm having issues either with 'binding' or syntax.
dbo.stateByStatehood.annexDate
USE bigCity
--1.
SELECT CONVERT(datetime2(7), GETDATE()) annexDate;
--2.
SELECT CONVERT (datetime2(7)), stateByStatehood.annexDate date

You can go for cast to date datatype as given below:
SELECT CONVERT(date, GETDATE()) as annexDate;
SELECT CAST(GETDATE() AS DATE) as annexDate
annexDate
2021-08-27

Related

SQL Server error in conversion of date from string

NPD.CreatedOn is defined as a datetime datatype column (in SQL Server).
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(MONTH, CONVERT(VARCHAR(7), NPD.CreatedOn, 126), CONVERT(VARCHAR(30), GETDATE(), 126)) <= 6
I get this error:
Conversion failed when converting date and/or time from character string.
What can I try to resolve it?
Don't use things like DATEDIFF in the WHERE on your columns, such queries aren't SARGable and thus can (will) perform poorly. If you want rows where the date is on or after the start of the month 6 months ago then do the date logic on GETDATE()/SYSDATETIME()/etc:
SQL Server doesn't have a "start of month" function, but you can use EOMONTH and then add a day:
SELECT *
FROM dbo.NPDMaster NPD
WHERE NPD.CreatedOn >= DATEADD(DAY, 1, EOMONTH(GETDATE(),-7));
You don't need to convert the datetime values to text. DATEDIFF() expects datetime values as second and third argument:
SELECT *
FROM NPDMaster NPD
WHERE DATEDIFF(month, NPD.CreatedOn, GETDATE()) <= 6
The actual reason for the error (as is explained in the documentation), is that ...DATEDIFF implicitly casts string literals as a datetime2 type.

Convert Numeric to Date in MS SQL

There is already a Datecolumn in Table which is in Numeric DataType(Converted to Int for faster ODBC Transfer), How can i convert that number to Data again?
Example the Values are like
42508
42826
43191
42158
42527
Which are nothing but like
SELECT CONVERT(numeric, getdate())
Query Result
43571
Just want to know how can i convert back that to normal date ?
You may use next conversion:
SELECT CONVERT(date, DATEADD(day, 43570, 0))
which will output:
17/04/2019 00:00:00
In this case SQL Server will use implicit data type conversion, because DATEADD() allows datetime datatype as third parameter and DATEADD() will convert 0 to 1900-01-01.

incorrect results while passing a datetime instead of getdate()

I am working on a SQL query which returns all records between two dates from a table as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,GETDATE(),101))
and dateadd(day,1,convert(datetime,convert(varchar,GETDATE(),101)))
The above query works fine and gives me the desired results but when I tried to use a normal date string instead of getdate(), the query returns and empty result as follows
select convert(varchar(2),TestDate,108) from dbo.Table
where TestDate between convert(datetime,convert(varchar,'2015-12-27 00:00:00.000',101)) and dateadd(day,1,convert(datetime,convert(varchar,2015-12-27 00:00:00.000',101)))
The above query returns an empty result set which is not what I wanted.
I tried passing date string in different formats but that didn't work.
May I know a correct way to do it?
Why would you convert dates to a string for comparisons? Just do the comparisons as dates.
In addition, you can use datepart() to extract the hour, rather than using some esoteric format to convert():
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast(GETDATE() as date) and
cast(dateadd(day, 1, getdate()) as date)
If you want the hour as a string instead of a number, then use datename() rather than datepart().
I guess that you are having an extra CONVERT.
Wherever you have this
convert(varchar,GETDATE(),101)
just replace with your date:
'2015-12-27 00:00:00.000'
because the purpose of the CONVERT function is to translate a Date into a Varchar
In addition to Gordon's answer, you can substitute string dates as so:
select datepart(hour, TestDate)
from dbo.Table
where TestDate between cast('2015-12-27 00:00:00.000' as date) and
cast(dateadd(day, 1, '2015-12-27 00:00:00.000') as date)
Assuming this is for a webapp, be sure to use placeholders instead of actual text to prevent SQL insertion attacks.

How to filter only the date from a string stored in a varchar

Ii have values stored in the SQL Server in the following manner : 02-Jul-12 12:00:00 AM here the time and minutes, seconds can be anything like 02-Jul-12 12:15:52 PM ,02-Jul-12 6:02:12 AM so on.
I want to have a where condition which will omit the time and take the data based on the date like the following where some_Date='02-Jul-12'
How would I do this?
SELECT * FROM whatever WHERE some_Date LIKE '02-Jul-12%';
If you are on SQL2008 or later, you can cast your DATETIME to DATE.
See this post: http://blog.sqlauthority.com/2012/09/12/sql-server-get-date-and-time-from-current-datetime-sql-in-sixty-seconds-025-video/
But in a WHERE-clause it is better to search between dates, like this:
DECLARE #startDate DATETIME = '02-Jul-2012'
DECLARE #endDate DATETIME = DATEADD(DAY, 1, #startDate)
SELECT * FROM [table] WHERE [some_Date] BETWEEN #startDate AND #endDate
SELECT * FROM dbo.tbl_MyTable
WHERE
REPLACE(CONVERT(VARCHAR(9), DateTimeValueColumn, 6), ' ', '-')='02-Jul-12'
or
On chage in code is instead of using getdate function voncert you datestring in datetime format and do compare this follow query will work for you
SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) =
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
If you are storing dates as characters -- which is not recommended -- you should at least use ISO format: YYYY-MM-DD hh:mm:ss. This makes the date useful for sorting and comparisons ("<" works, ">" works, "between" works as well as equals).
To extract the date, you can then use left(datestr, 10). In your format, you would use:
where left(datestr, 9) = '01-Jan-13'
If you are storing the fields as a datetime or smalldatetime, you may think they are stored as a string. They are not. They are stored as some number of days since some particular date, with day parts stored as fractional days. If you are using SQL Server 2005 or greater, then the best way is:
where cast(datetime as date) = '2013-01-01' -- I recommend ISO formats, even for constants. '20130101' is even better
To select rows with today's date (not time)
select * from myTable where datediff(dd, dateColumn, getdate()) = 0

Simple DateTime sql query

How do I query DateTime database field within a certain range?
I am using SQL SERVER 2005
Error code below
SELECT *
FROM TABLENAME
WHERE DateTime >= 12/04/2011 12:00:00 AM
AND DateTime <= 25/05/2011 3:53:04 AM
Note that I need to get rows within a certain time range. Example, 10 mins time range.
Currently SQL return with Incorrect syntax near '12'."
You missed single quote sign:
SELECT *
FROM TABLENAME
WHERE DateTime >= '12/04/2011 12:00:00 AM' AND DateTime <= '25/05/2011 3:53:04 AM'
Also, it is recommended to use ISO8601 format YYYY-MM-DDThh:mm:ss.nnn[ Z ], as this one will not depend on your server's local culture.
SELECT *
FROM TABLENAME
WHERE
DateTime >= '2011-04-12T00:00:00.000' AND
DateTime <= '2011-05-25T03:53:04.000'
You need quotes around the string you're trying to pass off as a date, and you can also use BETWEEN here:
SELECT *
FROM TABLENAME
WHERE DateTime BETWEEN '04/12/2011 12:00:00 AM' AND '05/25/2011 3:53:04 AM'
See answer to the following question for examples on how to explicitly convert strings to dates while specifying the format:
Sql Server string to date conversion
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
You can execute below code
SELECT Time FROM [TableName] where DATEPART(YYYY,[Time])='2018' and DATEPART(MM,[Time])='06' and DATEPART(DD,[Time])='14
SELECT *
FROM TABLENAME
WHERE [DateTime] >= '2011-04-12 12:00:00 AM'
AND [DateTime] <= '2011-05-25 3:35:04 AM'
If this doesn't work, please script out your table and post it here. this will help us get you the correct answer quickly.
select getdate()
O/P
----
2011-05-25 17:29:44.763
select convert(varchar(30),getdate(),131) >= '12/04/2011 12:00:00 AM'
O/P
---
22/06/1432 5:29:44:763PM
Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :
Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.
Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).
if you have a type of datetime and you want to check between dates only ,,,use cast to select between two dates ....
example...
... where cast( Datetime as date) >= cast( Datetime as date) AND cast( Datetime as date) <= cast( Datetime as date)