sql server获取对象并判断对象是否存在

 

ContractedBlock.gif ExpandedBlockStart.gif
 
   
写测试SQL语句时,经常出现对象已经存在这类的问题,很烦,很有必要在创建对象之前判断其是否存在,以下是在网上收集一些判断方法,整理出来,都试验证过。

-- 判断表是否存在,存在删除之
--
非临时表
if exists ( select * from sysobjects where id = object_id (N ' 表名 ' ) and OBJECTPROPERTY (id, N ' IsUserTable ' ) = 1 )

-- OR if exists(select 1 from sysobjects where id=object_id('表名') and xtype='U')
drop table 表名
-- 临时表
if object_id ( ' tempdb..表名 ' ) is not null
drop table 表名

-- 判断存储过程是否存在
if exists ( select 1 from sysobjects where id = object_id ( ' 存储过程名 ' ) and xtype = ' P ' )

drop procedure 存储过程名

-- 获取用户创建的对象信息

SELECT [ name ] , [ id ] ,crdate FROM sysobjects where xtype = ' U '

/*

xtype 的表示参数类型,通常包括如下这些
C = CHECK 约束
D = 默认值或 DEFAULT 约束
F = FOREIGN KEY 约束
L = 日志
FN = 标量函数
IF = 内嵌表函数
P = 存储过程
PK = PRIMARY KEY 约束(类型是 K)
RF = 复制筛选存储过程
S = 系统表
TF = 表函数
TR = 触发器
U = 用户表
UQ = UNIQUE 约束(类型是 K)
V = 视图
X = 扩展存储过程

*/

-- 删除表主键

declare @PKName varchar ( 100 )
declare @sql varchar ( 4000 )

-- 获取主键名称
select @PKName = name from sysobjects where xtype = ' PK ' and parent_obj = object_id ( ' 表名 ' )
set @sql = ' alter table prodconstru drop constraint ' + @PKName
exec ( @sql )

-- 添加主键

alter table 表名 add constraint 主键名 primary key (列名);

-- -获取表的列名等信息(在网上当的)
select c.name, t.name as type, c.length
,(
case t.name
when ' nvarchar ' then c.length / 2
when ' nchar ' then c.length / 2
else c.length
end )
as reallength
from syscolumns c join systypes t
on c.xtype = t.xtype
where t.name <> ' sysname ' and c.id = object_id ( ' 表名 ' )

-- 判断表是否含有带自动编号的列

select objectproperty ( object_id ( ' 表名 ' ), ' tablehasidentity ' )

 

转载于:https://www.cnblogs.com/dyz/archive/2010/02/03/1662629.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值