سؤال

I know it isn't recommended to create a table using an execute immediate command but I need to create a table which prompts the user for 2 pieces of information before acting. Currently I have:

DECLARE
TEST_NAME VARCHAR2(200);  
TEST_VERSION VARCHAR2(200); 
BEGIN
  TEST_NAME := '&1';
  TEST_VERSION := '&2';

EXECUTE IMMEDIATE 'create table TEST_TABLE
(
PROJ_NAME VARCHAR(255) DEFAULT TEST_NAME,
PROJ_VER VARCHAR(255) DEFAULT TEST_VERSION,
COL_1 NUMBER(5)
)';
End;

This throws the error

Error report:
ORA-00984: column not allowed here
ORA-06512: at line 8
00984. 00000 -  "column not allowed here"
*Cause:    
*Action:

How can I solve this issue? Also as a second question, if I were to be successful in creating this table, in a different script, how would I use an if statement to compare a variable against the default value of the proj_name column, (test_name)?

EDIT: Thanks to tbone and Parado I solved my first issue though if anyone could help with know how to use an if statement to do something like this:

If test_var = proj_name.default_value ...

I need to be able to compare against the default proj_name value even when no rows have been inserted. Thanks,

هل كانت مفيدة؟

المحلول

Try this way:

DECLARE
TEST_NAME VARCHAR2(200);  
TEST_VERSION VARCHAR2(200); 
BEGIN
  TEST_NAME := '&1';
  TEST_VERSION := '&2';

EXECUTE IMMEDIATE 'create table TEST_TABLE
(
PROJ_NAME VARCHAR(255) DEFAULT '''||TEST_NAME||''',
PROJ_VER VARCHAR(255) DEFAULT  '''||TEST_VERSION||''',
COL_1 NUMBER(5)
)';
End;

نصائح أخرى

You can do something like this:

set serveroutput on

declare
  l_var1 varchar2(100) := 'SOME_VALUE';
  l_sql  varchar2(4000);
begin
  l_sql := 'create table test_tab(
  col1 varchar2(100) default ''' || l_var1 || '''
  )';

  -- show the ddl used
  dbms_output.put_line(l_sql);

  -- create the table
  execute immediate l_sql;

end;

Here I'm hardcoding l_var1 to 'SOME_VALUE', but you can use the same approach with a parameter or user variable.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top