判断表是否存在
IF EXISTS (SELECT * FROM sysobjects WHERE name = 't_dispatchBill_entry' AND xtype = 'U')
DROP TABLE t_dispatchBill_entry
GO
在ms sql中当我们需要修改表结构的时候,有时候因为添加或修改的表字段存在或不存在而导致后面的sql脚本执行失败。
这时我们需要一个语句来判断当前字段的有效性。然后再执行我们的sql脚本,这样就可以避免了。
--根据表名查询当前表的字段及其对应的表
select b.name tableName, a.name fieldName
from syscolumns a join sysobjects b on a.id = b.id
where b.xtype = 'u' and b.name = 'mm_sample';
go
/*
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 = 扩展存储过程
*/
--根据表名查询字段信息
select name from syscolumns where id in (
select id from sysobjects where name = 'mm_sample'
)
go
select table_Name, column_Name from information_schema.columns
where table_name = 'mm_sample'
go
select name, length from syscolumns
where id = object_id( 'mm_sample ')
and colid in (
select colid from sysindexkeys where id = object_id( 'mm_sample ')
)
go
--select object_id('mm_sample')
--select * from sysobjects where id = object_id('mm_sample')
select name, * from syscolumns where id = object_id('mm_sample')
go
--查看表信息
sp_help 'mm_sample'
go
if (exists (select name from syscolumns where id = object_id('mm_sample') and name = 'wt_id'))
print '该字段已经存在!';
else
print '该字段不存在';
go
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/IBM_hoojo/archive/2010/06/03/5644111.aspx
浙公网安备 33010602011771号