zoukankan      html  css  js  c++  java
  • 【SQL Server学习笔记】表基础:数据类型、创建表、键、约束、表变量、


    1、表中字段类型


    SQL Server的字段类型大致可以分成这么几类:

    A、字符型:char、nchar、varchar、nvarchar

    B、精确数值型:bit、tinyint、smallint、int、bigint、smallmoney、money、numeric、decimal(与numeric完全一样)

    C、非精确数值型:float、real

    D、日期时间型:date、smalldatetime、datetime、datetime2、datetimeoffset、time、timestamp

    E、二进制型:binary、varbinary

    G、后续版本的SQL Server 将删除的类型:text、netxt、image

     F、其他类型:xml、hierarchyid、geography、geometry、uniqueidentifier、sql_variant、table(只是用于表变量、表值函数中定义行的存储)


    2、表

     
    
    --创建表
    CREATE TABLE t
    	(vid INT NOT NULL,
    	 v VARCHAR(20) NOT null,
    	 vidd int not null)             
    
    --添加列
    ALTER TABLE t
    ADD vv INT NULL
    
    
    --修改列定义
    --如果缺了Null或者NOT NULL,那么会根据数据库的默认配置来设
    --如果列有索引,当列类型为varchar、nvarchar、varbinary时才能修改,且新大小要比原大小更大
    ALTER TABLE t
    ALTER COLUMN v VARCHAR(10)  --这里会设置成NULL
    
    
    --修改列的排序规则,注意不能同时指出是否可以为NULL,否则会报错
    ALTER TABLE t
    ALTER COLUMN v varchar(50) COLLATE Chinese_PRC_CI_AS
    
    
    --重命名列名
    
    
    /*=================================================================================
    创建计算列:
    
    1.计算列不能用Default约束、Foreign key约束
    
    2.由于计算列的值是计算出来的(不管是否物理的存储在表中),所以不能被显式的更新、插入。
    
    3.非持久计算列能用在索引中,但必须是确定的(对于一组给定的输入,总能返回相同的结果)、
      精确的(不包含浮点值)。
      
    4.持久计算列的值是被物理的保存在数据库中的,对计算中使用到的列进行任何修改,都会
      引起存储值的更新,但这个列的值仍然是不能直接修改的,仍然要经过计算。
      特别需要注意的是持久化列能用于表分区、不精确值(浮点)的索引
    ===================================================================================*/
    alter table t
    add computeColumn as (vid * vidd)
    
    --创建持久计算列
    alter table t
    add persistedColumn as (vid * vidd) persisted
    
    --改为非持久列
    alter table t
    alter column persistedColumn  drop persisted
    
    --改为持久列
    alter table t
    alter column persistedColumn add persisted
    
    
    /*========================================================================
    删除表中的列:
    		1.当该列没有使用primary key约束,foreign key约束,
    						unique约束,
    						check约束,
    						default值约束时,该列才能被删除。
    
    		2.不能删除索引中的列
    ==========================================================================*/
    alter table t
    drop column v
    
    
    /*========================================================================
    当数据库设计、应用程序需要大量不常填充的列,
    或者表中存储的列集合只和表中存储数据的子集相关时,可以考虑使用稀疏列
    
    注意:
    1.一个表中可以存储30000个不常填充的列,其他数据类型都能使用稀疏列,
      但image、ntext、text、timestamp、geometry、geography、用户定义类型除外。
      
    2.没有应用的稀疏列,将不会为NULL值分配存储空间。
    
    2.使用列集。当表中包含成千上万的稀疏列时,列集特别有用,因为可以避免直接
                在查询中引用稀疏列的名称。
      A: 在列定义之后指定COLUMN_SET FOR ALL_SPARSE_COLUMNS来定义。
      
      B:一个表只可以有一个列集.
      
      C:如果一个表包含一个稀疏列,则无法将稀疏列集添加到该表,
         也就是说只能在定义表的时候使用列集,而不是先定义表然后再添加列集,这样会报错。
         
      D:任何没有在DML操作中引用的稀疏列,都被置为NULL值。
         一旦定义了稀疏列,查询时不会再返回所有稀疏列,只有非稀疏列和列集。     
    ==========================================================================*/
    --稀疏列
    create table tt
    	(vvid int not null,
    	 v1 varchar(10) SPARSE null,
    	 v2 varchar(30) SPARSE null,
    	 v3 int SPARSE null,
    	 v4 numeric(10,2) SPARSE null,
    	 v5 datetime SPARSE null
    	)
    
    INSERT INTO tt(vvid,v1,v2)
    values(1,'spv2','spv2')
    
    --将稀疏列转为非稀疏列
    alter table tt
    alter column v1 drop SPARSE
    
    --将非稀疏列转为稀疏列
    alter table tt
    alter column v1 add SPARSE
    
    
    --使用列集
    create table tx
    	(id int not null,
    	 v1 varchar(10) SPARSE null,
    	 v2 varchar(20) SPARSE null,
    	 v3 varchar(30) SPARSE null,
    	 vX XML COLUMN_SET FOR ALL_SPARSE_COLUMNS)
    
    INSERT INTO tx(id,v1)
    VALUES(1,'XYZ')
    
    --改为非稀疏列
    alter table TX
    alter column v1 DROP SPARSE
    
    --只会返回非稀疏列、列集
    SELECT *  FROM TX 
    
    --任何没有在DML操作中引用的稀疏列,都被置为NULL值。
    select ID,v1,v2,v3,vx from tx
    
    
    --重命名列,注意新的名称不要包含架构
    --可以是:COLUMN,DATABASE,INDEX,OBJECT(表,视图,函数,存储过程,触发器),USERDATATYPE
    exec sp_name 
    	@objname = 'dbo.tt.v',
    	@newname = 'wc',
    	@objtype = 'column'   
    
    --重命名表
    exec sp_rename 
    	@objname = 'dbo.t',
        @newname = 't1',
        @objtype = 'object'               
    
    --报告表的信息
    sp_help 'dbo.tt'
    
    --一次删除多个表
    drop table tt,t1,t   
    

    3、排序规则

    对于char、nchar、varchar、nvarchar类型的列,可以指定Windows或SQL排序规则。

    --显示SQL Server实例的默认的排序规则
    select SERVERPROPERTY('Collation') --显示:Chinese_PRC_CI_AS
    
    --显示数据库默认的排序规则
    select DATABASEPROPERTYEX('test2','Collation')  --显示:Chinese_PRC_CI_AS
    
    --获取友好的信息,显示排序规则到底是什么意思
    select description
    from sys.fn_helpcollations()
    where name = 'Chinese_PRC_CI_AS'
    


    返回:Chinese-PRC, case-insensitive, accent-sensitive, kanatype-insensitive, width-insensitive。

    意思是:大小写不敏感,口音敏感,假名不敏感,宽度不敏感。

    --指定排序规则时不能同时指定NULL或NOT NULL
    create table wc
    	(vid int not null,
         v varchar(10)  collate Chinese_PRC_CI_AS) 
    
    --指定列的排序规则     
    alter table wc
    add v1 varchar(20) COLLATE  Chinese_PRC_CI_AS,
        v2 varchar(30) COLLATE  Chinese_PRC_CI_AS
    

    注意:如果为同一个实例的同一个数据库或者多个数据库定义了不同的排序规则,有时候会有兼容性额问题。跨排序规则的关联可能会不正确,数据传输也会发生丢失或错误。


    4、键

    --没有指定约束名称来定义主键
    create table t
    	(id int primary key,
    	 idd int not null)
    
    --指定约束名称定义复合、聚集索引主键(多字段),
    create table tt
    	(id int not null,
    	 idd int not null,
    	 constraint pk_id_idd1
    	 primary key clustered (id,idd))
    	 
    
    --指定约束名称来定义复合、非聚集索引主键(多字段)	 
    create table ttt
    	(id int not null,
    	 idd int not null,
    	 constraint pk_id_idd2
    	 primary key  nonclustered (id,idd))
    
    --先定义表,再添加主键约束
    create table tttt
    	(id int not null,
    	 idd int not null,
    	 iddd int not null)
    
    alter table tttt
    add constraint pk_id_idd3
        primary key clustered (id,idd)
    
    
    --不指定外键约束名称来指定外键
    create table t1
    	(id int not null,
    	 idd int ,
    	 iddd int,
    	 foreign key (idd)
    	 references t(id))
    
    --通过约束名称来指定外键	 
    create table t2
    	(id int not null,
    	 idd int ,
    	 iddd int,	 
    	 constraint fk_wc1 --主表的主键是一个字段
    	 foreign key(iddd)
    	 references t(id),
    	 
    	 constraint fk_wc2 --主表的主键有2个字段,那么外键也必须有2个字段
    	 foreign key(id,idd) 
    	 references tt(id,idd))
    
    --递归外键,外键引用的是当前表的主键	 
    create table t3
    	(id int not null,
    	 idd int not null,
    	 
    	 constraint pk_wc3
    	 primary key clustered(id),  --主键
    	 
    	 constraint fk_wc4           --外键
    	 foreign key(idd)
    	 references t3(id))
    
    
    --允许外键的级联修改,就是当主表的记录删除或更新后,从表怎么处理
    create table t4
    	(id1 int ,
    	 id2 int ,
    	 id3 int ,
    	 id4 int default 0,
    	 
    	 constraint fk_wc5 
    	 foreign key (id1)
    	 references t(id)
    	 on delete no action    --当主表删除记录时,那么从表会报错
    	 on update no action,   --当主表更新记录时,那么从表会报错
    	 
    	 constraint fk_wc6 
    	 foreign key (id2)
    	 references t(id)
    	 on delete cascade      --当主表删除记录时,那么从表也删除
    	 on update cascade)     --当主表更新记录时,那么从表会删除
    
         /*
    	 constraint fk_wc7 
    	 foreign key (id3)
    	 references t(id)
    	 on delete set null    --当主表删除记录时,那么从表的记录会置为NULL
    	 on update set null),  --当主表更新记录时,那么从表的记录会置为NULL
    
    	 constraint fk_wc8 
    	 foreign key (id4)
    	 references t(id)
    	 on delete set default  --当主表删除记录时,如果从表设置了默认值,那么会置为默认值
    	 on update set default  --当主表更新记录时,从表的记录会置为默认值
    	 */
    	 )
    	 


    5、表变量

    表变量可以定义主键、唯一约束、check约束,但是不能加索引、外键。可以用在批处理、存储过程、函数中,之后不能有go,如果用了go,那么之后就不能在引用表变量了。


    6、约束

    --定义唯一约束后会自动创建一个唯一索引
    --在创建表时指定唯一约束
    create table tt(id int not null unique)
    
    --增加列时指定未命名的唯一约束
    alter table tt
    add idd int not null unique
    
    --增加列
    alter table tt
    add iddd int not null,
        idddd int not null
    
    --把增加的列定义为命名的唯一约束
    alter table tt
    add constraint uq_tt1 unique(iddd,idddd)
    


     

    --创建表时指定未命名check约束
    create table tt(id int not null check(id > 5 and id <=100))
    
    --增加列的同时指定check约束
    alter table tt
    add idd int not null check(idd >=100)
    
    --定义命名check约束,with check指定了在建立约束时要检查表中已经有的数据,
    --如果与此约束冲突,那么会报错,导致此约束建立失败
    alter table tt
    with check
    add constraint ck_tt check(id >=8 and idd >=120)
    
    --定义命名check约束,with check指定了在建立约束时不检查表中已经有数据,
    alter table tt
    with nocheck
    add constraint ck_ttt check(id >=8 and idd >=120)
    
    --禁用ck_ttt约束
    alter table tt
    nocheck constraint ck_ttt
    
    --这样才能插入记录
    insert into tt values(6,100)
    
    --启用约束
    --虽然刚才已经插入数据不符合ck_ttt约束,
    --但此时启用约束只对将要插入的数据有效
    alter table tt
    check constraint ck_ttt
    
    --禁用所有check、foreign key约束的检查
    alter table tt
    nocheck constraint all
    
    --启用所有check、foreign key约束的检查
    alter table tt
    check constraint all


     

    --创建表时指定未命名的default约束
    create table t(id int not null default 1)
    
    --增加列时指定约束
    alter table t
    add idd int not null default 2
    
    --增加列
    alter table t
    add iddd int not null
    
    --定义命名约束,注意:一个列上不能绑定2个default约束
    alter table t
    add constraint df_t 
    default 123 for iddd
    
  • 相关阅读:
    学习Python必须要会的知识,在字符串、列表、元组三者之间相互转换的方法
    python字符串中strip() 函数和 split() 函数的详解
    学习Python必须要知道的4个内置函数
    腾讯轻云服务器,如何使用Windows2016、2019
    jenkins 配置git选分支拉取代码
    查看mysql二进制文件(binlog文件)【报错+解决办法】
    apollo源码部署
    Maven镜像仓库替换为阿里云镜像仓库
    gitlab 日志相关
    gitlab本地搭建后用户(默认)头像不显示问题
  • 原文地址:https://www.cnblogs.com/momogua/p/8304631.html
Copyright © 2011-2022 走看看