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'))
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb.dbo.#tab') and type='U')
臨時表
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
create proc/view
或者
if Exists(select * from sysobjects where name='視圖或存儲過程名' AND type = 'P/V')
drop proc/view