简体   繁体   English

如何在C#中检查数据库中是否存在表(ACCESS或SQL)

[英]how can i check whether a table exists in the database (ACCESS or SQL) in C#

I found a lot of questions regarding with this question. 我发现了很多关于这个问题的问题。

But is there any simple statements to accomplish this task? 但有没有简单的陈述来完成这项任务?

for both SQL and ACCESS 适用于SQL和ACCESS

IF (EXISTS (SELECT 1 FROM sys.tables WHERE name = 'table_name'))
BEGIN
    -- do stuff
END

sys.tables can also give you some information about the table object, eg the is_replicated column tells you if the table was created by replication or the has_replication_filter column tells you if the table has a replication filter set up sys.tables还可以为您提供有关表对象的一些信息,例如, is_replicated列会告诉您表是由复制创建的,还是has_replication_filter列告诉您表是否已设置复制过滤器

NB: this is for SQL Server 注意:这是针对SQL Server的

Edit: For Access: 编辑:访问:

SELECT COUNT(*) as Exists from MsysObjects 
WHERE type = 1
AND name = 'MY_TABLE_NAME' 

Note that there is no standardized way to do this in SQL, you will have to write plattform-specific code. 请注意,在SQL中没有标准化的方法,您必须编写特定于平台的代码。

To my knowledge, all DBMS have this functionality in one way or another, but it differs greatly, eg in Oracle you can query the sys.all_tables view. 据我所知,所有DBMS都以这种或那种方式具有此功能,但它有很大不同,例如在Oracle中,您可以查询sys.all_tables视图。

You can also do using OBJECT_ID. 您也可以使用OBJECT_ID。

IF OBJECT_ID('table1') IS NOT NULL
print 'Exists' 
else
print 'Not Exists' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM