USE master;
GO
CREATEDATABASE Test
ON(
NAME = Test_dat,
FILENAME ='D:\Database\Testdat.mdf',
SIZE =10,
MAXSIZE = UNLIMITED,
FILEGROWTH =5)
LOG ON(
NAME = Test_log,
FILENAME ='D:\Database\Testlog.ldf',
SIZE =5MB,
MAXSIZE =1024MB,
FILEGROWTH =5MB )COLLATE Latin1_General_CI_AS
GO
ALTERDATABASE Test SET RECOVERY SIMPLE;
GO
1.2.2. 创建表和索引
USE Test;
GO
CREATETABLE dbo.Dev
(
DevId INTIDENTITY(1,1)NOTNULL,
DevName NVARCHAR(200)NOTNULL,
StockQty DECIMAL(9,2)NULL,
Flag BITNOTNULLDEFAULT(1),
DevType SMALLINTNOTNULLDEFAULT(1),
CreateUser NVARCHAR(10)NOTNULL,
CreateDate DATETIMENOTNULLDEFAULT( GETDATE()),
ModifyUser NVARCHAR(10)NULL,
ModifyDate DATETIMENULL,CONSTRAINT PK_Dev_DevId PRIMARYKEYCLUSTERED( DevId ASC));
GO
USE Test;
GO
CREATETABLE dbo.Dev
(
DevId INTIDENTITY(1,1)NOTNULL,
DevName NVARCHAR(200)NOTNULL,
StockQty DECIMAL(9,2)NULL,
Flag BITNOTNULLDEFAULT(1),
DevType SMALLINTNOTNULLDEFAULT(1),
CreateUser NVARCHAR(10)NOTNULL,
CreateDate DATETIMENOTNULLDEFAULT( GETDATE()),
ModifyUser NVARCHAR(10)NULL,
ModifyDate DATETIMENULL,);
GO
--创建主键ALTERTABLE dbo.Dev
ADDCONSTRAINT PK_Dev_DevID PRIMARYKEYCLUSTERED( DevId );
GO
--删除主键ALTERTABLE dbo.Dev
DROPCONSTRAINT PK_Dev_DevID;
1.2.3. 修改表和索引
USE Test;
GO
--添加字段ALTERTABLE dbo.Dev
ADD remark NVARCHAR(500)NULL;--修改字段名EXECUTE sp_rename 'dbo.Dev.remark','dbo.Dev.memo';--修改字段类型ALTERTABLE dbo.Dev
ALTERCOLUMN memo NVARCHAR(300);--添加有默认值的字段ALTERTABLE dbo.Dev
ADD delflag INTNOTNULLDEFAULT0;--删除字段ALTERTABLE dbo.Dev
DROPCOLUMN delflag;--删除约束ALTERTABLE dbo.Dev
DROPCONSTRAINT[DF__Dev__delflag__276EDEB3]--查询约束EXECUTE sp_helpconstraint @objname='dbo.Dev'--查询约束SELECT*FROM sys.objects WHERE parent_object_id=OBJECT_ID('dbo.Dev')--所有SELECT*FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('dbo.Dev')--默认SELECT*FROM sys.check_constraints WHERE parent_object_id=OBJECT_ID('dbo.Dev')--检查SELECT*FROM sys.key_constraints WHERE parent_object_id=OBJECT_ID('dbo.Dev')--键--添加默认约束ALTERTABLE dbo.Dev
ADDCONSTRAINT DF_Dev_CreateUser DEFAULT('Admin')FOR CreateUser;--添加检查约束ALTERTABLE dbo.Dev
ADDCONSTRAINT CK_Dev_StockQtyCheck CHECK( StockQty BETWEEN0AND10000);--添加唯一约束ALTERTABLE dbo.Dev
ADDCONSTRAINT UQ_Dev_DevName UNIQUE(DevName);
USE Test;
GO
--查询索引SELECT i.object_id, i.name index_name, i.index_id, i.type_desc, i.is_unique, ic.column_id, c.name column_name,ic.is_descending_key
FROM sys.indexes i
INNERJOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
INNERJOIN sys.columns c ON c.object_id = i.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID('dbo.Dev');--创建非聚集索引CREATENONCLUSTEREDINDEX Index_Dev_DevName
ON dbo.Dev (DevName)WITH(DROP_EXISTING=ON)--删除索引DROPINDEX Index_Dev_DevName ON dbo.Dev;--创建唯一非聚集索引CREATEUNIQUEINDEX Index_Dev_DevName
ON dbo.Dev (DevName)WITH(DROP_EXISTING=ON)