Datetime conversion error in SQL Server - sql-server

My table contains the column 'StartDate' and value stored in the column is in format '23.1.2018'.
I am writing a select query where I am passing FromDate and ToDate.
#FromDate = '2018-08-01'
#ToDate = '2018-08-05'
After execution, I get an error
Conversion failed when converting date and/or time from character string
Apart from that I have used several techniques of CAST and CONVERT like CONVERT(date, StartDate, 104) and so on...
But the same error persists.
Looking forward to solution.
select *
from [dbo].[LMT2_ServerLicenseUser]
where cast(cast(startdate as datetime(7)) as date) = cast(cast(#FromDate as datetime(7)) as date)
SELECT CONVERT(date, '2018-08-01')
select convert(varchar, '24.11.2017', 23)
select CONVERT(VARCHAR, CONCAT(CONVERT(date, StartDate, 104), RIGHT('0' + CONVERT(VARCHAR, StartTime), 8)), 103)

It is the language setting of the login that controls how these ambiguous date formats are interpreted (though this can be overridden with an explicit SET DATEFORMAT statement).
The DEFAULT_LANGUAGE can be changed via ALTER LOGIN
try using 103
SELECT CONVERT(date, '25/08/2008',103)

First i would suggest to change you date style not immediate effect but later you need to do, otherwise you have to pay such to do conversations (varchar -> date)
For your current date format you can use convert() function with style code of 103
select sl.*
from [dbo].[LMT2_ServerLicenseUser] sl
where convert(date, startdate, 103) >= #fromdate and
convert(date, startdate, 103) <= #todate;

Related

Convert a SQl DateTime field with hh mm ss

I am inserting a datetime field into my SQL database with a format of 2014-10-29 12:05:24.927
My interface needs to display this as 29/10/2014 12:05:24
my tsql statement is :
SELECT Convert(VARCHAR(20), MessageAudit.AuditDate, 120) As AuditDate FROM tableA
Which, produces yyyy-MM-dd hh:mm:ss how, can i format the date portion of this to be dd/MM/yyyy?
You can use something like:
declare #Date datetime
select #Date = cast('20141029 12:05:24.927' as datetime)
select convert(nvarchar(10), #Date, 103) + ' ' + convert(nvarchar(10), #Date, 108)
It will give you precisely 29/10/2014 12:05:24
Concatenate two format dd/mm/yy & hh:mm:ss
e.g
SELECT CONVERT(NVARCHAR(10), GETDATE(), 103) + ' ' +
CONVERT(NVARCHAR(10), GETDATE(), 108) AS [Date]
Here's a pretty extensive list of date formats in sql server:
http://www.sql-server-helper.com/tips/date-formats.aspx
for your specific problem you could do:
SELECT CONVERT(VARCHAR(20), AuditDate, 103) + ' ' +
CONVERT(VARCHAR(20), AuditDate, 108) AS AuditDate
FROM tableA
Though this will return the date as a string/varchar - which has it's own set of issues. You're really better off keeping the date in a date format and formatting it on the front end. This will allow you (depending on how the date is displayed) to still be "date" sortable rather than string sortable.
As http://msdn.microsoft.com/it-it/library/ms187928.aspx, you have to specify 103 as the third parameter of the CONVERT() function.
SELECT Convert(VARCHAR(20), MessageAudit.AuditDate, 103) As AuditDate FROM tableA

Show empty string when date field is 1/1/1900

I'm querying a database like so:
SELECT DISTINCT
CASE WHEN CreatedDate = '1900-01-01 00:00:00.000' THEN '' ELSE CreatedDate END AS CreatedDate
FROM LitHoldDetails
lhd.CreatedDate is a DateTime field and is non-nullable. I want to display an empty string if the field is the minimum date (1/1/1900), but my CASE statement doesn't work; CreatedDate displays 1900-01-01 00:00:00.000 in my query when that value is in the database. I'm using SQL Server 2008 R2. What am I doing wrong?
When you use a CASE expression (not statement) you have to be aware of data type precedence. In this case you can't just set a DATETIME to an empty string. Try it:
SELECT CONVERT(DATETIME, '');
One workaround is to present your date as a string:
CASE WHEN CONVERT(DATE, CreatedDate) = '1900-01-01' -- to account for accidental time
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END
Or you could fiddle with the presentation stuff where it belongs, at the presentation tier.
Here is an example that works exactly as you seem to want:
DECLARE #d TABLE(CreatedDate DATETIME);
INSERT #d SELECT '19000101' UNION ALL SELECT '20130321';
SELECT d = CASE WHEN CreatedDate = '19000101'
THEN ''
ELSE CONVERT(CHAR(10), CreatedDate, 120)
+ ' ' + CONVERT(CHAR(8), CreatedDate, 108)
END FROM #d;
Results:
d
-------------------
<-- empty string
2013-03-21 00:00:00
select ISNULL(CONVERT(VARCHAR(23), WorkingDate,121),'') from uv_Employee
Try this code
(case when CONVERT(VARCHAR(10), CreatedDate, 103) = '01/01/1900' then '' else CONVERT(VARCHAR(24), CreatedDate, 121) end) as Date_Resolved
If you CAST your data as a VARCHAR() instead of explicitly CONVERTing your data you can simply
SELECT REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM','')
The CAST will automatically return your Date then as Jun 18 2020 12:46PM fix length strings formats which you can additionally SUBSTRING()
SELECT SUBSTRING(REPLACE(CAST(CreatedDate AS VARCHAR(20)),'Jan 1 1900 12:00AM',''),1,11)
Output
Jun 18 2020
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
An alternate solution that covers both min (1/1/1900) and max (6/6/2079) dates:
ISNULL(NULLIF(NULLIF(CONVERT(VARCHAR(10), CreatedDate, 120), '1900-01-01'), '2079-06-06'), '').
Whatever solution you use, you should do a conversion of your date (or datetime) field to a specific format to bulletproof against different default server configurations.
See CAST and CONVERT on MSDN: https://msdn.microsoft.com/en-us/library/ms187928.aspx
Use this inside of query, no need to create extra variables.
CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN '' ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'
Works like a charm.
Simpler method that worked. ISNULL Nested CAST function can remove 1900-1-1 value if data is NULL
ISNULL(CAST(CAST(<<DateColumn>> AS DATE) AS Varchar),' ') [<<Date Column Name>>]

Only Date Part comparison with System Date in SQL Server

I have a stored procedure :-
CREATE procedure St_Proc_GetTimeEntryID
#userID int,
#timeEntryID int output
as begin
set nocount on;
SET #timeEntryID=0
DECLARE #TEMP INT
SET #TEMP=0
SELECT #TEMP=ProductionTimeEntryID
FROM production
WHERE ProductionTimeEntryID =
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CalendarDate = (select GETDATE()))
and IsTaskCompleted=1 )
BEGIN
SET #timeEntryID=#TEMP
END
END
Here CalendarDate is column which containing Date As 06/26/201212:00PM format .
I want to compare the date part only with system date part (06/26/2012 = 06/26/2012) in my subquery which is
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CalendarDate = (select GETDATE()))
and IsTaskCompleted=1 )
Please guide me what modification i ll do to get the result.
In SQL2K8;
... WHERE CAST(CalendarDate AS DATE) <= CAST(GETDATE() AS DATE)
(This will negate any index use on CalendarDate, alternatively bracket CalendarDate between CalendarDate >= CAST(CalendarDate AS DATE) AND < DATEADD(...)
The most efficient method (meaning fully able to utilize an index on CalendarDate, if one exists) is going to be, on SQL Server 2000/2005:
DECLARE #today SMALLDATETIME;
SET #today = DATEDIFF(DAY, 0, CURRENT_TIMESTAMP);
...
WHERE CalendarDate >= #today
AND CalendarDate < DATEADD(DAY, 1, #today);
If using SQL Server 2008+:
DECLARE #today DATE = CURRENT_TIMESTAMP;
...
WHERE CalendarDate >= #today
AND CalendarDate < DATEADD(DAY, 1, #today);
You can also use a direct cast in SQL Server 2008+, but I'm not 100% sure this is guaranteed to use an index on CalendarDate in all scenarios:
WHERE CONVERT(DATE, CalendarDate) = CONVERT(DATE, CURRENT_TIMESTAMP);
Because this casting does not work with other date/time data types, for consistency I much prefer the open-ended range technique, and definitely do not condone most of the scenarios where you perform implicit or explicit conversions on the column (since this usually means an index won't be used). I've ranted about this and several other date/time atrocities plenty at the following blog posts:
What do BETWEEN and the devil have in common?
Bad habits to kick : mis-handling date / range queries
Something like this?
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=412
and (convert(datetime, convert(varchar(100), CalendarDate, 106)) <= convert(datetime, convert(varchar(100), GETDATE(), 106)))
and IsTaskCompleted=1 )
Use convert function
In your case:
SELECT CONVERT(DATE,GETDATE(),101)
More specifically:
(SELECT MAX(ProductionTimeEntryID)
FROM production
where UserID=#userID
and (CONVERT(DATE,CalendarDate) = CONVERT(DATE,GETDATE()))
and IsTaskCompleted=1 )

T-SQL Date Format with Substring

We have a field by name target_date. It's a string. We need to extract the month and year from that field.
Example:
1/10/2011(dd/mm/yyyy)
we are trying with
substring(target date,findstring(targetdate,"/",1)+1,(findstring(targetdate,"/",2)-findstring(targetdate,"/",1)+1)).
Please help me.
Thanks.
Well, first issue here is that you are storing datetime as string. I will assume that for whatever reason you can't fix that...
What I would do in this case is use convert() function
convert(datetime, target_date, 103)
and then extract needed values using month() and year()
Description
Use CAST and CONVERT (Transact-SQL) to convert your string to datetime.
Use DATEPART (Transact-SQL) to extract month and year.
Sample
-- this will give you the month of your target_date
datePart(mm, convert(datetime, target_date, 103))
-- this will give you the year of your target_date
datePart(yyyy, convert(datetime, target_date, 103)) -- 2011
-- or
datePart(yy, convert(datetime, target_date, 103)) -- 11
declare #date varchar(10)
set #date = '1/10/2011'
select DATEPART(yyyy, CONVERT(datetime, #date, 103)), DATEPART(mm, CONVERT(datetime, #date, 103))
Try this :
Month : left(right(target_date , 7),2)
Year: right(target_date , 4)
This is if the format of target_date is always the same (ie. dd/mm/yyyy)

How to get a date in YYYY-MM-DD format from a TSQL datetime field?

How do I retrieve a date from SQL Server in YYYY-MM-DD format? I need this to work with SQL Server 2000 and up. Is there a simple way to perform this in SQL Server or would it be easier to convert it programmatically after I retrieve the result set?
I've read the CAST and CONVERT on Microsoft Technet, but the format I want isn't listed and changing the date format isn't an option.
SELECT CONVERT(char(10), GetDate(),126)
Limiting the size of the varchar chops of the hour portion that you don't want.
SELECT convert(varchar, getdate(), 100) -- mon dd yyyy hh:mmAM
SELECT convert(varchar, getdate(), 101) -- mm/dd/yyyy – 10/02/2008
SELECT convert(varchar, getdate(), 102) -- yyyy.mm.dd – 2008.10.02
SELECT convert(varchar, getdate(), 103) -- dd/mm/yyyy
SELECT convert(varchar, getdate(), 104) -- dd.mm.yyyy
SELECT convert(varchar, getdate(), 105) -- dd-mm-yyyy
SELECT convert(varchar, getdate(), 106) -- dd mon yyyy
SELECT convert(varchar, getdate(), 107) -- mon dd, yyyy
SELECT convert(varchar, getdate(), 108) -- hh:mm:ss
SELECT convert(varchar, getdate(), 109) -- mon dd yyyy hh:mm:ss:mmmAM (or PM)
SELECT convert(varchar, getdate(), 110) -- mm-dd-yyyy
SELECT convert(varchar, getdate(), 111) -- yyyy/mm/dd
SELECT convert(varchar, getdate(), 112) -- yyyymmdd
SELECT convert(varchar, getdate(), 113) -- dd mon yyyy hh:mm:ss:mmm
SELECT convert(varchar, getdate(), 114) -- hh:mm:ss:mmm(24h)
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
Starting with SQL Server 2012 (original question is for 2000):
SELECT FORMAT(GetDate(), 'yyyy-MM-dd')
The form you are after is listed in the books online documentation.
http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx
For example, try the following:
select convert(varchar,getDate(),120)
select convert(varchar(10),getDate(),120)
The convert function with the format specifier 120 will give you the format "yyyy-MM-dd HH:mm:ss", so you just have to limit the length to 10 to get only the date part:
convert(varchar(10), theDate, 120)
However, formatting dates is generally better to do in the presentation layer rather than in the database or business layer. If you return the date formatted from the database, then the client code has to parse it to a date again if it needs to do any calculations on it.
Example in C#:
theDate.ToString("yyyy-MM-dd")
For YYYYMMDD try
select convert(varchar,getDate(),112)
I have only tested on SQLServer2008.
I'm not sure why the simplest way has been ignored/omitted in the answers above:
SELECT FORMAT(GetDate(),'yyyy-MM-dd');--= 2020-01-02
SELECT FORMAT(GetDate(),'dd MMM yyyy HH:mm:ss');-- = 02 Jan 2020 08:08:08
I prefer the second one because whichever language you speak, you will understand what date it is!
Also SQL Server always 'understands' it when you send that to your save procedure, regardless of which regional formats are set in the computers - I always use full year (yyyy), month name (MMM) and 24 hour format (capital HH) for hour in my programming.
One other way...
CONVERT(varchar, DATEPART(yyyy, #datetime)) + '/' + CONVERT(varchar, DATEPART(mm, #datetime)) + '/' + CONVERT(varchar, DATEPART(dd, #datetime))
For those who would want the time part as well (I did), the following snippet may help
SELECT convert(varchar, getdate(), 120) -- yyyy-mm-dd hh:mm:ss(24h)
SELECT convert(varchar, getdate(), 121) -- yyyy-mm-dd hh:mm:ss.mmm
SELECT convert(varchar, getdate(), 126) -- yyyy-mm-ddThh:mm:ss.mmm
--example -- 2008-10-02T10:52:47.513
replace(convert(varchar, getdate(), 111), '/','-')
Will also do trick without "chopping anything off".
In case someone wants to do it the other way around and finds this.
select convert(datetime, '12.09.2014', 104)
This converts a string in the German date format to a datetime object.
Why 104? See here: http://msdn.microsoft.com/en-us/library/ms187928.aspx
In your cast and convert link, use style 126 thus:
CONVERT (varchar(10), DTvalue, 126)
This truncates the time. Your requirement to have it in yyyy-mm-dd means it must be a string datatype and datetime.
Frankly though, I'd do it on the client unless you have good reasons not to.
You may also use. This is by using the new datatype DATE. May not work in all previous versions, but greatly simplified to use in later version.
SELECT CAST(getdate() AS DATE)
SELECT LEFT(CAST(getdate() AS DATE), 7)
If you want to use it as a date instead of a varchar again afterwards, don't forget to convert it back:
select convert(datetime,CONVERT(char(10), GetDate(),126))
From SQL Server 2008 you can do this: CONVERT(date,getdate())
SELECT CONVERT(NVARCHAR(20), GETDATE(), 23)
I would use:
CONVERT(char(10),GETDATE(),126)
SELECT Code,Description FROM TABLE
-- This will Include only date part of 14th March 2010. Any date with date companents will not be considered.
WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate <= DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))
-- This will Include the whole day of 14th March 2010
--WHERE ID= 1 AND FromDate >= CONVERT(DATETIME, '2010-02-14', 126) AND ToDate < DATEADD(dd, 1, CONVERT(DATETIME, '2010-03-14', 126))
Using a CASE statement for each of the convert / cast functions always works for me:
Please replace tableXXXXY with your table name, and issueDate_dat with the name of your datetime field in that table:
SELECT issueDate_dat, CONVERT(varchar, DATEPART(yyyy, issuedate_dat)) AS issueDateYYYY
, CASE WHEN (len(CONVERT(varchar, DATEPART(mm, issuedate_dat))) < 2) THEN '0' +CONVERT(varchar, DATEPART(mm, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(mm, issuedate_dat)) END AS issueDateMM
, CASE WHEN (len(CONVERT(varchar, DATEPART(dd, issuedate_dat))) <2) THEN '0' +CONVERT(varchar, DATEPART(dd, issuedate_dat)) ELSE CONVERT(varchar, DATEPART(dd, issuedate_dat)) END AS issueDateDD
FROM tableXXXXY
Hope this was helpful. chagbert.
This solution works for me, simple and effective (with 126 too)
CONVERT(NVARCHAR(MAX), CAST(GETDATE() as date), 120)
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
cmdGetPaymentStatement.Parameters.AddWithValue("#pStartDate", DateTime.Parse("22/12/2017", culture, System.Globalization.DateTimeStyles.AssumeLocal)).IsNullable = true;
Seems unnecessary to do any strange things, if you want your date to be seperated by slash.
Just escape it with a backslash. Otherwise you will end up with a dot.
SELECT FORMAT(GETDATE(),'yyyy\/MM');
Tested on SQL Server 2016
If your source date format is all messed up, try something along the lines of:
select
convert(nvarchar(50),year(a.messedupDate))+'-'+
(case when len(convert(nvarchar(50),month(a.messedupDate)))=1
then '0'+ convert(nvarchar(50),month(a.messedupDate))+'-'
else convert(nvarchar(50),month(a.messedupDate)) end)+
(case when len(convert(nvarchar(50),day(a.messedupDate)))=1
then '0'+ convert(nvarchar(50),day(a.messedupDate))+'-'
else convert(nvarchar(50),day(a.messedupDate)) end)
from messytable a
As string processing is expensive, and FORMAT more so, I am surprised that Asher/Aaron Dietz response is not higher, if not top; the question is seeking ISO 8601 date, and isn't specifically requesting it as a string type.
The most efficient method would be any of these (I've included the answer Asher/Aaron Dietz have already suggested for completeness):
All versions
select cast(getdate() as date)
select convert(date, getdate())
2008 and higher
select convert(date, current_timestamp)
ANSI SQL equivalent 2008 and higher
select cast(current_timestamp as date)
References:
https://sqlperformance.com/2015/06/t-sql-queries/format-is-nice-and-all-but
https://en.wikipedia.org/wiki/ISO_8601
https://www.w3schools.com/sql/func_sqlserver_current_timestamp.asp
https://learn.microsoft.com/en-us/sql/t-sql/functions/current-timestamp-transact-sql?view=sql-server-ver15
change GetDate() to any format as String:
SELECT FORMAT(GetDate(), 'yyyy-MM-dd HH:mm:ss')

Resources