943,724 Members | Top Members by Rank

Ad:
  • C# Discussion Thread
  • Unsolved
  • Views: 12703
  • C# RSS
Mar 26th, 2008
0

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

Expand Post »
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!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
Ratte is offline Offline
38 posts
since Oct 2007
Mar 27th, 2008
0

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

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

C# Syntax (Toggle Plain Text)
  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
Reputation Points: 69
Solved Threads: 75
Posting Pro in Training
JerryShaw is offline Offline
465 posts
since Nov 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C# Forum Timeline: identify current user asp.net c# project
Next Thread in C# Forum Timeline: AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap()





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC