MsSql判断表是否有自增标识

如果表有自增标识,那么就不能给这个自增列插入值或者更新这个列。

当然,如果要强制插入标识列也是可以的,只要设置Identity_insert为on即可,语法:

set Identity_insert tablename on;
insert into tablename (col1,col2) values (value1,value2)

但有时候我们在操作表的时候,我们并不知道这个表有没有标识列,如果有自增的标识列,我们可以用上面的方法打开开关进行插入,但是如果这个表是没有自增列的,用了上面的方法就会报错,所以我们有必要在使用这个开关语句的时候先判断一下这个表是不是有标识列,判断的SQL语句有两种:

select * from syscolumns where id=object_id(N'tablename') and COLUMNPROPERTY(id,name,'IsIdentity')=1;


select * from syscolumns where id=object_id(N'tablename') and status=0x80

两种方法都可以

posted on 2017-11-03 17:19  ymworkroom  阅读(890)  评论(0编辑  收藏  举报