954,148 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to check if table exists, if not create it (exceptions)...

I need my program to connect to a database, check if a table exists, and if not, create it.

I intend to check the presence of a table by simply running a "select * from table" query via an SqlCommand. I am going to put this in a try block. My problem is, how/where do I actually create the table? In the catch block? What if the SqlException was not due to the table not existing, but for instance due to an incorrect password? What is the best way to do this?

Thanks!

Ratte
Light Poster
38 posts since Oct 2007
Reputation Points: 10
Solved Threads: 0
 

A better approach is to see if it exists through sysObjects, and create it there, catch any errors on that.

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Country_Master]') AND type in (N'U'))

CREATE TABLE [dbo].[Country_Master](
	[County_id] [int] IDENTITY(1,1) NOT NULL,
	[CountryName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)


Then in c# run an Execute non query. Place that into a try catch

JerryShaw
Posting Pro in Training
465 posts since Nov 2006
Reputation Points: 69
Solved Threads: 75
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You