How to convert two types of dates format into one date format in SQL? - sql

I have three table in the database two of them contain dates however the dates are in two format, first 20-02-2011 and second is 25/09/2018. Let say each table have 10000 records and mixed with these two types of dates format. This why I why I create the column like --- (Transaction_Date, Varchar(10) Not Null)
I tried convert (Varchar(10),Transaction_Date,105)
and also tried replace(convert(varchar(10),Transaction_Date,105),'/','-')
However date and year functions are still not working.
Please suggest a possible way.

How about this?
select replace(date, replace(Transaction_Date, '/', '-'), 105)
That is: (1) convert to a date and (2) replace the slash before converting.

You need to remember about your culture. Saved format vs server culture. But this is very possible
select Cast('2-22-2011' as datetime) f1,
Cast('2/22/2011' as datetime) f2
I other words just use Cast
select cast(Transaction_Date as datetime) . . .
But you should as soon as possible get rid of columns that saves date as string and create new date/time column, and insert your date values there
alter table tbl add column temp datetime
update tbl set temp = Cast(Transaction_Date as datetime)
alter table tbl drop column Transaction_Date
alter table tbl add column Transaction_Date datetime
update tbl set Transaction_Date = temp
alter table tbl drop column temp

Related

SQL Server - Looking for a way to shorten code

I'm basically very new to SQL Server, so please bare with me. Here is my problem:
I have a table with (let's say) 10 columns and 80k rows. I have 1 column called Date in the format of YYYY-MM-DD type varchar(50) (can't convert it to date or datetime type I tried, the initial source of data is not good).
**Example :
Table [dbo].[TestDates]
Code
SellDate
XS4158
2019-11-26
DE7845
2020-02-06
What I need to do is to turn the YYYY-MM-DD format to DD/MM/YYYY format. After a lot of tries (I tried the functions (DATE_FORMAT, CONVERT, TO_DATE etc) and this is solution :
1- I added a primary key for join purpose later (ID)
2- I split my date column in 3 columns in a whole new table
3- I merged the 3 columns in the order I need with the delimiter of my choice (/) in the same new table
4- I copied the good column to my initial table using the primary key ID I created before
alter table [dbo].[TestDates]
add ID int not null IDENTITY primary key;
SELECT ID,
FORMAT(DATEPART(month, [SellDate]),'00') AS Month,
FORMAT(DATEPART(day, [SellDate]),'00') AS Day,
FORMAT(DATEPART(year, [SellDate]),'0000') AS Year
INTO [dbo].[TestDates_SPLIT]
FROM [dbo].[TestDates]
GO
ALTER TABLE [dbo].[TestDates_SPLIT]
ADD SellDate_OK varchar(50)
UPDATE [dbo].[TestDates_SPLIT]
SET SellDate_OK = [Day] + '/' + [Month] + '/' + [Year]
ALTER TABLE [dbo].[TestDates_SPLIT]
DROP COLUMN Month, Day, Year
ALTER TABLE [dbo].[TestDates]
ADD SellDate_GOOD varchar(50)
UPDATE [dbo].[TestDates]
SET [TestDates].SellDate_GOOD = [TestDates_SPLIT].SellDate_OK
FROM [dbo].[TestDates]
INNER JOIN [dbo].[TestDates_SPLIT]
ON [TestDates].ID = [TestDates_SPLIT].ID
This code works but i find too heavy and long, considering I have 6 more dates columns to work on. Is there a way to make it shorter or more efficient? Maybe with SET SellDate = SELECT (some query of sorts that doesn't require to create and delete table)
Thank you for your help
I tried the usual SQL functions but since my column is a varchar type, the converting was impossible
You should not be storing dates as text. But, that being said, we can try doing a rountrip conversion from text YYYY-MM-DD to date to text DD/MM/YYYY:
WITH cte AS (
SELECT '2022-11-08' AS dt
)
SELECT dt, -- 2022-11-08
CONVERT(varchar(10), CONVERT(datetime, dt, 121), 103) -- 08/11/2022
FROM cte;
Demo

Add a column and populate it with the queried values from another column

I have a column having dates in varchar format, I want to convert it, to date format, which I did through below query:
select to_date(EVENT_DT, 'YYYYMMDD') from demographic;
Now, I want to create a new column and populate the column with the values that I got from above query. I am not able to do it with alter table.
Any solutions?
Hope it works as #Mike Walton said
Alter table demographic add Converted_date date;
----ms sql server
Update demographic set Converted_date = convert(date, EVENT_DT , 101);
---or using to_date
Update demographic set Converted_date = to_date(EVENT_DT, 'YYYYMMDD');

How to convert a string column into a date column

Imported a date column from a CSV file where there are string values are shown as
date
44705
44704
44703
I want to convert the entire column into a date format as
date
"2022-05-22"
"2022-05-21"
"2022-05-20"
I have used this script which allowed me to generate the result.
SELECT dateadd(d,44703,'1899-12-30') as date
The question is, how could I apply this script for a range of values (there are 700 rows in the table). e.g 44000 to 44705. I would like all string values to be converted as a date format.
select cast (44705-1 as smalldatetime) gives 2022-05-25 00:00
So you could just update the column using the above.
See https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=dc24abb3025e0f3796e7d978ba406be3
New fiddle with update statement, this line will update all rows, as per test.
update #test
set pdate = cast(dateadd(d,tdate-2,'1899-12-30') as smalldatetime)
To convert a string to date we can add temporary date column and fill it and delete old column and rename new one to old one
alter table TableName add NewColumnName date null; --create temporary column
update TableName set NewColumnName =dateadd(d,cast(cast([date] as float) as int)-2,'1899-12-30') --fill it
alter table TableName drop column [date]--delete old column
EXEC sp_RENAME 'TableName.NewColumnName' , 'date', 'COLUMN'--rename new one to old one

Display Now date and Time in SQl table column

I want to be able to have todays date and time now in a table column
If my table is say Table1, basically it should display the time and date when
SELECT * FROM Table1 is run.
I've tried the following but they just show the time from the moment in time I assign the value to column
ALTER TABLE Table1
ADD TodaysDate DateTime NOT NULL DEFAULT GETDATE()
and
ALTER TABLE Table1
ADD TodaysDate DateTime
UPDATE Table1
SET TodaysDate = GETDATE()
Hope this is clear. any help is appreciated.
Thanks
In SQL Server you can use a computed column:
alter table table1 add TodaysDate as (cast(getdate() as date));
(use just getdate() for the date and time)
This adds a "virtual" column that gets calculated every time it is referenced. The use of such a thing is unclear. Well, I could imagine that if you are exporting the data to a file or another application, then it could have some use for this to be built-in.
I hope this clarifies your requirement.
The SQL Server columns with default values stores the values inside the table. When you select the values from table, the stored date time will be displayed.
There are 2 options I see without adding the column to the table itself.
You can use SELECT *, GETDATE() as TodaysDate FROM Table1
You can create a view on top of Table 1 with additional column like
CREATE VIEW vw_Table1
AS
SELECT *, GETDATE() as TodaysDate FROM dbo.Table1
then you can query the view like you mentioned (without column list)
SELECT * FROM vw_Table1
This will give you the date and time from the moment of the execution of the query.

Computed Column Specification in SQL Server - Time Difference in hours or minutes

Is there a way to have a column in the table which auto-calculates the time difference between the start date and the end date as such?
(datediff(hour,[StartTime],[EndTime]))
ALTER TABLE yourTable
ADD yourColumn AS (datediff(hour,[StartTime],[EndTime]))
SQLFiddle DEMO
EDIT:
That was the syntax for alter table, off-course you can also define it during table creation
CREATE TABLE tbl1
(
startDate DATETIME,
enddate DATETIME,
diffCol AS (datediff(hour,startDate,enddate))
);
SSMS also have an option in table designer to add formula for computed columns
Assuming both StartTime and EndTime are columns on the same row of your table, you can use a computed column:
ALTER TABLE MyTable ADD TimeDiffHours AS DateDiff(hour,[StartTime],[EndTime]);