码迷,mamicode.com
首页 > 数据库 > 详细

sql server实用要点全解

时间:2017-12-28 23:27:18      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:成功   ext   ack   case   自定义   转化   等于   got   精确   

本文介绍sql server的相关的查询语句和标准T-sql语法

sql server中支持的数据类型

  1. ANSI字符和UNICODE字符的区别

    在学习数据类型之前先来学学什么是ANSI字符和Unicode字符
    ANSI编码用一个字节来存放英文,用二个字节存放中文,但是由于自身限制有些中文是无法表示的
    Unicode编码对所有的字符都用两个字节表示,对中文和英文都有非常好支持
  2. sql server支持的数据类型如下

    bigint 整数值,不包含小数点,精度19,也就是最大19位数
    binary(50) 二进制串,可以指定长度
    bit 占位符,允许01或者NULL
    char(10) 固定长度的字符串,最多8000
        设置了某个长度,那么如果值得长度小于指定的长度就自动填充,超过了就自动截断
        用来表示ANSI字符
    date 存储日期格式的值 YYYY-MM-DD // 2017-10-11
    datetime 存储日期和时间 YYYY-MM-DD HH:MM:SS // 2017-10-11 22:23:21.423
    datetime2(7) 存储日期和时间 2017-10-11 22:24:37.2500000
    datetimeoffset(7) 基本格式和datetime2相同,但是加上了时区偏移 2017-10-11 22:25:49.3633333 +00:00
    decimal(3, 1) 设置一个数值,其中前面一个参数表示数值的最大位数(不包括小数点),后面一个参数表示小数位数(不包括小数点)
    float 表示浮点值,可以说任何一个数值都可以用float来表示
    image 可变长度的字符串,用来保存图片
    int 保存整数,可以是负数,如果传递小数默认取整数部分值保存
    money 用来表示货币数据,或者转化货币字符串,如插入$111字符串,自动转化成111.00货币数据
    nchar(10) 固定长度和char类型一致,nchar用来表示Unicode字符
    ntext 用来存储大文本数据,存储Unicode字符串
    numeric(18, 0) 和decimal的作用和使用方式相同,只是名称不一样而已
    nvarchar(50) 可变长度的字符串,用来存储Unicode字符,支持4000个字符的存储
    nvarchar(MAX) 和nvarchar表达的意思类似,不过支持更大的字符长度存储
    real 数据类型表示浮点值,和float类似,只不过real保存的数字,小数位数和整数位数最大7位,可以用float代替,float设置在1-15之间,默认是real
    smalldatetime 日期格式,2017-10-11 22:26:00,精确到一分钟
    smallint 最大,五位数,只保存值得整数部分,带符号范围-3276832767,无符号065535
    smallmoney 存储值比money小,介于 -214,748.3648214,748.3647 之间的货币数据。
    sql_variant 存储除了 text ,ntext, timestamp 之外的任何类型值 
    text 用来存储大文本数据,用来保存非Unicode字符
    time(7) 存储时间 20:34:00.0000000
    timestamp 时间戳,当行修改或者创建时自动更新,一个表只能设置一个
    tinyint 允许从 0255 的所有数字
    uniqueidentifier 存储全局唯一标识符 (GUID)。使用newid()可以创建一个guid,一般用来作为主键
    varbinary(50) 可变长度二进制字符串,binary是定长
    varbinary(max) 超长二进制字符串
    varchar(50) 可变长度的字符串
    varchar(MAX) 超长字符串
    xml 存储XML格式的数据,超长

标准语法

  1. 变量

    局部变量

    使用declare声明局部变量
        declare @a nchar(5);
        declare @a nchar(5), @b int;
    使用select或者set给变量赋值
        select @a = ‘111‘;
        select @a = ‘aa‘, @b = 1;
        select @a = StudentName from [Student] where StudentID = 9;
        set @a = ‘ha‘;

    全局变量

    全局变量使用@@开头,是系统内置的,无法自定义,例如
    print @@VERSION; 输出版本信息
    print @@DBTS; 返回当前时间戳值
  2. 操作符

    注释符

    单行注释,使用 -- 注释
    多行注释,使用 /*内容*/

    运算符

    算数运算符
        + - * / %
    赋值运算符
        =
    比较运算符
        > < = >= <= <>(不等于) != !>(不大于) !<
    逻辑运算符
        主要用在where字句
        all and any between exists in like not or some
    字符串连接运算符
        +
    通配符
        配合like用于模糊查询
        % 表示 >= 0 个字符
        _ 表示 1 个字符
        [] 表示任意单个字符
        [^] 表示非任意单个字符
  3. 流程控制语句

    if

    if(1 < 2)
        begin
            print ‘haha‘
        end
    else
        begin
            print ‘kuku‘
        end

    case

    类似于一般编程语言的switch
    如下是根据员工的名称,给员工添加职位信息
        select *, 职位 = case 
            when [StudentName] = ‘小王‘ then ‘老总‘
            when [StudentName] = ‘小叶‘ then ‘技术总监‘
            else ‘普通员工‘
            end
        from [dbo].[Student]
        或者使用如下简写形式
        select *, 职位 = case [StudentName]
            when ‘小王‘ then ‘老总‘
            when ‘小叶‘ then ‘技术总监‘
            else ‘普通员工‘
            end
        from [dbo].[Student]

    while

    declare @index int = 0;
    while @index < 100
        begin
            set @index += 1;
        end
    print @index

    流程终止语句

    break 跳出循环
    continue 跳出本次循环
    return 终止程序
    goto 跳转到标识符位置重新执行代码
        declare @index int = 0;
        count: set @index+=1; // 声明count标识符
        if(@index < 10) goto count; // 条件满足则跳转到标识符位置,重新执行代码
    waitfor 设置延迟时间或者时间点,参数必须是datetime类型
        waitfor delay ‘00:00:03‘ print ‘haha‘; // 延迟3秒执行
        waitfor time ‘20:43:00‘ print ‘叶家伟你好帅‘; // 设置代码执行时间点
  4. 聚合函数

    sum 求和
    avg 平均值
    min 最小值
    max 最大值
    count 计数
    distinct 去重
        select distinct StudentName from [dbo].[Student]
    聚合函数一般和group by字句配合使用
        select StudentName, count(StudentName) as number from [dbo].[Student] group by StudentName
        可以在group by字句后面使用having做进一步筛选,和where作用类似
        select StudentName, count(StudentName) as number from [dbo].[Student] group by StudentName having StudentName = ‘yejiawei‘;
  5. 数学函数

    abs 绝对值 abs(-2)
    pi 圆周率 pi()
    power 乘方 power(10,3)
    rand 随机数 
        print rand(100) 固定随机数
        print rand() 0~1之间任意随机数
    round 四舍五入 print round(1.2225555,3)
    square 平方 print square(4)
    sqrt 平方根 print sqrt(4)
  6. 字符串函数

    charindex函数
        print charindex(‘b‘, ‘abcd‘, 0)
        从字符串abcd的起始位置开始找b出现的索引位置,索引从1开始,返回结果如果为0,表示不存在
    left函数
        print left(‘abcdefg‘, 3) 从字符串左边开始截取三个字符
    right函数,从右边截取
    len函数,返回字符串个数 print len(‘absdg‘)
    replace函数,字符串替换,print replace (‘abdgae‘, ‘ae‘, ‘叶家伟‘)
    reverse函数,字符串反转 print reverse(‘cefet‘)
    str函数,将数值转化成字符串
        print str(round(1.2222234324, 3), 5, 3)
        转化后字符串长度是5,小数位数是3
    substring函数
        print substring(‘gaerget‘, 2, 3);
        从索引为2开始截取3个字符,索引是从1开始的
  7. 日期函数

    getdate 系统当前时间 print getdate()
    day 返回指定时间的天数部分 print day(getdate())
    month 返回月份 print month(getdate())
    year 返回年份 print year(getdate())
    dateadd 时间增加
        print dateadd("year", 4, getdate()) 增加4年
        print dateadd("month", 4, getdate()) 增加4月
        print dateadd("day", 4, getdate()) 增加4天
    datediff 返回时间间隔
        print datediff(day, ‘2017-4-5‘, ‘2017-4-9‘) 返回天数的差数
  8. 类型转换函数

    cast 类型简单转换 print cast(‘111‘ as int)
    convert 类型代号转换 print convert(varchar(255), getdate(), 102)
  9. 其他函数

    UPPER函数,大写,print upper(‘qq‘)
    LOWER函数,小写,print lower(‘QQ‘)
    FORMAT函数,格式化数据,print format(getdate(), ‘yyyy-mm-dd‘)

T-sql语法

  1. select基本语句的使用

    with语句的使用

    书写复杂的嵌套的select语句可以使用with提取,简化
    with result(StudentID, StudentName) as (
        select StudentID, StudentName from [dbo].[Student]
    )
    select * from result;
    使用with提取的select语句必须在随后使用

    列别名的三种方式

    select 
        StudentID id1, 
        id2 = StudentID, 
        StudentID as id3 
    from [dbo].[Student]

    into语句的使用

    创建一张表,将筛选的结果复制到新表中
    select * into BackUpTable from [dbo].[Student]

    where语句的使用

    or配合
        select * from [dbo].[Student] where StudentID = 10 or StudentID = 12
    not配合
        select * from [dbo].[Student] where not StudentID > 12
    like配合
        select * from [dbo].[Student] where StudentName like ‘%李‘
    between配合
        select * from [dbo].[Student] where StudentID not between 12 and 17
    null配合
        select * from [dbo].[Student] where StudentName is null
    In配合
        select * from [dbo].[Student] where StudentID in (10,12)
    all配合
        select * from [dbo].[Student] where StudentID >All (select StudentID from [dbo].[Student] where StudentID in (10,12))
        >All表示 大于子查询的最大值
    some配合
        some和any等效
        >some表示 大于子查询的最小值
    exists配合
        两表联合查询
        select TeacherId from [dbo].[Teacher] as a where exists (select TeacherType from [dbo].[Teacher] as b where a.TeacherId = b.TeacherType)
        先计算外层的查询的数据,然后传递到子查询中进行判断,满足则返回数据

    group by使用

    分组
    select StudentID, count(StudentID) as number from [dbo].[Student] group by StudentID
    group by后面如果要进一步筛选只能用having

    order by使用

    排序
    select * from [dbo].[Student] order by StudentID desc  -- 倒序

    top 使用

    取前5个
        select top 5 * from [dbo].[Student]
    取前5%
        select top 5 percent * from [dbo].[Student]
  2. update基本语句的使用

    更新数据 
    update [dbo].[Student] set StudentName=‘小花‘ where StudentID = 24
  3. insert into基本语句的使用

    新增数据
        整行插入 insert into [dbo].[Teacher] values (‘teacher‘, 2, 3)
        指定列插入 insert into [dbo].[Student] (StudentName) values (‘小叶‘)
  4. delete基本语句的使用

    删除一条数据 delete from [dbo].[Student] where StudentID = 25
    删除整个表数据
        delete from [dbo].[Student]
        delete * from [dbo].[Student]
  5. union表联接

    将两个表的数据合并到一个结果集中
    默认合并剔除重复值
        select * from [dbo].[Student]
        union
        select * from [dbo].[Student]
    使用all可以显示所有值
        select * from [dbo].[Student]
        union all
        select * from [dbo].[Student]
    不同数据类型强并
        select StudentName from [dbo].[Student]
        union all
        select cast(StudentID as nvarchar(50)) from [dbo].[Student]   
    空列强并
        select StudentName, StudentName from [dbo].[Student]
        union all
        select cast(StudentID as nvarchar(50)), null from [dbo].[Student]
  6. 约束

    not null 非空约束
        表设计中可设置
    primary key 主键约束
        表设计中直接设置,非空唯一
    foreign key 外键约束
        表设计中直接设置,在外键表中设置
    check 指定条件约束
        表设计器中直接设置,如 ProductPrice > 1
    default 默认值约束
        表设计中可设置
  7. 嵌套查询

    select * from [dbo].[Student] where StudentID = (select StudentID from [dbo].[Student] where StudentID = 10)
    先计算子查询的结果,然后再判断,这要求子查询结果唯一
  8. 关系表联合

    内联

    使用inner join,先进行笛卡尔积运算,当满足条件数据横向拼接到一个结果集
    select StandardName from [dbo].[Teacher] as a inner join [dbo].[Standard] as b on a.StandardId = b.StandardId

    外联

    左外联,使用 left outer join,以左表为基准,当条件满足合并,不满足置空
    select * from [dbo].[Teacher] as a left outer join [dbo].[Standard] as b on a.StandardId = b.StandardId
    右外联,使用 right outer join
    全外联,使用 full outer join
        先以左表为基准,执行左外联的规则,执行之后,如果右表数据还有未匹配的,那么执行右外联的规则,将结果集合并

    交叉

    使用cross join,只进行笛卡尔积运算
    select * from [dbo].[Student] cross join [dbo].[Student] as b
  9. 视图的使用

    视图是一张虚拟表,将一段sql语句使用表关联,使用MSSM可以方便的创建视图
  10. 存储过程

    存储过程就是讲 sql 封装起来随时执行,使用MSSM方便创建
    执行存储过程 exec [dbo].[MyTest] 12
  11. 触发器

    触发器用来根据数据库完成某种操作然后调用,使用MSSM创建
  12. 游标的使用

    declare mycursor cursor for select * from [dbo].[Student] -- 声明游标
    open mycursor -- 打开游标
    fetch next from mycursor -- 使用游标
        while @@FETCH_STATUS=0 -- 执行状态码,0表示成功,-1表示失败,-2表示数据没有
            begin
                fetch next from mycursor
            end
    close mycursor -- 关闭游标
    deallocate mycursor --释放游标
    注:游标的性能很差,基本不用
  13. 索引

    聚集索引,就是按照顺序找数据,无需额外添加聚集索引,主键就是聚集索引
    非聚集索引,就是按照名字找数据,是无序的,可以使用MSSM创建
  14. 事务

    事务就是代码块,失败了可以回滚,sql中的每条语句默认就是一个事务
    use [SchoolDB]
    begin transaction myTransaction -- 开始事务
    print @@trancount -- 打印事务状态 1
        set transaction isolation level read uncommitted -- 设置事务隔离级别,不可脏读
        save transaction savepoint -- 设置回滚点
        insert into [dbo].[Student](StudentName) values(‘小红‘) 
        rollback transaction savepoint -- 回滚到回滚点
        commit transaction myTransaction -- 提交事务,保存数据
    print @@error -- 打印代码状态 0
    print @@trancount -- 打印事务状态 0
    select * from [dbo].[Student]

sql server实用要点全解

标签:成功   ext   ack   case   自定义   转化   等于   got   精确   

原文地址:https://www.cnblogs.com/ye-hcj/p/8137894.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!