Check if a database and tables exist in sql server in a vb .net project

You can query SQL Server to check for the existence of objects.

To check for database existence you can use this query:

SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase'

To check for table existence you can use this query against your target database:

SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U'

This below link shows you how to check for database existence is SQL Server using VB.NET code:

Check if SQL Database Exists on a Server with vb.net

Referenced code from above link:

Public Shared Function CheckDatabaseExists(ByVal server As String, _
                                           ByVal database As String) As Boolean
    Dim connString As String = ("Data Source=" _
                + (server + ";Initial Catalog=master;Integrated Security=True;"))

    Dim cmdText As String = _
       ("select * from master.dbo.sysdatabases where name=\’" + (database + "\’"))

    Dim bRet As Boolean = false

    Using sqlConnection As SqlConnection = New SqlConnection(connString)
        sqlConnection.Open
        Using sqlCmd As SqlCommand = New SqlCommand(cmdText, sqlConnection)
            Using reader As SqlDataReader = sqlCmd.ExecuteReader
                bRet = reader.HasRows
            End Using
        End Using
    End Using

    Return bRet

End Function

You could perform the check in another way, so it's done in a single call by using an  EXISTS  check for both the database and a table:

IF NOT EXISTS (SELECT * FROM master.dbo.sysdatabases WHERE name = 'YourDatabase')
BEGIN
    -- Database creation SQL goes here and is only called if it doesn't exist
END

-- You know at this point the database exists, so check if table exists

IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'YourTable' AND type = 'U')
BEGIN
    -- Table creation SQL goes here and is only called if it doesn't exist
END

By calling the above code once with parameters for database and table name, you will know that both exist.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值