sql server数据库常用语句

1、创建索引的语句

create index 索引名 on 表(字段1,字段2,、、、);

create index index_AttachFile on AttachFile(CBillGuid,CGuid,DCreateTime);

此种默认方式创建的索引为非聚集索引。

建立非聚集索引,可以使用nonclustered 关键字。

如create nonclustered index 索引名 on 表(字段1,字段2,、、、);

若建立聚集索引,使用如下sql:

CREATE CLUSTERED INDEX CLUSTER_id ON TABLE_name(ID)

若表新增数据频繁,可定义一个聚集索引,如此新增的数据则按聚集索引进行排列,存取比较快速。 

扫描二维码关注公众号,回复: 310139 查看本文章

2、查询表有哪些索引

select b.*  from sys.sysobjects a, sys.sysindexes b where a.id = b.id  and a.name = 表名 and b.rows <>0;

3、常用的系统表

sys.indexes 索引
sys.objects 对象(表...)
sys.columns 字段
sys.index_columns 索引_字段
sys.tables 自定义表

 4、自定义排序

当没有合适的排序字段,需要自定义排序次序时,可以利用ORDER BY  CHARINDEX (<’substring_expression’>, <expression>)来进行自定义排序。

其中substring _expression 是所要查找的字符表达式,expression 可为字符串也可为列名表达式。如果没有发现子串,则返回0 值。

此函数不能用于TEXT 和IMAGE 数据类型。

如:

  1. select charindex('cd','abcdefg') --3  
  2. select charindex('ac','abcdefg') --0  

所以,当需要自定义排序时,可使用如下方式:

SELECT * from TaskBudgetBody ORDER BY charindex(State, '1,2,3,4,5,6,7,8,9,0') ASC。

 

 stuff()

[sql]  view plain  copy
 
  1. select stuff('abcde',2,3,'mmmm')  
[sql]  view plain  copy
 
  1. -- ammme  

--通过在第一个字符串 (abcde) 中删除从第二个位置(字符 b)开始的三个字符,
--然后在删除的起始位置插入第二个字符串,创建并返回一个字符串。

 

5、查询重复数据中最大值

在一张表中,根据字段A将数据进行查询,会查询到同是字段A某个值的数据多条,同是字段A另外值的数据可能多条,但这些多条数据,只保留Id最大的一条数据,简单的sql编写方式为:

 select max(id) from dic_dqxx 

 where parentid in (select parentid from dic_dqxx group by parentid having count(parentid) > 0)

 group by parentid;

第二种写法:

select *

FROM TaskAppreCord a where a.dateTime in (select max(b.dateTime) from TaskAppreCord b where b.cTaskGuid=a.cTaskGuid and b.userId = a.userId and b.signTag = a.signTag and b.resType=a.resType) 

and a.cTaskGuid='1111111111’  ORDER BY a.signTag ASC

6、获取表的各个字段

select a.name columnname,c.name as typename,

case when a.is_nullable =0 then 'Not Null' else 'Null' end as nullable,

a.*

from sys.columns a , sys.objects b, sys.types c 

where a.object_id= b.object_id and b.name='taskhome' and a.system_type_id=c.system_type_id order by a.column_id;

其中:select * from sys.objects; 是数据库中的所有的对象,type_desc确定该对象是系统表,用户表,视图或其他。

select * from sys.types:字段类型

select * from sys.columns :表的字段,通过object_id与sys.onjects取得关联关系。

 7、添加主键约束索引

alter table TaskAppreCord

      add constraint PK_TaskAppr_1CE36B853EC74557 Primary key (cGuid)

猜你喜欢

转载自jiage17.iteye.com/blog/2302171