1、说明:复制表(只复制表结构,源表名:sc 新表名 :d)
将一个表中的数据添加到一个新表里面
select * into d from sc;
将sc里面的数据放入到d表中,d表结构与sc表一样
2、拷贝表(拷贝数据,源表名:a ,目标表名:b)
insert into b(a,b,c) select d,e,f from a;
3、
Create table #MyTemplate(cola int primary key)
insert into #MyTemplate values(1)
4、select * into #myTb from table
临时表的说明:
临时表分为本地和全局临时表,本地临时表仅在当前会话中可见,全局临时表在所有会话中都可见
本地临时表的名称前面有一个编号符(#table_name),而全局临时表的名称前面有两个编号符(##table_name)
SQL语句使用Create Table语句中为table_name为引用临时表
除非使用Drop Table显示删除临时表,否则临时表将在退出其作用域时有系统自动删除
1、判断表是否存在
select * from sysobject where name='Test'
或者
IF EXISTS (SELECT * FROM dbo.SysObjects WHERE ID = object_id(N't') AND OBJECTPROPERTY(ID, 'IsTable') = 1)
PRINT '存在'
ELSE
PRINT'不存在'
或者
if object_id(N't',N'U') is not null
print '存在'
else
print '不存在'
2、判断临时表是否存在
临时表的信息放在tempdb数据库中,详细信息在tempdb.dbo.sysobjects(或者tempdb..sysobjects)
方法一、if object_id('tempdb.dbo.#tab') in not null
print 'yes'
else
print 'no'
方法二、
select 1 from tempdb.dbo.sysobjects where id=object_id('tempdb.dbo.#tab')
if exists(select 1 from tempdb.dbo.sysobjects where id=object_id('tempdb.dbo.#tab'))
或者
if exists(select * from tempdb.dbo.sysobjects where id=object_id('tempdb.dbo.#tab'))
PRINT '存在'
ELSE
PRINT'不存在'
或者
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb.dbo.#tab') and type='U')
PRINT '存在'
ELSE
PRINT'不存在'
临时表
declare @t table--临时表,只是执行一下
(id int)
insert into @t(id) values(1)
insert into @t(id) values(2)
insert into @t(id) values(3)
insert into @t(id) values(4)
select * from @t
select count(id) as '统计' from @t
select max(id) as '最大值' from @t
select sum(id) as '总和' from @t
3、判断数据库是否存在
方法一、 select * From master.dbo.sysdatabases where name='数据库名'
方法二、
if db_id('数据库名') is not null
drop database 。。。
go
create 。。。
四、
SQL Server中判断表中字段是否存在:
if exists
(select * from syscolumns where name='colname' and id=object_id('数据库名.架构.表名'))
print '存在'
else
print '不存在'
(代表表"表中"中是否存在colname字段 )
例:
select * from syscolumns where name='tDate' and id=object_id('dbo.test')
五、
SQL Server中判断存储过程或视图是否存在:
if object_id('视图或存储过程名') is not null
begin
drop proc/view
end
else
begin
create proc/view
end
或者
if Exists(select * from sysobjects where name='视图或存储过程名' AND type = 'P/V')
begin
drop proc/view
end
else
begin
create proc/view
end
其中p代表存储过程,v代表视图