Checking fro Table existince in SQL2005

R

Robert Bravery

HI all,

I want check for the existence of a particular table in sql. Then branch
code on the result
I was thinking of a command something like:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[tempimport]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
But dont know how to get a return value to my C# app so that I can make
decisions in my code

Thanks
Robert
 
W

warlord

Robert Bravery said:
HI all,

I want check for the existence of a particular table in sql. Then branch
code on the result
I was thinking of a command something like:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[tempimport]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
But dont know how to get a return value to my C# app so that I can make
decisions in my code

Just use what you have without the IF EXISTS something like

sql.CommantText = "SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[tempimport]')AND OBJECTPROPERTY(id, N'IsUserTable') = 1";
int a = sql.ExecuteNonQuery();

Then "a" should be 1 or more :)
 
S

Sericinus hunter

Robert said:
HI all,

I want check for the existence of a particular table in sql. Then branch
code on the result
I was thinking of a command something like:
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[tempimport]')
AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
But dont know how to get a return value to my C# app so that I can make
decisions in my code

Better use information_schema view. Something like this (SQL syntax tested):

sqlCommand.CommandText = @"SELECT
CASE
WHEN EXISTS (SELECT 1 FROM information_schema.tables
WHERE table_type = 'base table' AND table_name = 'tempimport')
THEN 1
ELSE 0
END;";

bool itExists = (1 == (int)sqlCommand.ExecuteScalar());
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top