SELECT…INTO 在 SQL Server 中也是常見的一個功能,過去用此方法創建的新表只能存儲到默認的文件組,但是?SQL Server 2017 可以創建到指定的文件組中。
使用?SELECT…INTO 需要了解的地方:
SELECT...INTO 為大容量操作,大容量操作是最小日志記錄操作;
使用 SELECT... INTO 語句可以是比創建表,然后填充具有 INSERT 語句的表更高效;
啟用事務復制時,將完全記錄 SELECT INTO 操作,即使處于大容量日志恢復模式下;
不能使用 SELECT…INTO 創建分區表;
SELECT...INTO 不使用源表的分區方案;
源表中定義的索引、約束和觸發器不會轉移到新表中;
指定 ORDER BY 子句無法確保按指定順序插入行;
稀疏列屬性不會轉移到新表中的列;
當選擇列表中包含計算列時,新表中的相應列并不是計算列;
在選擇現有標識列并將其插入到新表時,新列將繼承 IDENTITY 屬性;除非以下條件中的一個為真,列將被創建為 NOT NULL 而不繼承 IDENTITY 屬性:
1. SELECT 語句包含一個聯接。
2. 多個 SELECT 語句由 UNION 聯接。
3. 標識列在選擇列表內多次列出。
4. 標識列是表達式的一部分。
5. 標識列來自遠程數據源。
測試?SELECT…INTO 創建的新表指定到文件組:
--創建測試數據
use master
go
create database Demo
go
use Demo
go
create table Test(
id int not null identity(1,1),
userName varchar(50),
addTime datetime constraint df_addtime default(getdate())
) on [primary]
go
--插入100行數據
set nocount on
insert into Test(userName) select 'kk'+convert(varchar(10),@@identity)
go 100
set nocount off
go--創建文件組及文件
alter database Demo add filegroup fg;
go
alter database Demo
add file
(name='fg_data',filename = 'D:\SQLServer\Data2017/Demo1.mdf'
)
to filegroup fg;
go--注意:SELECT…INTO 創建的新表指定到文件組
select *
into newTest on fg
from Test
go--查看結果:
SELECT tbl.name AS TableName,fg.name AS [FileGroupName],CAST(p.rows AS float) AS [RowCount]
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and (idx.index_id < 2 or (tbl.is_memory_optimized = 1 and idx.index_id = (select min(index_id) from sys.indexes where object_id = tbl.object_id)))
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int) AND p.index_id=idx.index_id
LEFT OUTER JOIN sys.destination_data_spaces AS dds ON dds.partition_scheme_id = idx.data_space_id and dds.destination_id = p.partition_number
LEFT OUTER JOIN sys.filegroups AS fg ON fg.data_space_id = dds.data_space_id or fg.data_space_id = idx.data_space_id
WHERE (p.partition_number=1)
go
參考:?https://docs.microsoft.com/zh-cn/sql/t-sql/queries/select-into-clause-transact-sql