데이터베이스 / Create 테이블 예제 만 들 기 (Sql Server 2005 문법)
3752 단어 SQLServer2008R2
use master
go
if exists (select * from sysdatabases where name='Study')-- Study ,
drop database Study
go
EXEC sp_configure 'show advanced options', 1
GO
--
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
-- (xp_cmdshell) .
RECONFIGURE
GO
exec xp_cmdshell 'mkdir D:/data', NO_OUTPUT
-- xp_cmdshell , dos , 。
go
create database Study--
on primary
(
name='Study_data',--
fileName='D:/data/Study_data.mdf',--
size=10MB,--
filegrowth=10% --
)
log on
(
name='Study_log',--
fileName='D:/data/Study_data.ldf',--
size=1MB,
maxsize=20MB,--
filegrowth=10%
)
go
use Study
go
if exists (select * from sysobjects where name='Student')--
drop table Student
go
create table Student
(
id int identity(1,1) primary key,--id ,
[name] varchar(20) not null,
sex char(2) not null,
birthday datetime not null,
phone char(11) not null,
remark text,
tId int not null,
age as datediff(yyyy,birthday,getdate())-- 。
)
go
if exists (select * from sysobjects where name='Team')
drop table Team
go
create table Team
(
id int identity(1,1) primary key,
tName varchar(20) not null,
captainId int
)
go
alter table Student
add
constraint CH_sex check(sex in (' ',' ')),-- ,
constraint CH_birthday check(birthday between '1950-01-01' and '1988-12-31'),
constraint CH_phone check(len(phone)=11),
constraint FK_tId foreign key(tId) references Team(id),-- , Team
constraint DF_remark default(' ') for remark-- ,
go
alter table Team
add
constraint UK_captainId unique(captainId)--
go
insert into Team values(' ',1)
insert into Team values(' ',2)
insert into Team values(' ',3)
insert into Team values(' ',4)
insert into Team values(' ',5)
insert into Student values(' ',' ','1982-6-9','23456789451',' ',1)
insert into Student values(' ',' ','1987-6-9','78945678945',' ',4)
insert into Student values(' ',' ','1982-6-9','65987845651',' ',3)
insert into Student values(' ',' ','1981-6-9','25487965423',' ',5)
insert into Student(name,sex,birthday,phone,tId) values(' ',' ','1984-6-9','25487965423',5)
select * from Team
select * from Student
if exists (select * from sysobjects where name='teacher')
drop table teacher
go
create table teacher
(
id int identity (1,1) primary key,
name varchar(20),
address varchar(20)
)
go
insert into teacher values('zhang','hubei')
insert into teacher values('wang','hubei')
insert into teacher values('li','hubei')
insert into teacher values('chen','hunan')
insert into teacher values('zhao','hunan')
insert into teacher values('tian','guangdong')
insert into teacher values('ma','guangdong')
insert into teacher values('chang','tianjin')
insert into teacher values('liang','beijing')
select * from teacher
select count(*),address from teacher group by address having address<>'hunan'
-- having ‘hunan’