Home [SQL] Select...Into (將資料放到暫存資料表中)
Post
Cancel

[SQL] Select...Into (將資料放到暫存資料表中)

Select Into

SELECT…INTO 用來從某資料表查詢所得之資料集結果新增到另一個新建的資料表中。此一指令常用來複製備份資料表,或將資料表輸出至另一資料庫中。

語法

Copy all columns into a new table

可以複製所有的Columns(列)插入到新表中

1
2
3
4
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

其中 newtable 為欲新建的資料表名稱,該資料表會自動建立,且不可與已經存在的資料表名稱相同;而 externaldb 為至外部資料庫的路徑。

Copy only some columns into a new table

或者只複製希望的Columes(列)插入到新表中

1
2
3
4
SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

範例1

取得群組名稱為「周邊設備」之商品的商品id、商品名稱,並放到暫存資料表「#周邊設備」當中

1
2
3
4
5
--取得群組名稱為「周邊設備」之商品的商品id、商品名稱,並放到暫存資料表「#周邊設備」當中
select 商品ID,商品名稱 
into #周邊設備
from 商品清單
where 群組名稱 = '周邊設備'

確認暫存表是否存在&執行結果:select * from #周邊設備
暫存資料表的位置: 系統資料庫 > tempdb > 暫存資料表
刪除暫存表:drop table #周邊設備 (DROP TABLE #Table_name)

範例2

統計2006/4的商品別販賣數量,並將其結果存到暫存表「#商品別販賣數量」當中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
--統計2006/4的商品別販賣數量,並將其結果存到暫存表「#商品別販賣數量」當中
select 商品ID, sum(數量) "數量"
into #商品別販賣數量 --將其結果存到暫存表
from 販賣資料
where 處理日 between '2006-04-01' and '2006-04-30'
group by 商品ID

--先將統計的資料select出來,再加上into #table_name
/*
select 商品ID,sum(數量) "數量"
from 販賣資料
where 處理日 between '2006-04-01' and '2006-04-30'
group by 商品ID
*/

執行結果:

1
2
3
4
5
6
7
8
select * from #商品別販賣數量

商品ID	數量
1	5
2	1
4	3
7	1
8	1

暫存表指定的三種方式 ###tempdb

  1. select ... into #table_name:區域暫存資料表
  2. select ... into ##table_name:全域暫存資料表
  3. select ... into tempdb.. table_name:在 tempdb中製作新資料表 (* 只能用在有對tempdb寫入權限時)
    (* tempdb 為系統資料庫)

#Table 區域暫存表

select ... into #table_name:區域暫存資料表

在資料表前方加上「#」後,就代表是區域暫存資料表。
區域暫存資料表只在該 Session(工作階段)內有效。當Session被切斷之後,該暫存表就會自動刪除。

##Table 全域暫存表

select ... into ##table_name:全域暫存資料表

在資料表前方加上「##」後,就代表是全域暫存資料表。
全域暫存資料表可以被多個 Session(工作階段)所共享,當參照全域暫存資料表的「最後一個Session」被切斷時,該暫存表就會被自動刪除。(所有Session皆可以使用,所有的Session結束時才會自動刪除)

tempdb 系統資料庫中

select ... into tempdb.. table_name:在 tempdb中製作新資料表
(* 只能用在有對tempdb寫入權限時)
(* tempdb 為系統資料庫)

在資料表前方加上「tempdb..」後,就會在tempdb資料庫內製作資料表,這個資料表在你執行刪除指令,或是SQL SERVER再啟動前,都會持續存在。

MSDN - SELECT - INTO 子句 (Transact-SQL)
w3schools - SQL SELECT INTO Statement
Fooish - Select Into

This post is licensed under CC BY 4.0 by the author.