根据条件修改表

时间:2019-09-05 12:11:49

标签: sql oracle

我有以下查询试图在oracle上执行:-

基于条件是否需要更改表

IF (COL_LENGTH('AAXC_CUSTFORM_ATTR','API_NAME')=500)
BEGIN
alter table AAXC_CUSTFORM_ATTR alter column API_NAME varchar(1000);
END

我正面临以下问题:-

从命令第1行开始出错:

IF (COL_LENGTH('AAXC_CUSTFORM_ATTR','API_NAME')=500)
Error report:
Unknown Command

Error starting at line 2 in command:
BEGIN
alter table AAXC_CUSTFORM_ATTR alter column API_NAME varchar(1000);
END
Error report:
ORA-06550: line 2, column 1:
PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:

   ( begin case declare exit for goto if loop mod null pragma
   raise return select update while with <an identifier>
   <a double-quoted delimited-identifier> <a bind variable> <<
   continue close current delete fetch lock insert open rollback
   savepoint set sql execute commit forall merge pipe purge
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action

4 个答案:

答案 0 :(得分:1)

语法是:

alter table AAXC_CUSTFORM_ATTR modify API_NAME varchar(1000);

答案 1 :(得分:1)

您可以使用以下匿名块:

DECLARE
    V_LENGTH   USER_TAB_COLUMNS.DATA_LENGTH%TYPE;
BEGIN
    BEGIN
        SELECT
            DATA_LENGTH
        INTO V_LENGTH
        FROM
            USER_TAB_COLUMNS
        WHERE
            TABLE_NAME = 'AAXC_CUSTFORM_ATTR'
            AND COLUMN_NAME = 'API_NAME';

    EXCEPTION
        WHEN OTHERS THEN
            V_LENGTH := 0;
    END;

    IF V_LENGTH = 500 THEN
        EXECUTE IMMEDIATE 'alter table AAXC_CUSTFORM_ATTR MODIFY API_NAME varchar(1000)';
    END IF;
END;

干杯!

答案 2 :(得分:0)

DECLARE
len   NUMBER;
BEGIN
SELECT MAX(length(desc1) ) INTO
    len
FROM temp;
dbms_output.put_line(len);
IF
    ( len = 3 )
THEN
    EXECUTE IMMEDIATE 'Alter table temp modify desc1 varchar2(100)';
END IF;
END;

答案 3 :(得分:0)

类似这样的东西:

declare
  actualLength Number;

  myLength constant Number = 1000;
  myTable constant VarChar2(4000) := 'AAXC_CUSTFORM_ATTR';
  myColumn constant VarChar2(4000) := 'API_NAME';
begin    
  select Max(Data_Length) -- Max: in case you have several owners
    into actualLength
    from All_Tab_Cols
   where Table_Name = Upper(myTable) 
      -- you may want to add more filters, e.g. Owner
     and Column_Name = Upper(myColumn);

  -- I suggest actualLength < myLength - what if actualLength = 80, not 500?
  if (actualLength < myLength) then
    -- You can't execute Alter as it is but via execute immediate
    execute immediate 'alter table ' || myTable || ' alter column ' || myColumn || ' varchar(' || To_Char(myLength) || ')';
  end if; 
end;