https://jonesyeh.wordpress.com/2014/01/20/set-identity_insert-tablename-on%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A0%85/
–step 1:建立暫存資料表
CREATE TABLE [#tp](
[user_seq] [int] IDENTITY(1,1) NOT NULL,
[user_id] [varchar](10) NOT NULL,
[user_name] [nvarchar](30) NOT NULL,
[org_key] [varchar](10) NULL,
[org_relation_seq] [int] NULL,
[org_path] [varchar](255) NULL,
[org_path_desc] [nvarchar](255) NULL,
[user_type_key] [varchar](10) NULL,
[job_key] [varchar](10) NULL,
[level_key] [varchar](10) NULL,
[code_group_key] [varchar](10) NOT NULL,
[code_group_type_key] [varchar](10) NOT NULL,
[position_date] [date] NULL,
[begin_time] [datetime2](7) NOT NULL,
[end_time] [datetime2](7) NULL,
PRIMARY KEY NONCLUSTERED
(
[user_seq] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
–step2:從實體資料表匯入到暫存資料表
insert into [#tp]
select * from [comm].[tb_user_dim]
–執行失敗(位於資料表 ‘#tp’ 的識別欄位其外顯值只有當使用了資料行清單且 IDENTITY_INSERT 為 ON 時才能指定。)
–step3:設定IDENTITY_INSERT=ON
set IDENTITY_INSERT [#tp] ON
–step4:從實體資料表匯入到暫存資料表
insert into [#tp]
select * from [comm].[tb_user_dim]
–執行失敗(位於資料表 ‘#tp’ 的識別欄位其外顯值只有當使用了資料行清單且 IDENTITY_INSERT 為 ON 時才能指定。)
–從以上語法還是會失敗,原因是insert into 的資料表需要指定資料行名稱
–step5 修改insert into語法
set IDENTITY_INSERT [#tp] ON
insert into [#tp]
([user_seq]
,[user_id]
,[user_name]
,[org_key]
,[org_relation_seq]
,[org_path]
,[org_path_desc]
,[user_type_key]
,[job_key]
,[level_key]
,[code_group_key]
,[code_group_type_key]
,[position_date]
,[begin_time]
,[end_time])
select * from [comm].[tb_user_dim]
–(862 個資料列受到影響)
drop table [#tp]