Click to See Complete Forum and Search --> : sql query to create table if not exist


pran_chorge
June 27th, 2008, 02:22 AM
syntax & example for sql query to create table if not exist in ms access database
Thanks in advance

GremlinSA
June 27th, 2008, 06:23 AM
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Table]') AND type in (N'U'))
CREATE TABLE [dbo].[Table](
[Act_Id] [int] IDENTITY(1,1) NOT NULL,
[Activity] [text] NOT NULL ,
[Date] [datetime] NOT NULL ,
[User_ID] [nvarchar](20) NOT NULL ,
CONSTRAINT [PK_TABLE] PRIMARY KEY CLUSTERED
(
[Act_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

pran_chorge
June 27th, 2008, 06:57 AM
u have replied code in php . I need it in ms access. I am using front end as vb.net & back end as ms access. So please send it that i can use in ms access.
Thanks in advance

PeejAvery
June 27th, 2008, 09:35 AM
The code posted is basic SQL. It will work for Access. It's not even remotely close to PHP, although he used [php] tags to post it.

jp2code
July 14th, 2009, 01:13 PM
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Table]') AND type in (N'U'))
CREATE TABLE [dbo].[Table](
{snip}
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


Hey GremlinSA,

What do the functions *_ID*, *N*, and *type* do? Could you explain a little about what's going on?

Thanks,
Joe

monalin
July 14th, 2009, 03:15 PM
What do the functions *_ID*, *N*, and *type* do? Could you explain a little about what's going on?

Its a little easier to see whats going on if you run the query yourself and look at the results. Forget the WHERE clause he put in there and just run


USE [DatabaseName];
SELECT * FROM sys.objects;


You should see that this table holds a list of all the objects in the database consisting of Tables, Primary Keys, Foreign Keys, and other constraints. Each object has an ID associated with it.

The *N* prefix to the string just allows the string to contain Unicode characters.

The OBJECT_ID( ) just returns the corresponding id in the sys.objects table for the table you're looking for.

Lastly the *type* isn't really a function its just another column in the database. In this situation N'U' just tells the query you're only interested in tables. You can add in the other types if you wish to the search but for this situation all you're interested in are the tables. Oh, and 'U' stands for USER_TABLE.