检查SQL Server中是否存在表
我希望这是关于如何使用 SQL 语句检查 SQL Server 2000/2005 中表是否存在的最终讨论。
这里有两种可能的方法。 哪一种是标准/最佳方法?
第一种方式:
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
第二种方式:
IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
MySQL提供了简单的
SHOW TABLES LIKE '%tablename%';
语句。 我正在寻找类似的东西。
I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.
Here are two possible ways of doing it. Which one is the standard/best way of doing it?
First way:
IF EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='mytablename')
SELECT 1 AS res ELSE SELECT 0 AS res;
Second way:
IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL
SELECT 1 AS res ELSE SELECT 0 AS res;
MySQL provides the simple
SHOW TABLES LIKE '%tablename%';
statement. I am looking for something similar.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
为什么大多数用户说“if *** is not null”!?尝试“if *** is null”:)
why most of user say 'if *** is not null' !?, try 'if *** is null' :)
如果您只想返回 true 或 false 如果 SQL Server 中存在或不存在
您可以使用以下查询,只需将 tableName 替换为您的表名称
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='表名')
选择 1 AS 资源 ELSE 选择 0 AS 资源;
if you want just to return true or false if exists or not in the SQL server
you can use the following query just replace tableName with your table Name
IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'
AND TABLE_NAME='tableName')
SELECT 1 AS res ELSE SELECT 0 AS res;
运行此查询来检查数据库中是否存在该表:
Run this query to check if the table exists in the database:
在SQL Server 2000中,您可以尝试:
In SQL Server 2000 you can try:
对于此类查询,最好使用
INFORMATION_SCHEMA
视图。 这些视图(大部分)是许多不同数据库的标准,并且很少随着版本的不同而改变。要检查表是否存在,请使用:
For queries like this it is always best to use an
INFORMATION_SCHEMA
view. These views are (mostly) standard across many different databases and rarely change from version to version.To check if a table exists use:
另请注意,如果出于任何原因您需要检查临时表,您可以执行以下操作:
Also note that if for any reason you need to check for a temporary table you can do this:
从我记事起,我们就一直使用
OBJECT_ID
样式We always use the
OBJECT_ID
style for as long as I remember请参阅以下方法,
方法 1:使用 INFORMATION_SCHEMA.TABLES 视图
我们可以编写如下查询来检查当前数据库中是否存在 Customers 表。
方法 2:使用 OBJECT_ID() 函数
我们可以使用如下所示的 OBJECT_ID() 函数来检查当前数据库中是否存在 Customers 表。
方法 3:使用 sys.Objects 目录视图
我们可以使用 Sys.Objects 目录视图来检查 Table 是否存在,如下所示:
方法 4:使用 sys.Tables 目录视图
我们可以使用Sys.Tables目录视图来检查表是否存在,如下所示:
方法5:避免使用sys.sysobjects系统表
我们应该避免直接使用sys.sysobjects系统表,在 Sql Server 的某些未来版本中将不再推荐直接访问它。 根据 Microsoft BOL 链接,Microsoft 建议直接使用目录视图 sys.objects/sys.tables 而不是 sys.sysobjects 系统表。
引用自: http ://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/
Please see the below approaches,
Approach 1: Using INFORMATION_SCHEMA.TABLES view
We can write a query like below to check if a Customers Table exists in the current database.
Approach 2: Using OBJECT_ID() function
We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.
Approach 3: Using sys.Objects Catalog View
We can use the Sys.Objects catalog view to check the existence of the Table as shown below:
Approach 4: Using sys.Tables Catalog View
We can use the Sys.Tables catalog view to check the existence of the Table as shown below:
Approach 5: Avoid Using sys.sysobjects System table
We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.
referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/
在不同的数据库中查找表:
Looking for a table on a different database:
只是想提一下一种情况,使用 OBJECT_ID 方法可能会更容易一些。
INFORMATION_SCHEMA
视图是每个数据库下的对象 -https://msdn.microsoft.com/en-us/library/ms186778.aspx
因此,您访问的所有表
将仅反映
[database]
中的内容。 如果您想检查另一个数据库中的表是否存在,而不需要每次动态更改[database]
,OBJECT_ID
将让您做到这一点盒子的。 Ex-一样
与SQL SERVER 2016 Edit
:从 2016 年开始,Microsoft 通过添加
if isn't
简化了在删除之前检查不存在的对象的功能drop
语句的关键字。 例如,将在 1 行代码中执行与
OBJECT_ID
/INFORMATION_SCHEMA
包装器相同的操作。https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/
Just wanted to mention one situation where it would probably be a little easier to use the
OBJECT_ID
method. TheINFORMATION_SCHEMA
views are objects under each database-https://msdn.microsoft.com/en-us/library/ms186778.aspx
Therefore all tables you access using
will only reflect what is in
[database]
. If you wanted to check if tables in another database exist, without dynamically changing the[database]
each time,OBJECT_ID
will let you do this out of the box. Ex-works just as well as
SQL SERVER 2016 Edit:
Starting with 2016, Microsoft simplified the ability to check for non-existent objects prior to dropping, by adding the
if exists
keywords todrop
statements. For example,will do the same thing as
OBJECT_ID
/INFORMATION_SCHEMA
wrappers, in 1 line of code.https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/
您可以使用下面的代码
或者
You can use below code
Or
使用信息模式是执行此操作的 SQL 标准方法,因此所有支持它的数据库都应该使用它。 请参阅此答案中的方法 1。
Using the Information Schema is the SQL Standard way to do it, so it should be used by all databases that support it. See Approach 1 in this answer.
在上面的代码中,表名称为
Mapping_APCToFNavigator
。Here in the above code, the table name is
Mapping_APCToFANavigator
.如果您需要使用不同的数据库:
If you need to work on different databases:
我知道这是一个老问题,但如果您打算经常调用它,我发现了这种可能性。
I know it is an old question but I have found this possibility if you plan to call it often.
只是为了开发人员和其他 DBA 的利益而在此处添加
一个脚本,该脚本接收 @Tablename 作为参数
(可能包含也可能不包含 schemaname),并在 schema.table 存在时返回以下信息:
我生成了要使用的脚本每次我需要测试表或视图是否存在时,在其他脚本中,当存在时,获取其 object_id 以用于其他目的。
当您传递空字符串、错误的架构名称或错误的表名称时,它会引发错误。
例如,这可以在过程内部并返回 -1。
例如,我的一个数据仓库数据库中有一个名为“Facts.FactBackOrder”的表。
这就是我实现这一目标的方法:
Just adding here, for the benefit of developers and fellow DBAs
a script that receives @Tablename as a parameter
(which may or may not contain the schemaname) and returns the info below if the schema.table exists:
I produced this script to be used inside other scripts every time I need to test whether or not a table or view exists, and when it does, get its object_id to be used for other purposes.
It raises an error when either you passed an empty string, wrong schema name or wrong table name.
this could be inside a procedure and return -1 for example.
As an example, I have a table called "Facts.FactBackOrder" in one of my Data Warehouse databases.
This is how I achieved this:
如果这是“最终”讨论,那么应该注意的是,如果服务器已链接,Larry Leonard 的脚本也可以查询远程服务器。
If this is to be the 'ultimate' discussion, then it should be noted that Larry Leonard's script can query a remote server as well if the servers are linked.
我认为以下查询有效:
I think the following query works:
我在选择 INFORMATIONAL_SCHEME 和 OBJECT_ID 时遇到了一些问题。 我不知道这是 ODBC 驱动程序的问题还是其他问题。来自 SQL Management Studio 的查询都没有问题。
解决方案如下:
因此,如果查询失败,则数据库中可能不存在这样的表(或者您没有访问它的权限)。
检查是通过比较处理 ODBC 驱动程序的 SQL 执行器返回的值(在我的例子中为整数)来完成的。
I've had some problems either with selecting from INFORMATIONAL_SCHEME and OBJECT_ID. I don't know if it's an issue of ODBC driver or something.. Queries from SQL management studio, both, were okay.
Here is the solution:
So, if the query fails, there is, probably, no such table in the database (or you don't have access permissions to it).
The check is done by comparing the value (integer in my case) returned by SQL executor which deals with ODBC driver..
你可以使用这个:
You can use this :
还有一个选项可以检查该表是否跨数据库存在
There is one more option to check if the table exists across databases
如果有人尝试在 linq to sql (或者特别是 linqpad)中执行相同的操作,请打开包含系统表和视图的选项并执行以下代码:
假设您有一个对象,其名称位于名为 item 的属性中,并且架构在名为 schema 的属性中,其中源变量名称为
a
If anyone is trying to do this same thing in linq to sql (or especially linqpad) turn on option to include system tables and views and do this code:
given that you have an object with the name in a property called item, and the schema in a property called schema where the source variable name is
a
对于尚未找到解决方案的人来说,需要了解一些重要信息:
SQL 服务器!= MYSQL。
如果您想使用 MYSQL 进行此操作,
则将其发布到此处非常简单,因为它是 Google 的热门搜索。
Something important to know for anybody who hasn't found their solution yet:
SQL server != MYSQL.
If you want to do it with MYSQL, it is quite simple
Posting this here because it's the top hit at Google.
-- -- 创建过程来检查表是否存在
-- -- 如何使用:检查表迁移是否存在
-- -- create procedure to check if a table exists
-- -- how to use : check if table migrations exists
我在这里以创建视图为例。
因为 ALTER/CREATE 命令不能位于 BEGIN/END 块内。 您需要测试是否存在并在创建之前删除它。
如果您担心权限丢失,您也可以编写 GRANT 语句脚本并在最后重新运行这些语句。
您可以将创建/更改包装到字符串中并执行 EXEC - 对于大视图来说这可能会变得难看
i taking here creating a view as example.
Because ALTER/CREATE commands can't be within BEGIN/END blocks. You need to test for existence and the drop it before doing a create
If you are woried about the permissions being lost you can script the GRANT statements as well and re-run those at the end.
You could wrap the create/alter into a string and do an EXEC - that might get ugly for large views