IF COL_LENGTH('EMP_NUM','EMPLOYEE') 不为空 - 在 ORACLE 中等价

IF COL_LENGTH('EMP_NUM','EMPLOYEE') IS NOT NULL - EQUIVALENT IN ORACLE

我在 SQL 服务器中使用以下脚本来更改列以允许 nullnot null

Oracle 11g 或更高版本中的等效语法是什么?

IF COL_LENGTH('EMP_NUM','EMPLOYEE') IS NOT NULL
   ALTER TABLE EMPLOYEEALTER COLUMN EMP_NUMnumeric(10,0) NOT NULL;

在 Oracle 中,您必须使用动态 SQL,因为您无法在 PL/SQL 中按原样执行 DDL。为什么 PL/SQL?因为IF-THEN-ELSEPL/SQL,不是SQL.

假设这是您的 PL/SQL 程序的一部分,那么您会

if col_length('EMP_NUM', 'EMPLOYEE') is not null then
  execute immediate 'alter table employee modify emp_num not null';
end if;

那是 ALTER 部分。但是,由于 Oracle 没有 COL_LENGTH 函数(据我所知也没有类似的功能),您必须自己做。这是一个例子:

一个 table 其列允许空值:

SQL> create table employee (emp_num number);

Table created.

检查 Null? 列 - 空,所以是的 - 它允许空值。

SQL> desc employee;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMP_NUM                                            NUMBER

查询数据字典以查找列的长度:

SQL> select data_length from user_tab_columns
  2  where table_name = 'EMPLOYEE'
  3    and column_name = 'EMP_NUM';

DATA_LENGTH
-----------
         22

最后,你以后的PL/SQL程序:

SQL> declare
  2    l_len number;
  3  begin
  4    select data_length
  5      into l_len
  6      from user_tab_columns
  7      where table_name = 'EMPLOYEE'
  8        and column_name = 'EMP_NUM';
  9
 10    if l_len is not null then
 11       execute immediate 'alter table employee modify emp_num not null';
 12    end if;
 13  end;
 14  /

PL/SQL procedure successfully completed.

SQL> desc employee;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMP_NUM                                   NOT NULL NUMBER

SQL>

如您所见,Null? 列现在包含 NOT NULL,这意味着 ALTER TABLE 已成功执行。


此外,您甚至可以创建自己的函数来查询列的数据长度,然后在您的过程中使用它:

SQL> create or replace function col_length(par_table in varchar2, par_column in varchar2)
  2    return number
  3  is
  4    retval user_tab_columns.data_length%type;
  5  begin
  6    select data_length
  7      into retval
  8      from user_tab_columns
  9      where table_name = par_table
 10        and column_name = par_column;
 11    return retval;
 12  end;
 13  /

Function created.

SQL> select col_length('EMPLOYEE', 'EMP_NUM') from dual;

COL_LENGTH('EMPLOYEE','EMP_NUM')
--------------------------------
                              22

SQL>

最后:

SQL> drop table employee;

Table dropped.

SQL> create table employee (emp_num number);

Table created.

SQL> begin
  2    if col_length('EMPLOYEE', 'EMP_NUM') is not null then
  3       execute immediate 'alter table employee modify emp_num not null';
  4    end if;
  5  end;
  6  /

PL/SQL procedure successfully completed.

SQL> desc employee;
 Name                                      Null?    Type
 ----------------------------------------- -------- ----------------------------
 EMP_NUM                                   NOT NULL NUMBER

SQL>