简体   繁体   English

转换和更改 Oracle 表列

[英]Converting and altering Oracle table columns

I need help for specific question.我需要特定问题的帮助。

I need to write some Oracle Database procedure, which will do next:我需要编写一些 Oracle 数据库过程,接下来将执行:

  • Receiving a table name as a parameter;接收表名作为参数;
  • Taking all fields with numeric value (number/bignumber/numeric/etc.) excepting primary key;取除主键外的所有带有数值的字段(数字/大数字/数字/等);
  • Convert these columns to to DATE format;将这些列转换为 DATE 格式;
  • Add these new formatted columns to this table (I mean an ALTER TABLE ADD COLUMN).将这些新的格式化列添加到这个表中(我的意思是一个 ALTER TABLE ADD COLUMN)。

How can I do this?我怎样才能做到这一点?

As all comments below post said it is not possible to convert any number to date.正如帖子下面的所有评论所说,不可能将任何数字转换为日期。 You need to know what is format of number.您需要知道什么是数字格式。 Below is example procedure to add columns and convert all numbers but it is based on condition that numbers store dates in format ddmmyyyy for example 12102014 will give date 12-Oct-2014 but if number have date in other format it will throw an exception.下面是添加列和转换所有数字的示例过程,但它基于数字以 ddmmyyyy 格式存储日期的条件,例如 12102014 将给出日期 12-Oct-2014,但如果数字具有其他格式的日期,它将引发异常。

create or replace procedure columns_change(t_name in varchar2) as
col varchar2(30);
begin
for x in (select column_name from all_tab_columns where table_name = t_name and data_type in ('NUMBER'/*add whatever you need*/)) loop
col := x.column_name;
if (length(col)> 29) then --that's to avoid extending name to more than 30 characters
col := substr(col,1,29);
end if;
execute immediate 'alter table ' || t_name || ' add d' || col || ' date';
execute immediate 'update ' || t_name || ' set ' || col || ' = to_date(' || x.column_name || ',''ddmmyyyy'')';
end loop;
end;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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