简体   繁体   中英

How to update data types in SQL from a returned list

I made a database and realized made a mistake where whole bunch of tables have nvarchar(255) data types in them. They were supposed to be datetime. I am trying to modify all of them by running a simple code.

First I ran the below code to identify all the tables and the relevant column names which have the word "date" in them as I know these are the columns who's data types needs to be changed:

select * 
from MyDatabase.INFORMATION_SCHEMA.COLUMNS c 
where c.COLUMN_NAME like '%date%'

I looked at the list and confirmed none of the columns have any data in them. Only some of them have NULL in them. Which I can delete those data if needed. Also only 3 in the returned list are not Null able; the rest are Null able. I can modify the not Nullable ones manually if its going to matter.

I was thinking like running a code like:

select * 
from MyDatabase.INFORMATION_SCHEMA.COLUMNS c 
where c.COLUMN_NAME like '%date%' and c.IS_NULLABLE = 'yes'

ALTER COLUMN c.COLUMN_NAME LIKE '%date%' DATETIME [NULL] -- for the Nullable items

With above code I was trying to use the logic from the below link: How do you change the datatype of a column in SQL Server?

Nevertheless, I know my above implementation is incorrect. Could anyone help me with the proper way? Thanks in advance

In mysql you could this. You can achieve the same results in other sql database services, just the syntax may be different.

select CONCAT('ALTER TABLE ', c.TABLE_NAME, ' MODIFY COLUMN ', c.COLUMN_NAME, ' 
DATETIME;') 
from INFORMATION_SCHEMA.COLUMNS c 
where c.COLUMN_NAME like '%date%' and c.TABLE_SCHEMA='database_name'

Basically you're retrieving all the columns with the word date and then using the CONCAT function to build alter queries. Then you just need to run the resulting queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM