3.1 SQL Server数据库表操作


 

数据库表操作

 

 

简介 本文主要讲了针对数据库表创建、删除、修改表字段的T-SQL方式

1.创建表

  use [SampleDb] -- 在创建表时,先使用一下当前想要的数据库
  -- 创建表
  -- create:创建
  -- table :表
  -- Student:表的名称
  create table Student
  (
  Id int, -- 学生编号
  Nickname varchar(20), -- 姓名
  Mobile char(11), -- 手机号
  Email varchar(30) -- 邮箱
  );

2.修改表

添加字段

  -- alter:修改
  -- add:添加
  -- 添加字段的语法:
  -- alter table 表
  -- add 字段 字段类型
  alter table Student
  add Sex bit -- 添加性别字段
  -- 添加年龄 Age: tinyint
  alter table Student
  add Age tinyint
  -- 批量添加字段
  --alter table Student
  --add 字段1 字段类型,字段2 字段类型

修改字段

  -- 修改字段类型语法
  -- column:列
  -- alter table 表名
  -- alter column 要修改的字段 新的字段类型
  -- 将Sex字段修改为 varchar(10)
  alter table Student
  alter column Sex char(4)

删除字段

  -- alter table 表名
  -- drop column 字段名
  -- 删除Email 这个字段
  alter table Student
  drop column Email

3.重命名

  - 将NickName的名称修改为:StudentName
  exec sp_rename
  'Student.NickName', -- 需要修改的字段名称,注意要指定字段所在的表
  'StudentName', -- 新的字段名
  'column' -- 表示删除的是列,字段
  -- 修改表名
  -- 将Student 表名 修改为 StudentInfo
  exec sp_rename
  'Student', -- 需要修改的表的名称
  'StudentInfo' -- 新的表名

4.删除表

  -- drop table <表名>
  drop table StudentInfo

5.Identity关键字

  create table Student
  (
  Id int identity, -- 学生编号,identity:默认是从1开始自增,每次增加1
  -- Id int identity(2,3) Id从 2 开始自增,每次自增3
  Nickname varchar(20), -- 姓名
  Mobile varchar(11), -- 手机号
  Email varchar(30) -- 邮箱
  );

Identity 自增主键,可以为数据表简单的解决数据“原子性”问题,但是有如下几个缺点:

  1. 如果删除数据后,identity 自增种子会断片,不连续
  2. 不能应对分布式系统,可能会造成数据不一致性。
 
分类: SQL Server
标签: SQL Server , 数据库

posted on 2025-04-21 11:44  漫思  阅读(28)  评论(0)    收藏  举报

导航