SQL Server : change date format - sql

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)

Related

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;

Convert date to varchar in SQL Server

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.

Converting string 'yyyy-mm-dd' to date

I want to select from table where date column is equal to specific date which I sending as a string in format 'yyyy-mm-dd'. I need to convert that string and than to compare if I have that date in my table.
For now I am doing this:
select *
FROM table
where CONVERT(char(10), date_column,126) = convert(char(10), '2016-10-28', 126)
date_column is a date type in table and I need to get it from table in this format 'yyyy-mm-dd' and because that I use 126 format. I am just not sure with the other part where I converting string which is already in that format and do I need to convert it because I don't know is it good to use this:
CONVERT(varchar(10), date_column,126) = '2016-10-28'
You don't need to convert the column as well. In fact, you better not convert the column, because using functions on columns prevents sql server from using any indexes that might help the query plan on that column.
Also, you are converting a string to char(10) - better just convert it to date:
where date_column = convert(date, '2016-10-28', 126)
Also, if you are using a datetime data type and not date, you need to check that the datetime value is between the date you pass to the next date.
You can convert string to date as follows using the CONVERT() function by giving a specific format of the input parameter
declare #date date
set #date = CONVERT(date, '2016-10-28', 126)
select #date
You can find the possible format parameter values for SQL Convert date function here
You do not need to do that. yyyy-MM-dd is the default format.
Please note that you need to take into account the time as well, if there's a timestamp in date_column. In that case you should write something like this
... WHERE date_column >= '2016-10-28 00:00:00' AND date_column < '2016-10-29 00:00:00'
... WHERE date_column BETWEEN '2016-10-28 00:00:00' and '2016-10-29 00:00:00'
As I just learned that (other than I thought) BETWEEN actually includes the end timestamp and thus is not equivalent to the above >= ... < approach.
This should use indexes properly as well.

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.

Wrong type in datetime column SQL Server

I have an application in asp. I insert data into SQL Server into a column of datetime type.
Let me give you an example for my question:
when I have the date 10/02/2012 and I insert it into SQL Server I see the data like this:
2012-10-02
but I would like to have it like this: 2012-02-10
When I have the date 29/02/2012 and I insert it into SQL Server I see the data in the correct format : 2012-02-29.
How can I manage the correct type I want?
The collation of database and table is Greek_CI_AS , in my language
any ideas how to fix it?
There are a few possibilities, but they all relate to the date format settings of the system components your strings are passing through (i.e. both the ASP runtime and your SQL Server).
There is a date format setting in SQL Server http://msdn.microsoft.com/en-us/library/ms189491.aspx
In ASP, the parsing of strings in VBScript depends upon the settings in effect during the parse - basically, http://support.microsoft.com/kb/306044
You can use CONVERT() to control the date format and you can specify a smaller target string to crop the result:
SELECT CONVERT(NVARCHAR(10), GETDATE(), 21) -- YYYY-MM-DD
SELECT CONVERT(NVARCHAR(10), GETDATE(), 102) -- YYYY.MM.DD
SELECT CONVERT(NVARCHAR(10), GETDATE(), 105) -- DD-MM-YYYY
SELECT CONVERT(NVARCHAR(10), GETDATE(), 110) -- MM-DD-YYYY
SELECT CONVERT(NVARCHAR(5), GETDATE(), 105) -- DD-MM
SELECT CONVERT(NVARCHAR(5), GETDATE(), 110) -- MM-DD
SELECT CONVERT(NVARCHAR(4), GETDATE(), 102) -- YYYY
-- To get YYYY-DD-MM, put two of the above together:
SELECT CONVERT(NVARCHAR(4), GETDATE(), 102)
+ '-' + CONVERT(NVARCHAR(5), GETDATE(), 105)
To force a date format for insertion, you can do a similar thing:
-- Insert in Italian dd-mm-yy (e.g. 10th February 2012)
INSERT INTO user_table VALUES (CONVERT(DATETIME, '10-02-12', 5));
-- Insert in USA mm-dd-yy (2nd October 2012)
INSERT INTO user_table VALUES (CONVERT(DATETIME, '10-02-12', 10));
See Microsoft MSDN reference CAST and CONVERT (Transact-SQL).
---- ANSWER TO ADDITIONAL QUESTION ----
I find your latest comment a little ambiguous. If you're asking how to search on a datetime field between two dates that you have in string format, then, try something like this:
SELECT *
FROM user_table
WHERE mydate BETWEEN convert(Datetime,'20/02/2012',103)
AND convert(Datetime,'01/03/2012')
whereas, if you are trying to search on an nvarchar field with two dates in string format, then, try something like this:
SELECT *
FROM user_table
WHERE convert(Datetime, mynvarchar, 103)
BETWEEN convert(Datetime,'20/02/2012',103)
AND convert(Datetime,'01/03/2012')
However, this is terribly inefficient. If you are going to be doing date searches a lot, I highly recommend storing your date field in datetime format. If you have a business requirement to store the nvarchar version, that's okay, but you can use dynamic columns, such as:
CREATE TABLE user_table
(
mynvarchar NVARCHAR(10), -- Date as a String in DD/MM/YYYY format
mydatetime AS CONVERT(DATETIME, mynvarchar, 103) PERSISTED
);
The advantage of this is the mydatetime field automatically updates itself and can be used in indexes and constraints if you wanted it to, but, you can manage it by manipulating the mynvarchar business columns.
In future, can I please request that when you ask question, that you provide more concrete examples, i.e. the name of your table, the name of your columns, so I don't have to keep inventing these.