2017-3-10 SQLserver增,删,改,查语句,主外键约束

来源:互联网 发布:西门子编程电揽电源 编辑:程序博客网 时间:2024/06/03 21:56

(一)

1.创建数据库  create database  数据库名称  ----不能数字开头,不能中文,不能符号开头

删除数据库  drop database 数据库名称

注释:/*    */  一段注释   --一行注释

2.创建表  create table 表名称

  列名  数据类型,

  ……     ,

  列名 数据类型,

3            设置主键列:primary key  设置唯一列:unique  设置非空:not null    设置自然增长列:identity(1,1)从一开始,每次增加1

     删除表:drop table 表名

  添加列:alter table 表名 add 列名 数据类型

  删除列:alter table 表名 drop column 列名

4.添加数据 insert into 表名 values(字符串,时间,布尔类型需要用单引号   数字不需要)

insert into Student values('s001','张三','true','n001','1995-2-2',99)

5.修改数据:update 表名 set 列名 = 值  -----   这样是修改这一列的全部值

update Student set Score =100

6.删除数据:delete from 表名     或者truncate table 表名

区别:delete删除的数据是可以恢复的,留言删除日志 truncate 删除是清空,没有日志,释放存贮地址,无法恢复

7.查询语句:select * from 表名

(二)

1.条件修改:可以针对某个某个数据进行修改

update 表名 set 列名 = 值 where 列名 = 值

update Student set Name = '小刘' where StudId='s001' ----  将s001的姓名改为小刘

2.条件删除:

delete from 表名 where 列名 = 值

delete from Student where StudId='s002  ---- 删除学号是s002学生的成绩

(三)高级查询

1.条件查询  

  + 查列 *改为要查看的列,多列逗号隔开    select Score from Student   --   查看学生成绩列
  + 筛选条件 where 列名 = >= <= > < 值 and or

2.模糊查询

  select * from 表名 where 列名 like ’%xxx%‘  %通配符,表示还有xxx的

3.排序查询

  select * from 表名  order by 列名 asc--从低到高/desc--从高到低

4.去重查询

  select distinct 列名 from 表名

5.分组查询

  select 某一列 from 表名 group by 对应的列名

6.子查询

  将查询的语句当作值来使用

(四)

 1.主外键的约束:

--alter table 被约束的表名 add constraint约束名称 foreign key(被约束表的列名)references 用来约束另外表的名称(用来约束外表的列名)

如表A中的Ids是主键,要约束表B中的Aid列,那么语句应该是:

alter table B add constraint (A_B_Ids   这个是约束名称,随便写) foreign key(Aid)  references A(Ids) 

 

0 0
原创粉丝点击