简体   繁体   中英

How do I check if a temporary table exists in SQL Anywhere?

我想编写一个SQL IF语句来检查是否存在本地临时表,但这些表不会记录在SQL Anywhere系统目录中。

请注意,您可以在11.0.1及更高版本中执行此操作:

DROP TABLE IF EXISTS t;

If you're asking the question, "How do I drop a local temporary table without raising an error if it doesn't exist?" then the answer's simple: just DROP it and ignore any error:

BEGIN
   DROP TABLE t;
   EXCEPTION WHEN OTHERS THEN
END;

If you really need to know the answer to the question "Does table t exist?" you can query the table and analyze the resulting SQLSTATE. The following function makes use of several features:

  • ON EXCEPTION RESUME ignores any exception raised by the SELECT and passes control to the IF statement.

  • EXECUTE IMMEDIATE lets you write a query where the table name is in a string variable.

  • TOP 1 makes sure that only one row is selected even if the table contains a million rows.

  • ORDER BY 1 lets you meet the requirement that TOP can only be used when the result set is ordered.

  • SELECT 1 relieves you of the burden of specifying a column name.

  • INTO @dummy means the SELECT (and consequently the EXECUTE IMMEDIATE) doesn't return a result set.

If the SELECT works, it's either going to set SQLSTATE to '00000' for success or '02000' for row not found. Any other SQLSTATE means there's some serious problem with the table... like it doesn't exist.

CREATE FUNCTION f_table_is_ok
   ( IN @table_name VARCHAR ( 128 ) )
   RETURNS INTEGER
   ON EXCEPTION RESUME
BEGIN
   DECLARE @dummy INTEGER;
   EXECUTE IMMEDIATE STRING (
      'SELECT TOP 1 1 INTO @dummy FROM ',
      @table_name,
      ' ORDER BY 1' );
   IF SQLSTATE IN ( '00000', '02000' ) THEN
      RETURN 1
   ELSE
      RETURN 0
   END IF;
END;

Here's some test code:

BEGIN
DECLARE LOCAL TEMPORARY TABLE tt ( c INTEGER );
DECLARE LOCAL TEMPORARY TABLE "t t" ( c INTEGER );
SELECT f_table_is_ok ( 'asdf' );
SELECT f_table_is_ok ( 'tt' );
SELECT f_table_is_ok ( '"t t"' );
SELECT f_table_is_ok ( '"SYS"."SYSTABLE"' );
END; 

just try to drop it anyways and ignore the error...

BEGIN
DROP TABLE table;
EXCEPTION WHEN OTHERS THEN

END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM