Unix Technical Forum

New to DB2: Create table if exists? How?

This is a discussion on New to DB2: Create table if exists? How? within the DB2 forums, part of the Database Server Software category; --> Hi all, I'm new in using DB2 and I have question on creating/ altering table. I created a file ...


Go Back   Unix Technical Forum > Database Server Software > DB2

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 02-27-2008, 02:06 PM
vincenthkh@gmail.com
 
Posts: n/a
Default New to DB2: Create table if exists? How?

Hi all,

I'm new in using DB2 and I have question on creating/ altering table.

I created a file (DDL) with SQL statements, then the database
administrator (my client) to create or alter the table automatically
by running the command "db2 -tvf <filename>".

However, now, I would like to create the table if it doesn't exist. Or
Alter the table if it exists.

I found some posts mentioned the statement of:
IF NOT EXISTS (SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME="MYTABLE")
THEN
CREATE TABLE MYTABLE (......)
END IF

I tried to add such statements in the file, but it failed.

So, how can I do this?

Please help & thanks.
Vincent Ho

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 02-27-2008, 02:06 PM
Knut Stolze
 
Posts: n/a
Default Re: New to DB2: Create table if exists? How?

vincenthkh@gmail.com wrote:

> Hi all,
>
> I'm new in using DB2 and I have question on creating/ altering table.
>
> I created a file (DDL) with SQL statements, then the database
> administrator (my client) to create or alter the table automatically
> by running the command "db2 -tvf <filename>".
>
> However, now, I would like to create the table if it doesn't exist. Or
> Alter the table if it exists.
>
> I found some posts mentioned the statement of:
> IF NOT EXISTS (SELECT NAME FROM SYSIBM.SYSTABLES WHERE NAME="MYTABLE")


SQL uses single-quotes to delimit strings: NAME = 'MYTABLE'

> THEN
> CREATE TABLE MYTABLE (......)


You have to use dynamic SQL for that, i.e. create a string that contains the
CREATE TABLE statement, then use EXECUTE IMMEDIATE to execute the statement
in that string.

> END IF


--
Knut Stolze
DB2 z/OS Utilities Development
IBM Germany
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 07:33 PM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0
www.UnixAdminTalk.com