SQL Server Query: Convert to dd/mm/yyyy from datetime - sql

I'm querying a max datetime to bring in the most recent record from another table surrounding a common ID coloumn. I would like to however format this datetime in the standard UK dd/mm/yyyy format. How would I do so? I just cant seem to get this...
Here is my code:
(SELECT TOP 1 MemberPayments.CoverFinishDay
FROM
Members LEFT JOIN MemberPayments
ON Members.MemberID = MemberPayments.MemberID
AND CoverFinishDay = (
SELECT MAX(CoverFinishDay)
FROM MemberPayments
WHERE Members.MemberID = MemberPayments.MemberID
))
CoverFinishDay is stored in standard american datetime. currently the query works, just in the wrong format. I need the output in dd/mm/yyyy

This will help you:
SELECT CONVERT(VARCHAR, GETDATE(), 105)
This is for SQL Sever

If you are using SQL Server 2012 you can convert any date using FORMAT function. In your case you can do like this:
SELECT FORMAT (MemberPayments.CoverFinishDay, 'd', 'en-GB')
For mor info you can access the page: http://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx

Related

How to convert date format in string using SQL query?

I am using ASP.NET MVC with petapoco. I want to display data from database table in the view as it has date column and I want to convert that date format in varchar like 'dd-mm-yyyy'.
My date column is TransactionDate.
My query is as follows, I have used convert function, but it is not working, my date column is still appearing with milliseconds like /Date152235232/.
Please help me with this and tell me how I can convert that particular TransactionDate column in the table to display date in the 'dd-mm-yyyy' format.
var sql = db.Query("Select CONVERT(varchar, d.TransactionDate ,101), d.DocumentId, d.SurveyNumber, d.FullName, d.Location, documenttype.DocumentTypeName, d.VillageName, d.PlanNumber, d.OwnerName, d.ContactNumber, d.Email, d.Status, d.TransactionDate FROM Document d " +
$"INNER JOIN DocumentType ON d.DocumentTypeId = documenttype.DocumentTypeId");
Here in the query I am joining two tables to fetch data from the table to display it
Try this: 105 will give you format dd-mm-yyyy: https://www.itsupportguides.com/knowledge-base/sql-server/sql-how-to-convert-datetime-to-formatted-date-string-dd-mm-yyyy/
CONVERT( VARCHAR, d.TransactionDate, 105 )
If your filed is date type and you want formatting dd-mm-yyyy then
you should have to use
select CONVERT (varchar(10), getdate(), 105)
return :15-08-2018
but if you want dd/mm/yyyy then you have to use below
CONVERT(VARCHAR(20), getdate(), 103) as date_conv
15/08/2018
more about date format
Your query is returning the date twice. Perhaps this will do what you want:
select convert(varchar(10), d.TransactionDate, 105) as TransactionDate,
d.DocumentId,
d.SurveyNumber,
d.FullName,
d.Location,
dt.DocumentTypeName,
d.VillageName,
d.PlanNumber,
d.OwnerName,
d.ContactNumber, d.Email,
d.Status
from Document d join
DocumentType dt
on d.DocumentTypeId = dt.DocumentTypeId;
Note the original TransactionDate has been removed from the query. I also added a table alias for DocumentType.

date time stored as varchar in sql how to filter on varchar

I am working on a project in which dates and times ar stored as a varchar e.g. "30-11-2017,7:30" first date in dd-mm-yyy format and then time separated with a comma. I am trying to filter on it but it is not working correctly kindly guide me how to filter data on date.
select *
from timetrack
where startDateAndTime >= '30-11-2017,7:30'
In attached image records have been shown. When I apply above query it shows no records
You can easily convert your date to SQL datatype datetime uisng parse function, for example select parse('30-11-2017,7:30' as datetime using 'it-IT').
So, in your case, you can apply this function in where clause, so you can easily apply comparison between dates:
select *
from timetrack
where parse(startDateAndTime as datetime using 'it-IT') >= '2017-11-30 07:30:00.000'
Your format is apparently italian :) But you have to specify your own date in the format convertable to datetime, as I have done in above example.
NOTE: parse is available starting with SQL Management Studio 2012.
Unless you are using ISO date format (yyyy-MM-dd HH:mm:ss or close) applying ordering (which inequalities like greater than or equal use) will not work: the date order is disconnected from the string ordering.
You'll need to parse the date and times into a real date time type and then compare to that (details of this depend on which RDBMS you are using).
If, you want to just filter out the date then you could use convert() function for SQL Server
select *
from timetrack
where startDateAndTime >= convert(date, left(#date, 10), 103)
Else convert it to datetime as follow
select *
from timetrack
where startDateAndTime >= convert(datetime, left(#date, 10)+' ' +
reverse(left(reverse(#date), charindex(',', reverse(#date))-1)), 103)
You need the date in a datetime column, Otherwise you can't filter with your current varchar format of your date.
Without changing the existing columns, this can be achieved by making a computed column and making it persisted to optimize performance.
ALTER TABLE test add CstartDateTime
as convert(datetime, substring(startDateAndTime, 7,4)+ substring(startDateAndTime, 4,2)
+ left(startDateAndTime, 2) +' '+ right(startDateAndTime, 5), 112) persisted
Note: this require all rows in the column contains a valid date with the current format
Firstly, you need to check what is the data that is entered in the 'startDateAndTime' column,then you can convert that varchar into date format
If the data in 'startDateAndTime' column has data like '30-11-2017,07:30', you would then have to convert it into date:
SELECT to_date('30-11-2017,07:30','dd-mm-yyyy,hh:mm') from dual; --check this
--Your query:
SELECT to_date(startDateAndTime ,'dd-mm-yyyy,hh:mm') from timetrack;

How to filter Time portion of a DateTime column

I want to retrive data from table according to a particular time so I use this query below.
select * from a
where convert(smalldatetime,date,datepart(hh,date)) ='09:12:00'
but I get no row as result. So what should I do for my expected result?
You can convert directly to varchar as below
SELECT * FROM a
WHERE CONVERT(VARCHAR(8), [date], 108) = '09:12:00'
Try this:
SELECT *
FROM a
WHERE CONVERT(VARCHAR(8), [DATE],108) = '09:12:00'
Your datatype is already smalldatetime so you have to convert to varchar and compare with string.
EDIT:
Answer explanation:
You have smalldatetime inside [DATE] column. For example 2015-10-01 09:12:00. To compare only time you need to convert to string which contains only time. For this reason you will use command CONVERT from TSQL.
It will convert smalldatetime to 8 characters string. As a result you will have 09:12:00 and then you compare it with your string.
In Sql server 2008 you can convert to TIME. By specifying TIME(0) you have the desired format:
SELECT *
FROM a
WHERE CAST(date as time(0)) ='09:12:00'
//CONVERT(data_type(length),expression,style)
SELECT * FROM a
WHERE CONVERT(varchar(8),[columnName],108) = '09:12:00'

Parsing date in sql query

I am using SQL Server 2005.
My Trade_Date column is of datatype datetime.
It has values as: 2/12/2013 11:59:00 PM , 2/13/2013 11:59:00 PM
i.e. different dates with time.
I want to compare date [only date] in where clause.
I am trying with following query:
select *
from foclosing
where CONVERT(varchar(11), Trade_Date) like '2/12/2013 %'
or
select *
from foclosing
where Trade_Date = CONVERT(datetime, '2/12/2013')
but both of these queries are not working.
What can be the issue?
select * from foclosing
where Trade_Date >= '20130212' AND Trade_Date < '20130213'
Use yyyymmdd which is safe for SQL Server
Don't apply functions to columns, then compare (your 1st query)See mistake 2 here: https://www.simple-talk.com/sql/t-sql-programming/ten-common-sql-programming-mistakes/
Don't compare locale-based dates as varchar (your 1st query)
Trade_Date has a time element which is why your 2nd query fails
In summary, a date conversion should not be used for examples like this: datetime is a range

Insert converted varchar into datetime sql

I need to insert a varchar in my table. The type in the table is a datetime so I need to convert it. I didn't think this would be to big of a problem however it keeps inserting 1900-01-01 00:00:00.000 instead of the date I want. When I do a select with my converted date it does show me the correct date.
I'll show you the code:
INSERT INTO Item (CategoryId, [Date], Content, CreatedOn)
SELECT
CategoryId, Convert(datetime, '28/11/2012', 103), Content, GetDate()
FROM
Item i
JOIN
Category c ON i.CategoryId = c.Id
JOIN
Division d ON d.Id = c.DivisionId
WHERE
Date = Convert(datetime, '31/03/2005', 103)
AND d.Id = '142aaddf-5b63-4d53-a331-8eba9b0556c4'
The where clause works perfectly and gives me the filtered items I need, all data is correctly inserted except for the converted date. The gives like I said 1900-...
If I just do the select so:
SELECT CategoryId, Convert(datetime, '28/11/2012', 103), Content, GetDate()
FROM Item i
JOIN Category c ON i.CategoryId = c.Id
JOIN Division d ON d.Id = c.DivisionId
WHERE Date = Convert(datetime, '31/03/2005', 103) AND d.Id = '142aaddf-5b63-4d53-a331-8eba9b0556c4'
I get the correct date being: 2012-11-28 00:00:00.000. I have tried to use a different conversion like:
Convert(datetime, '20121128')
But that just gives the same problem. Anyone that sees what I'm doing wrong?
Thx
If you must use a string-based date format, you should pick one that is safe and works in every SQL Server instance, regardless of date format, language and regional settings.
That format is known as ISO-8601 format and it's either
YYYYMMDD (note: **NO** dashes!)
or
YYYY-MM-DDTHH:MM:SSS
for a DATETIME column.
So instead of
Convert(datetime, '28/11/2012', 103)
you should use
CAST('20121128' AS DATETIME)
and then you should be fine.
If you're on SQL Server 2008 - you could also look into using DATE (instead of DATETIME) for cases when you only need the date (no time portion). That would be even easier than using DATETIME and having the time portion always be 00:00:00
Just wanted to throw out the fact that I found this SO Question (and many others like it) years later while trying to find the answer to my problem.
If you are troubleshooting this inside a stored procedure, the parameter of the stored procedure is where you need to modify. The programmer who created the code I'm troubleshooting had #ddt CHAR(10) and no modifications inside the stored procedure resolved the problem. I had to change the parameter to #ddt smalldatetime.