Convert date to varchar in SQL Server - sql

How do I convert a column which is date type to varchar?
Sample data:
ENDDATE (DATE TYPE)
'1947-12-01 00-00-00'
Requested results:
ENDDATE (VARCHAR)
121947

If I understand the question correctly, you need the ENDDATE of value '1947-12-01 00-00-00' as 121947. You can use the below query
SELECT RIGHT(MONTH(ENDDATE)*1010000+YEAR(ENDDATE),6)

If you are working with 2012 version or higher, you can use format. For earlier versions you can use convert with some string manipulations:
DECLARE #D as date = '1947-12-01'
SELECT REPLACE(RIGHT(CONVERT(char(10), #d, 103), 7), '/', '') As charValue2008,
FORMAT(#d, 'MMyyyy') as charValue2012
Results:
charValue2008 charValue2012
121947 121947
Please note that Format runs relativley slow, so if you have a lot of rows you might want to choose another way to do that.

Related

Error when converting varchar to date ddmmyyyy

I have a varchar column with the following format ddmmyyyy and I'm trying to convert it to date in the format dd-mm-yyyy. I'm using the query below but I get the error:
Conversion failed when converting date and/or time from character string.
select *, coalesce(try_convert(date, newdate, 105), convert(date, newdate))
from mydate
You don't have a date, you have a string. So, you can use string operations:
select stuff(stuff(newdate, 5, 0, '-'), 3, 0, '-')
If you want to convert to a date, you can do:
select convert(date, concat(right(newdate, 4), substring(newdate, 3, 2), left(newdate, 2)))
You could then format this as you want.
However, you should not be converting the value to a date. You should be storing it as a date in the first place.
To turn your string to a date, you can just [try_]cast() it; SQL Server is usually flexible enough to figure out the format by itself:
try_cast(newdate as date)
If you want to turn it back to a string in the target format, then you can use format():
format(try_cast(newdate as date), 'dd-MM-yyyy')
Compared to pure string operations, the upside of the try_cast()/format() approach is that it validates that the string is a valid date in the process.
Have to agree with the others. Why are you storing a date as a string in the first place? In a non-standard format, no less? Here's one way, but you should really fix the data model. Store dates as dates.
DECLARE #badIdea table (dt char(8));
INSERT #badIdea(dt) VALUES('21052020');
SELECT newdate = TRY_CONVERT(date, RIGHT(dt,4) + SUBSTRING(dt,3,2) + LEFT(dt,2))
FROM #badIdea;
BTW 105 won't work because it requires dashes. This works:
SELECT CONVERT(date, '21-05-2020', 105);
That's a bad format too, IMHO, because who knows if 07-08-2020 is July 8th or August 7th. But at least that one is supported by SQL Server. Your current choice is not.
SQL doesn't store date data types in different formats, and it's probably not a good idea to try and adjust this.
If, however, you are wanting a result set to simply display the date in a different format, you are on the right track. You just need to convert your date data type to a string.
SELECT *
, COALESCE ( TRY_CONVERT ( CHAR(10), newdate, 105 ), CONVERT ( CHAR(10), newdate ) )
FROM mydate

SQL Server : change date format

I need to change the date format from 'yyyy-mm-dd' to 'dd.mm.yyyy'.
I have data in my table like this '2018-08-08', I need convert it to '08.08.2018'.
I have tried:
UPDATE daily_tasks
SET date = REPLACE(date, date, CONVERT(VARCHAR(255), daily_tasks.date, 102))
WHERE 1;
But, it doesn't work.
Ideally you should be storing your dates as bona-fide date columns, not as text. That being said, the date text '2018-08-08' is in fact in an ISO format, and would still allow you to do things like sort and compare against other date literals, so it is not so bad.
But converting this text to a '08.08.2018' format is the wrong thing to do. If a anything, you might want to consider adding a new date column new_date to store this date information. Do that, and then populate it with:
UPDATE daily_tasks
SET new_date = TRY_CONVERT(datetime, date);
Store your date as DATE datatype and when you read data from database use
DECLARE #myDate DATE = '2018-08-08'
SELECT FORMAT(#myDate, 'dd.MM.yyyy')
SELECT CONVERT(VARCHAR(10), #myDate, 104)
Your syntax looks like SQL Sever, so i would do :
UPDATE daily_tasks
SET Col = REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
WHERE . . . ;
However, i would not recommend to do this, just use CONVERT() with SELECT statement whenever necessary :
SELECT REPLACE(CONVERT(VARCHAR(10), daily_tasks.date, 103), '/', '.')
Regardless of the database, dates are stored in an internal format. This is the correct way to store dates. Do not store dates as strings.
You can specify the format when you query:
CONVERT(VARCHAR(255), daily_tasks.date, 102)
Or, you can even add a computed column to provide this information:
alter table daily_tasks
add date_display as ( CONVERT(VARCHAR(255), daily_tasks.date, 102) ) ;
You could convert the date column to a varchar to store the date in your specified format. However I strongly recommend against this. You should leave it stored as a date.
If you want to do a SELECT to get the data out then you can convert it to your specified format like this:
SELECT CONVERT(VARCHAR, daily_tasks.date, 4)

Convert varchar containing various formats to DATETIME

I have a record_created column of type varchar containing multiple values formatted in two different ways throughout.
2017-04-17 16:55:53.3840460
Sep 18 2015 11:25PM
How can I convert this column into a DATETIME to be compared to GETDATE?
GETDATE() is SQL Server specific if so, then you can use try_convert() :
select cast(try_convert(datetime2, col) as datetime)
from table t
where try_convert(datetime2, col) is not null;
However, if the string date is exactly the same format which you have provide then you can simply do casting :
select cast(cast(col as datetime2) as datetime)
from table t;
If you are using SQL Server, then you may be able to use the CONVERT function here:
SELECT
CONVERT(datetime, LEFT('2017-04-17 16:55:53.3840460', 23), 121) AS date1,
CONVERT(datetime, 'Sep 18 2015 11:25PM', 100) AS date2;
Your first type of timestamp seems to work with mask 121, and the second one works with mask 100. The demo link below shows that the conversions are working.
Demo

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;

finding data lying between a specific date range in sql

I want to find records from my database which lie between any user input date range(say between 10/2/2008 to 26/9/2024). I tried using
SELECT NAME
,TYPE
,COMP_NAME
,BATCH_NO
,SHELF
,MFG_DATE
,EXP_DATE
,QTY
,VAT
,MRP
FROM STOCK_LOCAL
WHERE
convert(VARCHAR(20), EXP_DATE, 103)
BETWEEN convert(VARCHAR(20), #MEDICINEEXP_DATE, 103)
AND convert(VARCHAR(20), #MEDICINEEXPDATE, 103)
but with this query i need to enter perfect date range which is available in my database, it is not giving me data lying in between any date entered.
Thanks in advance
Since it is a poolr designed schema there isnt going to be any decent/Efficient solution for this.
In sql server if you are storing Date or Date & Time data. Use the Data or DATETIME datatypes for your columns.
In your case you are trying to compare a string with passed date. and even when you tried to convert the string (Date) into date datatype you didnt do it correctly.
My suggestion would be Add new columns to your table with Date datatype and update these columns with existing date/string values.
For now you can convert the Date(string) into date datatype using the following code.
DECLARE #MEDICINEEXP_DATE DATE = 'SomeValue1'
DECLARE #MEDICINEEXPDATE DATE = 'SomeValue1'
SELECT query....
FROM TableName
WHERE
CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) >= #MEDICINEEXP_DATE
AND CAST(
RIGHT(EXP_DATE, 4)
+SUBSTRING(EXP_DATE,CHARINDEX('/',EXP_DATE)+1,2)
+LEFT(EXP_DATE,2)
AS DATE) <= #MEDICINEEXPDATE
Note
This solution will get you the expected results but very inefficient method. It will not make use of any indexses on your EXP_DATE Column even if you have a very buffed up index on that column.