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

Please support our C# advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2007
Posts: 35
Reputation: Ratte is an unknown quantity at this point 
Solved Threads: 0
Ratte's Avatar
Ratte Ratte is offline Offline
Light Poster

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

 
0
  #1
Mar 26th, 2008
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!
Reply With Quote Quick reply to this message  
Join Date: Nov 2006
Posts: 436
Reputation: JerryShaw is on a distinguished road 
Solved Threads: 72
JerryShaw JerryShaw is offline Offline
Posting Pro in Training

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

 
0
  #2
Mar 27th, 2008
A better approach is to see if it exists through sysObjects, and create it there, catch any errors on that.

  1. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Country_Master]') AND type in (N'U'))
  2.  
  3. CREATE TABLE [dbo].[Country_Master](
  4. [County_id] [int] IDENTITY(1,1) NOT NULL,
  5. [CountryName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
  6. )

Then in c# run an Execute non query. Place that into a try catch
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC