Convert datatype of existing data from Char to DateTime with SQL - sql

I am relatively new to SQL Server and I am trying to update the datatype of about 3000 records from a Char to Datetime so I can use the DATEDIFF function. I created a view that achieves the conversion but what I think I need to do is alter the data in the origin table.
SELECT
CONVERT(datetime, CONVERT(char(8), TRANS_ACCOUNTINGDATE_ALLCAMPAIGNS_2010_ALLPROCESSINGACCOUNTS_ALL))
FROM Accounting;
What I think I need to do is an alter table and iterate over each row performing the conversion. Trying to change the data type using the GUI is not working for me.
Any help would be appreciated.
Thanks

The datatype is an attribute of the COLUMN, not just of the data inside the column. You can't put datetime data into a char field - that's the purpose of data types!
You need to add a new field and run an UPDATE statement to populate it with your converted data. Then you can drop the original field and rename your new one to the original name.

Related

SQL convert varchar into Date

A long time ago I created a database, and completely forgot to set the column to Date and now looking at the data, I want to extract, it looks like 2006-05-06.
How would I run a SQL statement to convert it into the correct format (dd/MM/yyyy) 06/05/2006, I'm running with the British format "103".
What I was planning on doing, I've already added a second column (s_batch_convert2) to the database, hoping to convert into that and then delete the original column (s_batch_convert), renaming the new column to the old one.
UPDATE s_service_repairs
SET s_batch_convert2 = TRY_CONVERT(Date, s_batch_convert, 103)
Am I along the right lines?
You should convert your existing column to a bona fide date. It seems to have the right format:
alter table s_service_repairs alter column s_batch_convert date;
Then you can add a computed column for the format you want:
alter table s_service_repairs s_batch_convert_mmddyyyy as ( try_convert(varchar(10), s_batch_convert, 103) );

HashBytes with datetime2 field

I am creating a hash key using hashbytes on multiple columns to get performance gain which we are using right now in where clause.
alter table dbo.Table1
add HashKey AS CAST(hashbytes('MD5', PID+PNumber+CONVERT([varchar] (50),[DateStamp]) +CONVERT(VARCHAR(50), TransactionCount)+OCD+ONbr+TransactionID) AS VARBINARY(80)) PERSISTED
But one of the column in that is a datetime2 field which i am unable to add. While i was trying i am getting below error message
"Computed column 'HashKey' in table 'table1' cannot be persisted because the column is non-deterministic.".
From my research i found that datetime2 cannot be used as it is non-deterministic.
But i cannot change the format as i need to compare the value exactly as it is including all milliseconds.
Can anybody please give me a work around?.Any alternate solution will be appreciated.
I am not sure of implications..
But casting datetime to binary always gives new value.see below for Example..
select getdate(),cast(getdate()as binary)
2016-08-02 10:17:20.573 0x000000000000000000000000000000000000000000000000A65600A98EEC
2016-08-02 10:17:40.537 0x000000000000000000000000000000000000000000000000A65600A9A651
so try like..
select hashbytes('md5',cast(getdate()as binary))

How to sort by varchar field containing a date in ascending order [duplicate]

This question already has answers here:
Comparing dates stored as varchar
(3 answers)
Closed 3 years ago.
In design time we have given [DOJInGovrService] field as varchar datatype.
now when we are trying order by this parameter(DOJInGovrService) in ascending order it is not giving the desired result.
I know it is datatype problem but I can't change the datatype now as data is already entered.
SELECT ED.class,
ED.CurrentOfficePlace,
ED.DOB,
ED.DOJInCurrentOff,
ED.DOJInGovrService,
ED.DOJInSamvarg,
ED.EmpName,
ED.HomePlace, ED.Qualification
FROM tbl_EmplyeesBiodata ED
ORDER BY DOJInGovrService asc
Date entered is in format dd-MM-yyyy (i.e. 28-08-2004).
please help me
This is just one of many reasons why you should Always use appropriate data types.
Even when you have data in the table, you can change the data type using an alter table ddl statement:
ALTER TABLE tableName
ALTER COLUMN ColumnName datetime2;
However, you should copy this table first and try the alter on the copy, so that if it messes up your data you will not risk anything.
If the alter is successful then do it on your live table. if not, you can go with a different approach, involving these stages:
rename the DOJInGovrService column to DOJInGovrService_old. use sp_RENAME.
Add a column DOJInGovrService with the correct datatype (datetime2), using alter table ddl stement.
Update the new DOJInGovrService column with the values in DOJInGovrService_old. you will probably need to use convert.
drop the DOJInGovrService_old column using the alter table ddl statement.
Try to convert it to datetime
select ED.class,ED.CurrentOfficePlace,ED.DOB,ED.DOJInCurrentOff,ED.DOJInGovrService,ED.DOJInSamvarg,ED.EmpName,ED.HomePlace,ED.Qualification
from tbl_EmplyeesBiodata ED
order by convert(date,DOJInGovrService,105) asc
This is only direct solution. The best way to do that is create new column with date type. The column will helps you to create query without cast or convert.

Modifying a column type with data, without deleting the data

I have a column which I believe has been declared wrongly. It contains data and I do not wish to lose the data.
I wish to change the definition from varchar(max) to varchar(an integer). I was under the impression I cannot just alter the column type?
Is the best method to create a temp column, "column2", transfer the data to this column, from the column with the problematic type, delete the problem column and then rename the temp column to the original problematic column?
If so, how do I copy the values from the problem column to the new column?
EDIT: For anyone with same problem, you can just use the ALTER statements.
As long as the data types are somewhat "related" - yes, you can absolutely do this.
You can change an INT to a BIGINT - the value range of the second type is larger, so you're not in danger of "losing" any data.
You can change a VARCHAR(50) to a VARCHAR(200) - again, types are compatible, size is getting bigger - no risk of truncating anything.
Basically, you just need
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumn VARCHAR(200) NULL
or whatever. As long as you don't have any string longer than those 200 characters, you'll be fine. Not sure what happens if you did have longer strings - either the conversion will fail with an error, or it will go ahead and tell you that some data might have been truncated. So I suggest you first try this on a copy of your data :-)
It gets a bit trickier if you need to change a VARCHAR to an INT or something like that - obviously, if you have column values that don't "fit" into the new type, the conversion will fail. But even using a separate "temporary" new column won't fix this - you need to deal with those "non-compatible" cases somehow (ignore them, leave NULL in there, set them to a default value - something).
Also, switching between VARCHAR and NVARCHAR can get tricky if you have e.g. non-Western European characters - you might lose certain entries upon conversion, since they can't be represented in the other format, or the "default" conversion from one type to the other doesn't work as expected.
Calculate the max data length store int that column of that table.
Select max(len(fieldname)) from tablename
Now you can decrease the size of that column up to result got in previous query.
ALTER TABLE dbo.YourTable
ALTER COLUMN YourColumn VARCHAR(200) NULL
According to the PostgreSQL docs, you can simply alter table
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
But here's the thing
This will succeed only if each existing entry in the column can be converted to the new type by an implicit cast. If a more complex conversion is needed, you can add a USING clause that specifies how to compute the new values from the old.
add a temp column2 with type varchar(NN), run update tbl set column2 = column, check if any error happens; if everything is fine, alter your original column, copy data back and remove column2.

Convert a string to a date in Access

I'm migrating data between tables in Access 2003. In the old table, the date was stored as a text field in the format YYYYMMDD.
I want to store the field as a datetime in the new table. I've tried using CDate() in my SQL statement, but it just displays as #Error in the results.
What am I doing wrong?
e.g. cdate(format("20091231", "####/##/##"))
So, in your case it will be
SELECT cdate(format(mystringFieldThatIsInYYYYMMDDFormat, "####/##/##"))
FROM myData