05Microsoft SQL Server 表创建,查看,修改及删除

Microsoft SQL Server 表创建,查看,修改及删除


创建表

创建普通表

use 数据库名称
go
create table 表名称(
列1 char(10) not null,
列2 varchar(8) not null,
列3 char(2) not null,
列4 varchar(30),
列5 smalldatetime not null,
列6 text)
Go

复制表结构

select * into ta3 from ta1 where 1<>1;

select top 0 * into tb4 from ta1;

 创建临时表

--临时表就是那些名称以井号 (#) 开头的表。如果当用户断开连接时没有除去临时表,SQL Server 将自动除去临时表。临时表不存储在当前数据库内,而是存储在系统数据库 tempdb 内。

--本地临时表 以一个井号 (#) 开头的那些表名只能被当前登录用户使用

create table #临时表名(
字段1 约束条件,
字段2 约束条件)
go

--全局临时表 以两个井号 (##) 开头的那些表名因此通常情况下,只要创建全局临时表的连接断开,全局临时表即被除去。

create table ##临时表名(
    字段1 约束条件,
    字段2 约束条件)
go

查看表

查看数据库中的所有表

select * from sysobjects where xtype='u' order by name asc

--查询数据库的所有表信息

select * from sysobjects where type='U';

--列出表里的所有的列名

select * from syscolumns where id = object_id('ta1');

--查询数据库表数据条数

select

    distinct a.name AS 表名,b.rows AS 数据行数

from sys.objects a,sysindexes b

where a.object_id=b.id and a.type='u'and b.rows = 0;

修改表

修改表名称

EXEC sp_rename 'oldname', 'newname';

修改表添加列

use 数据库名称

go

alter table 表名称

    add 列名称 数据类型

go

修改表修改列

use 数据库名称

go

alter table 表名称

    alter column 列名称 数据类型

go

修改表删除列

use 数据库名称

go

alter table 表名称

    drop column 列名称

go

删除表

use 数据库名称

go

Drop table 表名称

Go

--删除数据库的空表

select

    'drop table ' + a.name + ';'

    from sys.objects a,sysindexes b

where a.object_id=b.id and a.type='u' and b.rows = 0;

 

SELECT 'drop table '+ name+';'

FROM sys.objects

WHERE name NOT IN ( SELECT DISTINCT

 a.name

 FROM sys.objects a ,

 sysindexes b

 WHERE a.object_id = b.id

 AND b.rows > 0 )

 AND type = 'u';


 

 

转载于:https://www.cnblogs.com/Aha-Best/p/10857446.html

你可能感兴趣的:(05Microsoft SQL Server 表创建,查看,修改及删除)