Cast/Convert nvarchar to datetime(2) - sql

Since I described it poorly last time, again
i have table:
id time_stamp
1 12.01.20 15:34:34,000000000 EUROPE/PRAGUE
2 10.01.20 10:15:15,000000000 EUROPE/PRAGUE
3 09.01.20 05:55:42,000000000 EUROPE/PRAGUE
Table have huge amount these data. Column timestamp is data type "nvarchar". And i need to sort datas by date or use in clauses WHERE for constraint by date, so i need to convert "timestamp" to datetime. But I can't. I tried convert and cast but still failed.
From #Larnu i got advice, but didnt work, because I'm stupid and inaccurately described the problem.
UPDATE dbo.YourTable
SET [timestamp] = CONVERT(nvarchar(20),TRY_CONVERT(datetime2(0), [timestamp], 104), 126);
Now you can ALTER the table and change the data type to a datetime2(0):
ALTER TABLE dbo.YourTable ALTER COLUMN [timestamp] datetime2(0) NULL;
any advice on how to change with respect to the time_stamp column.
Thx.

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

How to convert two types of dates format into one date format in 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

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]);

Compare columns with time datatype in SQL

I have table with column with time Datatype.I want to compare the time in SQL.The main problem is when i compare any time with '00:00:00'/'00:10:00'.
For e.g. select timings from train where trn_time > '19:00:00'.
then in output i want '00:00:00' also wic I am not getting.
And I dont want to use 'Datetime' data type.
Please help.
i created a table in mysql with name 'table11'
CREATE TABLE `table11` (
`id` INT(10) NULL DEFAULT NULL,
`time_col` TIME NULL DEFAULT NULL
)
and inserted data as follows
and when i used following query
select * from table11 tbl where tbl.time_col< '19:00:00'
i got result
if you use tbl.time_col< '19:00:00' then only you will get '00:00:00' in the output.
i think in your case its better to use 'Datetime' datatype

store date only, not the the time in datetime field

This is a trivial question, I added a field
Alter table MyTbl add datecreated smalldatetime default CONVERT(varchar(10),GetDate(),101)
When I go check the new field, it shows not only the date but also time. I check the table definition (right click on table -> Modify in SSMS) and it does say the default value as GETDATE() [it discarded the convert(...) by default]. Why is this so. Is there a way to give a default date only to datetime field and not the time.
I ended up leaving the time field as it is because it is better to see what is going on in the table esp in initial test phase.
I just tried your ALTER statement, and it works as you expect; when I enter a row without including datecreated, it sets the value to the date with a time of 00:00:00.
The fact that you checked the table definition and it says the default is GETDATE() leads me to believe the column already existed and your ALTER failed.
this will reset the time section to zero
DateAdd(day, DateDiff(day, 0, PayDate), 0)
Just because you are converting the datetime returned from getdate() to a varchar(10), there is another implicit cast from varchar(10) to datetime, as it is the datatype for your field.
You need to have the datecreated field datatype a varchar(10).
Your alter table statement should be:
Alter table MyTbl add datecreated varchar(10) default CONVERT(varchar(10),GetDate(),101)