alter table with dynamic sql [message #253943] |
Wed, 25 July 2007 06:16 |
gautamvv
Messages: 254 Registered: June 2005
|
Senior Member |
|
|
create table testcol(col1 number,col2 number);
i have prepared a piece of code that adds a new column to th is
DECLARE
l_sqlstmt VARCHAR2(32767);
l_COLUMN_NAME VARCHAR2(32767);
BEGIN
SELECT COLUMN_NAME into l_COLUMN_NAME from user_tab_cols
where COLUMN_NAME='newcol' and table_name='testcol';
exception
when no_data_found then
l_sqlstmt := 'ALTER TABLE testcol ADD(newcol DATE)';
dbms_output.put_line(l_sqlstmt);
EXECUTE IMMEDIATE l_sqlstmt;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
end;
i run it for first time, fine, but when i run it again
it says
SQL> desc testcol;
Name Null? Type
----------------------------------------- -------- ---------------------
COL1 NUMBER
COL2 NUMBER
SQL> @test;
22 /
ALTER TABLE testcol ADD(newcol DATE)
PL/SQL procedure successfully completed.
SQL> desc testcol;
Name Null? Type
----------------------------------------- -------- ---------------------
COL1 NUMBER
COL2 NUMBER
NEWCOL DATE
SQL> @test;
22 /
ALTER TABLE testcol ADD(newcol DATE)
DECLARE
*
ERROR at line 1:
ORA-01430: column being added already exists in table
ORA-06512: at line 15
ORA-01403: no data found
|
|
|
|
|
|
Re: alter table with dynamic sql [message #253951 is a reply to message #253947] |
Wed, 25 July 2007 06:27 |
pablolee
Messages: 2882 Registered: May 2007 Location: Scotland
|
Senior Member |
|
|
Well, for a start, column names and table names are stored in the data dictionary in uppercase (unless defined using double quotes)
Apart from that, you are performing the task in an extremely awkward way.
Excecute the sql statement and trap the error
air code:
declare
associate error -0143 with an error name
begin
execute immediate 'alter table statement'
exception
when that error then
error logging or error message
end;
|
|
|