Sql Server的一些语句

来源:互联网 发布:凯立德导航端口不对 编辑:程序博客网 时间:2024/05/16 17:43

Sql Server的一些语句

一、   说明

当我们查询sql server数据库的时候,我们是否会看到有的查询语句是查询表“sysindexes”,而有的则是查询“sys.indexes”表。这两个表的说明如下:

u  Sysindexes表:是SQL Server2005以前的版本使用的存储索引的表。

u  sys.indexes表:是SQL Server2005(包含)以后中存储索引的表。

SQL Server2005对一些表结构的存储发生了变化,所以在使用的时候需要注意下。具体的对象关系可以查看下面的链接:

http://msdn.microsoft.com/en-us/library/ms187997.aspx

二、   SQL语句

1.  查询某个对象(表、索引等)在sysobjects中对应的Id

查询sysobjects表中是否存在“WCMID”表,如果存在则返回该对象Id,不存在则返回null

  select OBJECT_ID('WCMID'); 

语句等同于

  select id from sysobjects where name='WCMID' 

 

2.  查询某个Id在数据库中对应的名称

  select OBJECT_NAME(1838629593); 

语句等同于

  select name from sysobjects where id=1838629593 

 

3.  查询表Student表是否存在Age列,不存在则添加

  if not exists(SELECT * FROM SYSCOLUMNS WHERE name='Age' and id=OBJECT_ID('Student')) 

begin

    alter table Student  add Age int default 0 not null;

    update Student set Age=1  where RoleRange=1;

end

GO

 

 

4.  查看Student表上是否有名为“IX_NAME_AGE”索引

 

select * from sysindexes where name='IX_NAME_AGE' and id =OBJECT_ID('STUDENT');

5.  查询Student表中是否有“Age”列

 

select * from sys.columns where object_id=OBJECT_ID('STUDENT') and name='AGE'

 

6.  查询Student表上的“AGE”列是否存在索引

 

select * from sys.index_columns where object_id=OBJECT_ID('STUDENT') AND EXISTS(

  SELECT 1 FROM sys.columns where object_id=OBJECT_ID('STUDENT') and sys.index_columns.column_id=sys.columns.column_id and name='AGE'

);