zoukankan      html  css  js  c++  java
  • T_SQL 大集合

    创建一个数据库
    create database aaa[数据库名];

    删除一个数据库
    drop database aaa[数据库名];

    create database bbb
    on primary--指定主数据文件
    (
       name='bbb',
      size=5mb,
      maxsize=100bm,
      filename='c:\test.mdf'
    )
    log on
    (
       name='bbb_log',
      size=5mb,
      maxsize=100bm,
      filename='c:\test.ldf'
    )

    创建表
    create table Tbclass[表名]
    (
        classId[字段] int[类型] identity(1,1)[自动增长] primary key[设置主键],
        className nvarchar(50) not null,
        classDescription nvarchar(100) not null
    )

    修改表

    alter database tablename
    {
       
    }

    插入数据
    insert into Tbclass[表名](className[字段],classDescription) values('高一一班'[值],'实验班');

    多表插入,值对应
    insert into TblScore
    select 002,70,89 union [all]
    select 003,74,33 union  [all]
    select 004,73,89 union  [all]
    select 005,65,49 union [all]
    select 006,70,89

    --复制整个表满足年龄大于5的到另一个表
    select * into TblScoreBak from TblScore where age>5

    --把表结构复制到另一个表,不复制数据
    select * into TblScoreBak from TblScore where 1=2 [不成立就不复制数据]

    删除表
    delete from TblScoreBak  where tMath=89;
    delete from TblScoreBak;
    truncate table [tablename]  它清空表的同时还原了表的种子(标识到1)

    更新表
    update TblScore[表名] set tEnglish=tEnglish+10 where tSId=1;

    order by 排序 默认为asc升序
    select  * from TblTeacher order by tTAge desc,tTSalary asc
    select  * from TblTeacher where tTAge>10 order by tTAge desc  注意:where一定要在order by之前

    通配符查询
    select * from employee where name like '_erry'  查询一个5个字符后面是erry的employee
    select * from employee where name like '%n%'   查询句子带有n的所有employee %表示0个或多个字符

    查询表中数据是null的语句
    select * from employee where name is null(is not null)

    查询表中年龄是23,25,27 的员工的姓名
    select name from employee where age=23 or age=25 or age=27
    select name from employee where age in {23,25,27}

    查询表中年龄在23,27之间的员工姓名
    select name from employee where age>23 and age <27
    select name from employee where age between 23 and 27

    分组查询
    select age,Count(*) from employee group by age   按照分组查询年龄和它的组的个数

    having 语句   聚合函数不能出现 在where子句中,
    select age,Count(*) from employee group by age having count(*)>1  按照分组查询年龄和它的组的个数条件是个数大于1的

    查询出工资前三名的员工
    select top 3 * from employee order by salary desc

    去除查询出的重复的信息
    select distinct department from employee
    去除两个字段都重复的信息
    select distinct department , subcompany from employee

    union 函数
    select name,age from tempemployee
    union
    select name,age from employee
     把两个查询的结果放在一个表中显示(显示字段要一致)
    select name,age,salary from tempemployee
    union
    select name,age,'临时工,没月薪' from employee

    union默认把重复的数据合并起来,用union all 去除重复
    select name,age from tempemployee
    union all
    select name,age from employee

    数字函数
    abs() 求绝对值
    ceiling()舍入到最大整数  ceiling 天花板
    floor()舍入到最小整数   floor  地板
    round() 四舍五入  round 半径

    字符串函数  ()里放要处理的字段
    len()  字符串长度
    lower()  uper()  转大小写
    ltrim() rtrim()  去掉左右的空格
    substring(string,start_position,lenght)
    isnull(score,'缺考')  [字段里如果有null,那么就替换成 缺考]

    日期函数
    getdate()  获取当前时间
    dateadd()   dateadd(day, 3[-3],getdate()) 当前时间加[减]三天 dateadd(hour,3,getdate()) 当前时间加三个小时
    datediff()  计算出两个日期的差额 datediff(hour,2011-2-2,2011-2-1)
    datepart() 取得当前时段的值  datepart(year,getdate())  datepart(month,getdate())

    类型转换函数
    cast('123' as int) cast('2008-08-08' as datetime)
    convert(datetime,'2009-02-03') convert(varchar(50),134)

    空值处理函数
    select isnull(name,'佚名') as 姓名 from employee

    case函数用法
    select name,
    (
      case clevel
      when 1 then '普通客户'
      when 2 then '会员'
      when 3 then 'VIP'
      else '未知用户'
      end
    )as 客户类型
    from customers

    select name,
    (
    case salary
    when salary <2000 then '低收入'
    when salary>2000 and salary <5000 then '中收入'
    else '高收入'
    )as 收入水平
    from employee

    创建约束
    primary key  主键约束
    unique   惟一约束
    check   检查约束
    默认约束   设计器下有默认绑定

    外键约束
    级联删除,级联更新

    -============手动增加约束==========
    --手动删除一列(删除EmpAddress列)

    alter table employee drop column emp_address

    --手动增加一列(增加一列EmpAddr varchar(1000))

    alter table employee add empaddr varchar(1000)

    --手动修改一下EmpEmail的数据类型(varchar(200))

    alter table employee alter column emp_email varchar(100)

    --为EmpId增加一个主键约束

    alter table employee add constraint PK primary key(emp_Id)

    --非空约束,为EmpName增加一个非空约束,修改列为not null
    --增加一个非空约束其实就是修改列

    alter table employee alter column emp+name varchar(50) not null

    --为EmpName增加一个唯一约束

    alter table employee add constraint UQ_Employee_emp_name unique(emp_name)

    --为性别增加一个默认约束,默认为'男'

    alter table employee add constraint DF_employee_gender default ('男') for emp_gender

    --为年龄增加一个检查约束:年龄必须在0-120岁之间,含0岁与120岁。

    alter table employee add constraint CK_employee_age check (age>=0 end age<120)

    --增加外键约束,表Employee中有一列EmpDeptId引用TblDepartment表中的DeptId

    alter table employee add constraint FK_employee_department foreign key (deptID) references department(dept_ID) on delete descade????

    --删除某个名字的约束

    alter table employee drop constraint [约束名1],[约束名2],[约束名3]

    --一条语句删除多个约束,约束名用 逗号 隔开

    --用一条语句为表增加多个约束。
    alter table employee add
    constraint PK primary key(emp_Id),
    constraint UQ_Employee_emp_name unique(emp_name),
    constraint DF_employee_gender default ('男') for emp_gender,
    constraint CK_employee_age check (age>=0 end age<120)

    函数

    去除重复
    select distinct name,age,gender from tablename
    max() min() sum() avg() count()

    select name,age from where age=count(age)

    插入一条数据并返回最后一行指定的tclassid的值  inserted.[可以是每一个列的列号]
    insert into Tblclass output inserted.tClassId values('.net班','学习.net并就业')


    索引
      --创建一个非聚集唯一索引
    create unique nonclustered  index   IX_TT5_userid on tt5(userid)

    --创建一个聚集非唯一索引
    create clustered index IX_TT5_username on tt5[表名](username[字段])

    --创建一个聚集唯一索引
    create unique clustered index IX_TT5_username on tt5(username)

    子查询
    查询出工资为6到8的员工的信息  子查询
    select top 3 * from employee where id not in (select top (5*n) id from employee order by salary desc) order by salary desc  高效分页

    查询高二二班的所有学生
    select * from student where sClassId = (select cId from class where cName='高二二班')

    查询高一一班和高二一班的所有学生
    select * from student where sClassId in
    (select cId from class where cName='高一一班' or cName='高二一班')

    多表查询

    --查询年龄超过20岁的学生的姓名、年龄及所在班级
    select tsname,tsage,tblclass.tclassname  from tblstudent inner join tblclass on tblclass.tclassid=tblstudent.tsclassid where tsage>20
    --查询学生姓名、年龄、班级及成绩,三表查询
    select tsname,tsage,tblclass.tclassname,tblscore.tenglish,tblscore.tmath from tblstudent
     inner join tblclass on tblclass.tclassid=tblstudent.tsclassid
     inner join tblscore on tblstudent.tsid=tblscore.tsid
    --请查询出所有没有参加考试(在成绩表中不存在的学生)的学生的姓名。
    select tblstudent.tsname from tblscore inner join tblstudent on tblstudent.tsid=tblscore.tsid where tenglish is null or tmath is null

    --查询所有学生(参加和未参加考试)的学生姓名、年龄、成绩,如果没有参加考试显示缺考,如果小于english&math60分显示不及格(外连接)
    --学生表里是所有的学生,成绩表里可能就没有全部的学生,就是没来参加考试的
    select tsname,tsage,isnull(convert(varchar(5),tblscore.tenglish),'缺考'),
    isnull(convert(varchar(5),tblscore.tmath),'缺考'),
    是否及格=case
    when tblscore.tenglish>60 and tblscore.tmath>60 then '不及格'
    else '及格'
    end
    from tblstudent left join tblscore on tblstudent.tsid=tblscore.tsid
    [left join 就是取左表的数据再与右表对比,左表的全部,right join同理]

    存储过程
    一,系统存储过程 
    exec sp_??[系统存储过程名]
    二,自定义存储过程
    create proc[edure] 存储过程名
    @参数1 数据类型,
    @参数2 数据类型,
    as
    begin
    select * from student
    end

    例:
    --创建存储过程
    create proc usp_ShowStudentsByAge
    @uage int
    as
    begin
       select * from mystudent where fage<@uage
    end
    --执行存储过程
    exec usp_ShowStudentsByAge 30[参数]

    --删除存储过程
    drop proc usp_add
    修改存储过程
    alter.......

    create proc usp_add
    @unm1 int,
    @num2 int=150
    as
    begin
        select @num1+@num2
    end

    exec usp_add 200  (!后面可以不写,前面一定不行)

  • 相关阅读:
    基础字段及选项2(11)
    模型层及ORM介绍(9)
    Luogu [P3367] 模板 并查集
    Luogu [P1958] 上学路线_NOI导刊2009普及(6)
    Luogu [P3951] 小凯的疑惑
    Luogu [P2708] 硬币翻转
    Luogu [P1334] 瑞瑞的木板(手写堆)
    一步步学习如何建立自己的个性博客~~
    Android初学者—listView用法
    SQLite命令—对表插入和修改等操作
  • 原文地址:https://www.cnblogs.com/inline/p/2470585.html
Copyright © 2011-2022 走看看