1

我正在尝试编写一个 SQL 语句来检查表是否存在,如果存在,则将其放入 System i 中。

我以为这将是一个简单的IF EXISTS陈述,但我遇到了麻烦并且不确定如何继续。

声明全文:

IF EXISTS (SELECT TABLE_NAME FROM <<DatabaseName>>.VIEWS         
WHERE TABLE_NAME = 'TABLE')         
DROP VIEW <<DatabaseName>>.TABLE
GO

它返回错误

没有预期的关键字 IF

我是 System i 的完整初学者,但我读过有关程序可以解决这个问题?

4

1 回答 1

2

You can use an IF statement inside a stored procedure, so you could accomplish this with something like:

CREATE PROCEDURE CREATE_TABLE (
    IN IN_TABLE_NAME VARCHAR(128), 
    IN IN_TABLE_SCHEMA VARCHAR(128),
    IN IN_TABLE_DEF VARCHAR(4000))

    LANGUAGE SQL MODIFIES SQL DATA

    DECLARE CNT INT DEFAULT 0;
    DECLARE STMT VARCHAR(1000);
    SELECT COUNT(*) INTO CNT
      FROM QSYS2/SYSTABLES
      WHERE TABLE_NAME = IN_TABLE_NAME and TABLE_SCHEMA = IN_TABLE_SCHEMA

    CASE CNT
        WHEN 1 THEN
            SET TABLE_NAME = 'CORPDATA.DEPT_' CONCAT P_DEPT CONCAT '_T';
            SET STMT = 'DROP TABLE ' || IN_TABLE_SCHEMA || '/' || IN_TABLE_NAME;
            PREPARE S1 FROM STMT;
            EXECUTE S1;
    END CASE

    SET STMT = 'CREATE TABLE ' || IN_TABLE_SCHEMA || '/' || IN_TABLE_NAME || 
                IN_TABLE_DEF;
    PREPARE S1 FROM STMT;
    EXECUTE S1;

You could then call this proc passing in the table name, schema, and column definition:

CALL CREATE_TABLE('MYTABLE', 'MYSCHEMA', '(
    COL1 INTEGER NOT NULL, 
    COL2 VARCHAR(100))';

I haven't actually tested this, but this should give you a basic idea of what you need to do.

于 2012-12-07T21:49:56.693 回答