运行 使用 EXECUTE BLOCK 为唯一索引准备列的查询

run a query using EXECUTE BLOCK to prepair a column for an unique-Index

我在 table 中有一列要用于唯一索引。

我的脚本应该通过连接记录的 ID 使数据唯一, 如果当前记录的数据重复。

我知道我需要把它放在一个 EXECUTE BLOCK 中。

EXECUTE BLOCK 
AS 
    DECLARE VARIABLE ID BI;
    DECLARE VARIABLE REASON XTXT;
    DECLARE VARIABLE LAST_REASON XTXT = '';

BEGIN
FOR SELECT 
            ID_STATEMENT, 
            REASON 
    FROM 
            STATEMENT
    WHERE
            ID_STATEMENT > 0
    ORDER BY
            REASON ASC
    INTO    :ID, 
            :REASON
DO BEGIN
IF ( REASON = LAST_REASON ) THEN
    UPDATE
          STATEMENT
    SET 
          REASON = :REASON || ' X' || :ID
    WHERE
          ID_STATEMENT = :ID;
END
LAST_REASON = REASON;
END

但是我收到一条错误消息:

-104 Dynamic SQL Error SQL error code = -104 Token unknown - line 18, column 13

第18行开始into-part,第13列是:ID前面的':',

我在PHP下试了一下,驱动是PDO。

据我了解,您想使字段 REASON 唯一。在这种情况下很简单:

EXECUTE BLOCK 
AS 
    DECLARE VARIABLE ID BLOB;
    DECLARE VARIABLE REASON XTXT;

BEGIN
FOR SELECT 
            REASON || LIST(ID_STATEMENT, 'X'),
            REASON 
    FROM 
            STATEMENT
    WHERE
            ID_STATEMENT > 0
    GROUP BY
            REASON
    HAVING
            COUNT(*) > 1
    INTO    :ID, 
            :REASON
DO BEGIN
    DELETE FROM
          STATEMENT
    WHERE
          REASON = :REASON;
    INSERT INTO
          STATEMENT
    VALUES
          (:ID, :REASON);
END
END

在那之后,在 table 中,您将拥有具有唯一 REASON 和串联 ID 的记录。

我现在更进一步了。

冒号的语法问题已解决。

我一直收到错误消息的原因是冒号 在 INTO 行中是我使用的 PDO-driver 中的错误 在 PHP.

纯属巧合,在研究另一个课题时,我有 了解到此错误自 PHP 版本 5.6 以来就存在,至少 尚未被 7.3 版本淘汰。

这个“EXECUTE BLOCK”运行非常好:

EXECUTE BLOCK 
AS 
    DECLARE VARIABLE ID BI;
    DECLARE VARIABLE REASON XTXT;
    DECLARE VARIABLE LAST_REASON XTXT = '';
BEGIN
      FOR SELECT 
                  ID_STATEMENT, 
                  REASON 
          FROM 
                  STATEMENT
          WHERE
                  ID_STATEMENT > 0
          ORDER BY
                  REASON ASC
          INTO    :ID, 
                  :REASON
      DO 
        BEGIN
              IF (REASON = LAST_REASON) THEN BEGIN
                  UPDATE
                        STATEMENT
                  SET 
                        REASON = :REASON || ' X' || :ID
                  WHERE
                        ID_STATEMENT = :ID;
              END
              LAST_REASON = REASON;
        END
END

Driver: PHP 基间- / Firebird-Driver

重要的是 IF-Statement 中“THEN”之后的“BEGIN”!!!