Icon View Thread

The following is the text of the current message along with any replies.
Messages 1 to 2 of 2 total
Thread ColumnExists function
Tue, Jun 24 2008 4:46 PMPermanent Link

"David Cornelius"
Use this in a script to tell if a column exists in a table or not:

CREATE FUNCTION "ColumnExists" (IN "TableName" VARCHAR(40) COLLATE ANSI, IN
"ColumnName" VARCHAR(40) COLLATE ANSI)
RETURNS BOOLEAN
BEGIN
 DECLARE ColCursor CURSOR FOR ColStmt;
 DECLARE ColName VARCHAR;

 PREPARE ColStmt FROM
   ''SELECT * FROM Information.TableColumns
    WHERE Name = '''''' + ColumnName + '''''' AND
      TableName = '''''' + TableName + '''''''';

 OPEN ColCursor;
 FETCH FIRST FROM ColCursor (Name) INTO ColName;
 CLOSE ColCursor;
 UNPREPARE ColStmt;

 RETURN COALESCE(ColName, '''') = ColumnName;
END

--
David Cornelius
CorneliusConcepts.com
Tue, Jun 24 2008 4:47 PMPermanent Link

"David Cornelius"
Example use in a script:

SCRIPT
BEGIN
 IF NOT ColumnExists('Notes', 'test') then
   EXECUTE IMMEDIATE 'ALTER TABLE "Notes"
     ADD COLUMN "test" INTEGER';
 END IF;
                       
 IF ColumnExists('Notes', 'test') then
   EXECUTE IMMEDIATE 'ALTER TABLE "Notes"
     DROP COLUMN "test"';
 END IF;
END

--
David Cornelius
CorneliusConcepts.com
Image