|
-
Jul 18th, 2008, 01:25 AM
#1
Thread Starter
Addicted Member
check if SQL table exists
Hello,
I am implemeting a window application in vb.net using Visual Studio 2005, how can i check if SQL table is created in SQL server from my application cuz i want to disable that button if the sql table is created and enable that button if that table doesnt exist in order to create it.
Thank you
Hiba
-
Jul 18th, 2008, 01:39 AM
#2
Hyperactive Member
Re: check if SQL table exists
MCP, MCTS, Microsoft MVP [Asp.Net/IIS]
For more .NET development tips visit .NET Tips
If the post is useful then please  Rate it
-
Jul 18th, 2008, 04:45 AM
#3
Thread Starter
Addicted Member
Re: check if SQL table exists
Hello,
How can I use this statment :
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') AND type in (N'U'))
in Vb.net code?
Thanx
-
Jul 18th, 2008, 08:03 AM
#4
Re: check if SQL table exists
vb.net Code:
Option Strict On Option Explicit On Imports System.Data.SqlClient Public Class MyForm Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim conn As New SqlConnection() 'Creates a new connection object Dim cmd As New SqlCommand() 'Creates a new command object Dim exists As Byte = 0 'Creates a byte variable that will store the cmd return value conn.ConnectionString = "Data Source=MyServer; " & _ "Initial Catalog=MyDatabase; " & _ "User Id=MyUserId; " & _ "Password=MyPassword" cmd.CommandText = "SELECT COUNT(*) " & _ "FROM sys.objects " & _ "WHERE object_id = OBJECT_ID(N'[dbo].[TableName]') " & _ "AND type in (N'U')" Try conn.Open() 'Opens the connection cmd.Connection = conn 'Instructs the cmd object to use conn as its connection when executing exists = CByte(cmd.ExecuteScalar()) 'Use ExecuteScalar to return a single value, the count, and assign it to the exists variable conn.Close() Catch ex As SqlException MessageBox.Show(ex.Message) 'Catch any SqlException and display it in a MessageBox Catch ex As Exception MessageBox.Show(ex.Message) 'Catch any ApplicationException and display it in a MessageBox End Try MyButton.Enabled = CBool(exists) 'Convert the exists variable to a boolean to determine whether the button should be enabled. 'Note that by assigning the exists variable a value of 0 earlier, if there is an error in connecting to the database, the value will 'remain 0, and the button will be disabled by default. End Sub End Class
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|