如何检查表是否存在

[英]How to check table exist or not exist


How to check table is there or not?

如何检查表是否存在?

Using VB 6.0

使用VB 6.0

cmd.CommandText = "drop table t1"
cmd.Execute

Above code is working fine, but if table is not exist then it showing “table does not exit”

上面的代码工作正常,但如果表不存在那么它显示“表不退出”

How to check table exist or table not exist?

如何检查表存在或表不存在?

Need VB CODE help?

需要VB CODE帮助吗?

3 个解决方案

#1


2  

For a Jet MDB (and perhaps generically for many OLEDB Providers) you can use an approach like:

对于Jet MDB(也许通常用于许多OLEDB提供商),您可以使用以下方法:

Private Sub Main()
    Dim cnDB As ADODB.Connection

    Set cnDB = New ADODB.Connection
    cnDB.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
            & "Jet OLEDB:Engine Type=5;Data Source='sample.mdb'"

    'Check presence of table --------------
    Dim rsSchema As ADODB.Recordset

    Set rsSchema = _
        cnDB.OpenSchema(adSchemaColumns, _
                        Array(Empty, Empty, "t1", Empty))
    If rsSchema.BOF And rsSchema.EOF Then
        MsgBox "Table does not exist"
    Else
        MsgBox "Table exists"
    End If
    rsSchema.Close
    Set rsSchema = Nothing
    '--------------------------------------

    cnDB.Close
End Sub

#2


4  

If you just want to drop the table without throwing an error message, you can use the following SQL if you're using MySQL.

如果您只想删除表而不抛出错误消息,则可以使用以下SQL,如果您使用的是MySQL。

DROP TABLE t1 IF EXISTS

Other databases have a similar feature, but the syntax is different. To do the same in MSSQL:

其他数据库具有类似的功能,但语法不同。要在MSSQL中执行相同的操作:

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 't1') DROP TABLE t1;

Although that looks very ugly.. there must be a better syntax to get the same result.

虽然看起来很丑陋......但必须有更好的语法来获得相同的结果。

#3


1  

You'd be better off checking for existance of the table concerned, rather than trying to drop it.

你最好检查相关表的存在,而不是试图放弃它。

The SQL syntax is dependent on the database server/engine you're using, but for Sql Server you could use something like:

SQL语法依赖于您正在使用的数据库服务器/引擎,但对于Sql Server,您可以使用以下内容:

Sql Server 2000:

Sql Server 2000:

SELECT 1 as Exists FROM sysobjects WHERE name = 't1'

Sql Server 2005/2008:

Sql Server 2005/2008:

SELECT 1 as Exists FROM sys.objects WHERE name = 't1'

You can then use VB like:

然后你可以使用VB:

Dim rs as Recordset
Dim iExists as Integer

rs = cmd.Execute
On Error Goto DoesNotExist
rs.MoveFirst
iExists = CInt(rs!Exists)
DoesNotExist:
If iExists = 1 Then
 ' Put code here for if the table exists
Else
 ' Put code here for if the table does not exist
End If

Note: This code needs tidying up and "productionising" =) (i.e. I haven't actually tested that it works as I don't have VB6 on this machine)

注意:此代码需要整理和“生产”=)(即我实际上没有测试它是否有效,因为我在这台机器上没有VB6)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2009/06/30/dfe451d98befd02f25772a4076c80b8b.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号