SQL server 表中如何创建索引?看个示例,你就会了
use master
go
if db_id(N'zhangxu')is not null
drop database zhangxu
go
create database zhangxu
sp_helpdb zhangxu
use zhangxu
go
IF EXISTS (SELECT *FROM SYS.OBJECTS WHERE NAME = N'WORKER')
DROP TABLE WORKER
GO
create table worker
(
w_id int identity (1000,1) not null,
w_name Nvarchar(10) unique,
w_age SMALLINT CONSTRAINT CK_W_AGE CHECK(w_age>20 and w_age<150),
w_pay money DEFAULT 0,
CONSTRAINT PK_W_ID PRIMARY KEY(W_ID)
)
SELECT *FROM WORKER--用查询技术查看表信息
sp_help worker--利用存储过程查看表信息
/*
创建简单的非聚集索引
*/
USE ZHANGXU
GO
if exists(select name from sys.indexes where name = N'IX_ID_NAME')
DROP INDEX IX_ID_NAME on worker
go--检查是否存在索引,有则删除索引
create index IX_ID_NAME--创建索引
on worker(w_id,w_name)--在ID NAME 两个字段上创建非聚集索引
drop index worker.IX_ID_NAME--删除索引
select *from sys.indexes where name = 'IX_ID_NAME'--查看索引
/*
创建唯一非聚集索引
*/
USE ZHANGXU
GO
IF EXISTS(SELECT NAME FROM SYS.INDEXES WHERE NAME = N'IX_W_NAME')
DROP INDEX IX_W_NAME ON WORKER
GO
CREATE UNIQUE INDEX IX_W_NAME--唯一非聚集索引
ON WORKER(W_NAME)
/*
查看索引T-SQL脚本
*/
--IX_W_NAME 唯一 非聚集索引
USE [zhangxu]
GO
/****** 对象: Index [IX_W_NAME] 脚本日期: 07/29/2007 16:54:53 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_W_NAME] ON [dbo].[worker]
(
[w_name] ASC
)
WITH
(
SORT_IN_TEMPDB = OFF,
DROP_EXISTING = OFF,
IGNORE_DUP_KEY = OFF,
ONLINE = OFF
)
ON [PRIMARY]
--PK_W_ID聚集索引
USE [zhangxu]
GO
/****** 对象: Index [PK_W_ID] 脚本日期: 07/29/2007 16:56:45 ******/
ALTER TABLE [dbo].[worker]
ADD CONSTRAINT [PK_W_ID] PRIMARY KEY CLUSTERED
(
[w_id] ASC
)
WITH
(
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
ONLINE = OFF
) ON [PRIMARY]
--UQ_WORKER 唯一,非聚集索引
USE [zhangxu]
GO
/****** 对象: Index [UQ__worker__07020F21] 脚本日期: 07/29/2007 16:58:38 ******/
ALTER TABLE [dbo].[worker]
ADD UNIQUE NONCLUSTERED
(
[w_name] ASC
)
WITH
(SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
ONLINE = OFF
) ON [PRIMARY]
select *from worker
insert into worker(w_name,w_age,w_pay) values('王国龙',25,4500)