千家信息网

SqlServer系列笔记——表的创建维护

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,--创建表create table Employees(EmployeeID Int primary key ,Name VarChar(10) NOT NULL,Sex Char(2) defaul
千家信息网最后更新 2025年02月01日SqlServer系列笔记——表的创建维护


--创建表

create table Employees

(

EmployeeID Int primary key ,

Name VarChar(10) NOT NULL,

Sex Char(2) default '男',

Birthdate Datetime NULL,

Address Varchar(50) NULL,

Phone Char(13) check (phone like '000-[0_9]'),

Remark text

)

create table wage

(

EmployeeID Int foreign key references Employees(EmployeeID),

Name VarChar(10) NOT NULL,

Wage money NOT NULL,

Putdate Datetime NOT NULL,

)

--添加主键约束

alter table Employees

add constraint Employees_PK primary key (EmployeeID)

--添加外键约束

alter table wage

add constraint wage_FK foreign key (EmployeeID) references Employees(EmployeeID)

--删除约束

alter table wage

drop constraint wage_FK

--添加default约束

alter table Employees

add constraint a default ('unknown') for name,

constraint b default ('男') for sex,

constraint phone_check check(phone like '(\d{3})\d{9}')

--删除列

alter table Employees

drop column Remark

--添加列

alter table Employees

add Remark text,

phone varchar(10)

--删除表的全部数据,表还在

delete from table_name

DELETE FROM Person WHERE age> 20

--删除数据还原标识

truncate table table_name

--添加Insert


给可以给字段默认值,如果Guid类型主键的默认值设定为newid()就会自动生成主键:

insert into Person3(Name,Age) values('lili',38);

insert into Person(Id,Name,Age) values(newid(),'tom',30);

--更新Update

更新一个列:UPDATE T_Person Set Age=30


更新多个列:UPDATE T_Person Set Age=30,Name='tom'


更新一部分数据: UPDATE T_Person Set Age=30 where Name='tom'

------注意SQL中等于判断用单个=,而不是==


--Where中还可以使用复杂的逻辑判断UPDATE T_Person Set Age=30 where Name='tom' or Age<25,

--or相当于C#中的||(或者)

update Person1 set NickName=N'二十岁'

where (Age>20 and Age<30) or(Age=80)


--Where中可以使用的其他逻辑运算符:or、and、not、<、>、>=、<=、!=(或<>)等


0