Oracle 参数化查找 table 的列数 - ORA-00905: 缺少关键字
Oracle parameterize finding column count of a table - ORA-00905: missing keyword
我正在向多个 table 添加多个列。在添加它们之前,我想确保它们不存在。
SELECT count(*)
INTO myCount
FROM user_tab_cols
WHERE column_name = 'newCol'
and table_name = 'tableName';
由于唯一的变量是tableName
和columnName
,我想到了将这两个变量参数化以期重用它。所以我写了一个pl/sql:
DECLARE
myCount NUMBER;
COUNT_COLUMN VARCHAR2(1000) :=
' SELECT count(*)
INTO myCount
FROM user_tab_cols
WHERE column_name = :1
and table_name = :2';
BEGIN
EXECUTE IMMEDIATE COUNT_COLUMN using 'columnName','tableName';
/*code to check count and add column*/
DBMS_OUTPUT.PUT_LINE(myCount);
EXCEPTION
WHEN
OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'sql failed: ' || SQLCODE || ': ' || SUBSTR(SQLERRM, 1, 200));
END;
我希望 myCount
变量包含 table 中的列数。但是我收到以下错误。
sql failed: -905: ORA-00905: missing keyword
如何摆脱这个错误?我还有什么其他方法可以实现这一目标?
INTO 子句不得包含在 SQL 查询中,但要在 EXECUTE IMMEDIATE 语句中使用。所以,你需要修复你的动态 SQL 如下 -
DECLARE
myCount NUMBER;
COUNT_COLUMN VARCHAR2(1000) :=
' SELECT count(*)
FROM user_tab_cols
WHERE column_name = :1
and table_name = :2';
BEGIN -- Add the BEGIN keyword to complete a PL/SQL block
EXECUTE IMMEDIATE COUNT_COLUMN INTO myCount using 'columnName','tableName';
/*code to check count and add column*/
DBMS_OUTPUT.PUT_LINE(myCount);
EXCEPTION
WHEN
OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'sql failed: ' || SQLCODE || ': ' || SUBSTR(SQLERRM, 1, 200));
END;
我正在向多个 table 添加多个列。在添加它们之前,我想确保它们不存在。
SELECT count(*)
INTO myCount
FROM user_tab_cols
WHERE column_name = 'newCol'
and table_name = 'tableName';
由于唯一的变量是tableName
和columnName
,我想到了将这两个变量参数化以期重用它。所以我写了一个pl/sql:
DECLARE
myCount NUMBER;
COUNT_COLUMN VARCHAR2(1000) :=
' SELECT count(*)
INTO myCount
FROM user_tab_cols
WHERE column_name = :1
and table_name = :2';
BEGIN
EXECUTE IMMEDIATE COUNT_COLUMN using 'columnName','tableName';
/*code to check count and add column*/
DBMS_OUTPUT.PUT_LINE(myCount);
EXCEPTION
WHEN
OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'sql failed: ' || SQLCODE || ': ' || SUBSTR(SQLERRM, 1, 200));
END;
我希望 myCount
变量包含 table 中的列数。但是我收到以下错误。
sql failed: -905: ORA-00905: missing keyword
如何摆脱这个错误?我还有什么其他方法可以实现这一目标?
INTO 子句不得包含在 SQL 查询中,但要在 EXECUTE IMMEDIATE 语句中使用。所以,你需要修复你的动态 SQL 如下 -
DECLARE
myCount NUMBER;
COUNT_COLUMN VARCHAR2(1000) :=
' SELECT count(*)
FROM user_tab_cols
WHERE column_name = :1
and table_name = :2';
BEGIN -- Add the BEGIN keyword to complete a PL/SQL block
EXECUTE IMMEDIATE COUNT_COLUMN INTO myCount using 'columnName','tableName';
/*code to check count and add column*/
DBMS_OUTPUT.PUT_LINE(myCount);
EXCEPTION
WHEN
OTHERS THEN
DBMS_OUTPUT.PUT_LINE( 'sql failed: ' || SQLCODE || ': ' || SUBSTR(SQLERRM, 1, 200));
END;