Wednesday, March 28, 2012

How can I check if table already exists in a DB?

How can I check if table already exists in a DB?
Today I just create my table at startup, if it exist I get a error telling
me that the table already exist, ignoring the error message.
But this is a dirty way of doing it. Any other idea.
It must be quick and clean.Hi !
quote:

> How can I check if table already exists in a DB?

If you generate sql script for table and check "generate drop object" on ,
you will see in generated scipt something like this :
if exists (select * from dbo.sysobjects where id = object_id(N'[accounts]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [accounts]
where 'accounts' is my tablename.
You can use this approach or , using odbc API , try to get table metadata,
i'm sure it should be way to get it, just never tried it.
Regards,Alexander|||use SQLTables function
"GTi" <nospam@.online.com> wrote in message
news:PUsQb.1148$O41.64225@.amstwist00...
quote:

> How can I check if table already exists in a DB?
> Today I just create my table at startup, if it exist I get a error telling
> me that the table already exist, ignoring the error message.
> But this is a dirty way of doing it. Any other idea.
> It must be quick and clean.
>
|||Or try this:
USE [YourDB]
IF EXISTS (
SELECT name
FROM sysobjects
WHERE type = 'u' AND
name = N'YourTable' -- Remove N if not using unicode
)
BEGIN
-- Do action
END
Regards,
Johan
"Furer Alexander" <alex_f@.sentry-com.co.il> wrote in message
news:OLebgPN6DHA.1636@.TK2MSFTNGP12.phx.gbl...
use SQLTables function
"GTi" <nospam@.online.com> wrote in message
news:PUsQb.1148$O41.64225@.amstwist00...
quote:

> How can I check if table already exists in a DB?
> Today I just create my table at startup, if it exist I get a error telling
> me that the table already exist, ignoring the error message.
> But this is a dirty way of doing it. Any other idea.
> It must be quick and clean.
|||Thanks to you all...
"GTi" <nospam@.online.com> wrote in message
news:PUsQb.1148$O41.64225@.amstwist00...
quote:

> How can I check if table already exists in a DB?
> Today I just create my table at startup, if it exist I get a error telling
> me that the table already exist, ignoring the error message.
> But this is a dirty way of doing it. Any other idea.
> It must be quick and clean.
>
|||IF OBJECTPROPERTY ( object_id('authors'),'ISTABLE') = 1
print 'Authors is a table'
"GTi" <nospam@.online.com> wrote in message
news:PUsQb.1148$O41.64225@.amstwist00...
quote:

> How can I check if table already exists in a DB?
> Today I just create my table at startup, if it exist I get a error telling
> me that the table already exist, ignoring the error message.
> But this is a dirty way of doing it. Any other idea.
> It must be quick and clean.
>

No comments:

Post a Comment