SQL Server 2012 - Convert(varchar,'2018-12-16 17:33:29',105) + ' ' Convert(varchar,'2018-12-16 17:33:29',108) is not showing correct data - sql-server-2012

I have a datetime datatype column with the data format '16-12-2018 17:33:29' (dd-mm-yyyy hh:mm:ss). So if I get input data as 2018-12-16 17:33:29, the data needs to be converted into '16-12-2018 17:33:29'.
This is the datatype conversion I have been trying,
SELECT
CONVERT(VARCHAR(10), '2018-12-16 17:33:29', 105) + ' ' +
CONVERT(VARCHAR(10), '2018-12-16 17:33:29', 108)
Output is: 2018-12-16 2018-12-16
But if I use Getdate() instead of hardcoded value I'm getting the expected data format:
SELECT
CONVERT(VARCHAR(10), GETDATE(), 105) + ' ' +
CONVERT(VARCHAR(10), GETDATE(), 108)
Output is: 16-12-2018 17:36:18
My question is, why the same datatype conversion query is working if we use getdate() but not in hardcoded values?

Your second query has a date value as second parameter. Your first query has just a string there.
The fact that that string looks like a date is not important as far as SQL is concerned.
Edit.
When your column has a datetime type, then use datetime values to transport data. Try and keep away from strings as often as possible.

Related

after converting date only getting date not time

I am trying to convert date as mm/dd/yy format in Sql Server 2008 but after conversion i have only got formatted date but in my database there also time . my database value is :
2003-02-28 17:22:43.000
2003-02-28 17:22:43.000
2003-02-28 17:24:26.000
2003-02-28 17:24:26.000
2003-03-24 09:45:25.000
2003-03-24 09:45:25.000
2003-03-24 09:46:36.000
2003-03-24 09:46:36.000
2006-07-20 12:47:31.070
2003-03-27 15:44:53.000
2003-03-27 15:44:53.000
2003-03-27 15:51:56.000
2003-03-27 15:51:56.000
2003-03-27 16:05:03.000
my query for convert date format is
SELECT CONVERT(VARCHAR(20), StatusDate, 101) AS Post_Converted,StatusDesc, RowVersionInitials from PurchaseOrderStatusHistory
and my output is
05/29/2014
05/29/2014
05/29/2014
05/29/2014
date is successfully formatted but the 'time' is missing . please suggest me how would i get the database time also .
For some reason, SQL Server doesn't offer mm/dd/yyyy with the time component. I would advise you to use format 120 -- the ISO standard format -- but you are asking specifically for this.
You can concatenate the values together:
SELECT CONVERT(VARCHAR(20), StatusDate, 101) + ' ' + CONVERT(VARCHAR(20), StatusDate, 108) AS Post_Converted,
StatusDesc, RowVersionInitials
FROM PurchaseOrderStatusHistory;
Instead of 108, you might want 114:
SELECT CONVERT(VARCHAR(20), StatusDate, 101) + ' ' + CONVERT(VARCHAR(8), StatusDate, 114) AS Post_Converted,
StatusDesc, RowVersionInitials
FROM PurchaseOrderStatusHistory;
This gives you the flexibility of adding milliseconds.
CONVERT accepts a third parameter, in your case 101 to specify the format.
Find details here
What you'd need is - assumably - this
SELECT CONVERT(VARCHAR(20), StatusDate, 120)
... or another appropriate output format.
With SQL Server 2012+ there is FORMAT(), but with v2008 you cannot use this...

Issue with Date format in SQL

I am currently using SQL Server 2008. I am extracting a column F254 value from a SQL query where it is returning the date format in MM/DD/YYYY (e.g. 8/17/2017).
I need the output to be in format YYYYMMDD (e.g. 20170817).
Note that the column F254 is of datatype char(10) and I cannot change the datatype.
I have tried below but the getting the needed output
H.F254 AS Original_Date, --> 8/17/2017
CONVERT(VARCHAR(10), H.F254, 111) AS eg1, --> 8/17/2017
REPLACE(CONVERT(VARCHAR(10), H.F254, 103), '/', '') AS eg2 -->8172017
CONVERT(VARCHAR(9), H.F254, 112) AS eg3 --> 8/17/2017
I have also checked the following Date Format but its not working
I think you have to convert it to a date first!
select convert(varchar(10),cast(H.F254 as date),112)

Convert date format doesn't take effect on self made date string in SQL Server

I have a rather strange issue here. I have a date string, which I've created partly by myself to incorporate a variable. The problem is, that I'm setting another language settings. In this case, I have to also convert the string to fit the language settings format. I'm using this code:
cast(convert(varchar, cast(cast(getdate() as date) as varchar) + ' ' + RIGHT('0' + CAST(#HR as varchar), 2) + ':00:00.000', 120) as datetime)
I get the error "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.", which is normal if you assign wrong date format before casting.
The problem is, that when I try to convert the personally created date string, it doesn't change its format no matter what format code I set it in. That doesn't change even when I hardcode a number instead of my variable:
convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
results in 2016-09-14 02:00:00.000
For example,
convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
Results in 09/14/2016.
Even though I have a different language setting, isn't SQL server supposed to always recognize the date format in the standard format?
Please give me an advice so I can overcome this issue.
Thanks in advance!
PS: I managed to solve my issue by inserting converted datetime column in a variable before setting bulgarian language. I'm still very interested to know what causes the problem though.
Ok I may have a soution for the question: Why is the format differently handled in SQL-SERVER when converting.
CONVERT(data_type(length),expression,style)
The STYLEvalue only applies for date/time.
So it's because of the datatype that the output is different.
See following example:
SELECT convert(varchar, dateadd(Hour, 2, getdate()), 101) as datetime
You get the result:
09/14/2016
Here your are converting a datetime datatype into a varchar and the STYLE-value with 101 applies for CONVERT and the output is converted in that format.
Example 2 is the same but the inner most part is casted into a varchar before converting it:
SELECT convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101) as datetime
The result you get is:
Sep 14 2016 4:09PM
So because we are trying to convert a varchar into a varchar the STYLE-value doesn't apply for the conversion.
That is also why the first query is handled diffrent then the other:
SELECT convert(varchar, cast(cast(getdate() as date) as varchar) + ' 0' + CAST(2 as varchar) + ':00:00.000', 101)
Here you cast into varchar cast(cast(getdate() as date) as varchar) before converting. So the STYLE-value is not applying because it's not from datatype date/time.
I hope it made it a bit clear. Let me know if this helped.
When you use convert to format the datetime, you can pass a style number to it.
Looky here or here for those numbers.
The query below converts custom created datetimes to the 126 (ISO8601) format.
declare #d int = 2;
SELECT
CONVERT(varchar,
CONVERT(datetime,
CONCAT(FORMAT(GETDATE(),'yyyy-MM-dd'),' ',#d,':0')
)
,126) AS MyDateStamp1,
CONVERT(varchar,
CONVERT(datetime,
CONVERT(varchar,GETDATE(),102)+' '+convert(varchar,#d)+':0'
)
,126) AS MyDateStamp2;
The FORMAT & CONCAT functions can be used in SQL Server 2012 and beyond.
But if you have an earlier version then CONVERT should work instead.
Additional tip:
If you're using the CONVERT solution above, note that
"convert(varchar, CAST(dateadd(Hour, 2, getdate()) AS varchar), 101)" calls for you to set datatype to varchar.
I just came across code
"Convert(date,ML.StartDate,101)"
and since style 101 is mm/dd/yyyy, and the output was yyyy-mm-dd, I knew something was wrong. By changing the code to
"Convert(varchar,ML.StartDate,101)"
the proper date style was displayed in the result set.

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I have a table with a column that stores the date and time. I need to write a query to get only the date from that column,
SELECT CAST(CONVERT(VARCHAR, LoginTime, 101) AS datetime) FROM AuditTrail
But, when I run the query I am getting this error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
the data in the column is datetime ex: 2012-06-18 12:08:04.000
so i need to extract the date only and remove the time
note that the [Logintime] column is datatime format
Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
WHERE ISDATE(LoginTime) = 1
Click here to view result
EDIT :
As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT
SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail
or
SELECT LEFT(LoginTime,10) FROM AuditTrail
EDIT 2 :
The major reason for the error will be in your date in WHERE clause.ie,
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('06/18/2012' AS DATE)
will be different from
SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <=
CAST('18/06/2012' AS DATE)
CONCLUSION
In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.
hope this may help you:
SELECT CAST(LoginTime AS DATE)
FROM AuditTrail
If you want to have some filters over this datetime or it's different parts, you can use built-in functions such as Year and Month
as you can see on the answer to this question:
Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = ##spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.
The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.
some problem, but I find the solution, this is :
2 February Feb 28 (29 in leap years)
this is my code
public string GetCountArchiveByMonth(int iii)
{
// iii: is number of months, use any number other than (**2**)
con.Open();
SqlCommand cmd10 = con.CreateCommand();
cmd10.CommandType = CommandType.Text;
cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, #start, 103) and CONVERT(VARCHAR, #end, 103)";
cmd10.Parameters.AddWithValue("#start", "" + iii + "/01/2019");
cmd10.Parameters.AddWithValue("#end", "" + iii + "/30/2019");
string result = cmd10.ExecuteScalar().ToString();
con.Close();
return result;
}
now for test
lbl1.Text = GetCountArchiveByMonth(**7**).ToString(); // here use any number other than (**2**)
**
because of check **February** is maxed 28 days,
**

To change date format in sql

I have date in mm/dd/yyyy format in database.I want to display in form as dd/mm/yyyy.
Can anybody help?I want to get time along with date.
CONVERT(VARCHAR(10), YourField, 103)
Per your comment - you want the time as well.
select (CONVERT(VARCHAR(10), YourField, 103) + ' ' + CONVERT(VARCHAR(15), YourField, 108)) as DateTime
http://msdn.microsoft.com/en-us/library/aa226054.aspx
A date value doesn't have a format at all. It gets it's format when you convert it to a string.
You can use the convert function to convert the value in the database, but you should rather leave that to the code in the user interface.
What Guffa said, plus this from books online: http://msdn.microsoft.com/en-us/library/aa226054.aspx
CONVERT(VARCHAR(10), column, 103)
103 is yyyy
3 is yy