Home > Database > Mysql Tutorial > body text

SQL 判断表是否已存在 【转】

WBOY
Release: 2016-06-07 15:14:49
Original
1558 people have browsed it

sqlserver中 判断 表 是否 存在 分类: 数据库开发技术 sqlserver中 判断 表 是否 存在 在sqlserver(应该说在目前所有数据库产品)中创建一个资源如表,视图,存储过程中都要 判断 与创建的资源 是否 已经 存在 在sqlserver中一般可通过查询sys.objects系统表

 sqlserver中判断是否存在 

分类: 数据库开发技术

sqlserver中判断是否存在
在sqlserver(应该说在目前所有数据库产品)中创建一个资源如表,视图,存储过程中都要判断与创建的资源是否已经存在
在sqlserver中一般可通过查询sys.objects系统表来得知结果,不过可以有更方便的方法

如下:

if   object_id('tb_table') is not null 
print 'exist' else print'not exist'      

如上,可用object_id()来快速达到相同的目的,tb_table就是我将要创建的资源的名称,所以要先判断当前数据库中不存在相同的资源

object_id()可接受两个参数,第一个如上所示,代表资源的名称,上面的就是表的名字,但往往我们要说明我们所要创建的是什么类型的资源,


这样sql可以明确地在一种类型的资源中查找是否有重复的名字,如下:

if   object_id('tb_table','u') is not null 
 print 'exist' else print'not exist'

第二个参数 "u" 就表示tb_table是用户创建的表,即:USER_TABLE地首字母简写


查询sys.objects中可得到各种资源的类型名称(TYPE列),这里之举几个主要的例子
u  -----------  用户创建的表,区别于系统表(USER_TABLE)
s  -----------  系统表(SYSTEM_TABLE)
v  -----------  视图(VIEW)
p  -----------  存储过程(SQL_STORED_PROCEDURE)可使用select distinct type ,type_desc from sys.objects 获得全部信


原文地址: http://blog.csdn.net/fulianglove/archive/2008/08/07/2783381.aspx

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!