0

我在我的数据仓库表中插入记录时遇到问题。我有一个代理键,它为每条记录创建自动递增 1。我收到错误消息:

只有在使用列列表并且 IDENTITY_INSERT 为 ON 时,才能为表“TARGET”中的标识列指定显式值

下面的代码片段:

INSERT INTO [DW_Table] (Valid_Start_Date, Valid_End_Date, Current_Flag, Col1, Col2, Col3) 
  SELECT
   Getdate() AS Valid_Start_Date, NULL AS Valid_End_Date, 1 as Current_Flag, Col1, Col2,Col3
  FROM (
    MERGE INTO [DW_Table] AS TARGET
    USING ([Base_Table]) AS SOURCE
    ON ( SOURCEC.Account_Key = TARGET.Account_Key
         AND TARGET.Current_Flag = 1)
    WHEN MATCHED .................................

我已经尝试列出这些字段,因为我知道问题在于尝试将记录插入到自动递增字段中。我已将其作为“使用”基表行的一部分完成,但仍然出现错误。

有人可以给我一些指示吗?

谢谢

4

2 回答 2

0

尝试这样的事情:

use tempdb
go
drop table if exists dw_table
drop table if exists dw_table_stg 

create table DW_Table
(
  Id int identity, 
  Valid_Start_Date date, 
  Valid_End_Date date, 
  Current_Flag bit, 
  Account_Key int , 
  constraint uk_account_current unique (Account_Key, Current_Flag),
  Col1 int, 
  Col2 int, 
  Col3 int
)

insert into DW_Table (Account_Key,Col1, Col2, Col3, Current_Flag) 
       values (1,2,3,4,1),(2,2,3,4,1),(3,2,3,4,1)

go


declare @DW_Table_stg table( Account_Key int primary key, Col1 int, Col2 int, Col3 int)

insert into @DW_Table_stg (Account_Key,Col1, Col2, Col3) values (1,2,5,12)

insert into [DW_Table] 
     ( Account_Key, Valid_Start_Date, Valid_End_Date, Current_Flag, Col1, Col2, Col3) 
select Account_Key, Getdate(),        NULL,           1,            Col1, Col2, Col3
from 
(
    merge into [DW_Table] AS t
    using @DW_Table_stg AS s
    ON ( s.Account_Key = t.Account_Key )
    when matched and t.Current_Flag = 1 and checksum(s.Col1,s.Col2,s.Col3) <> checksum(t.Col1,t.Col2,t.Col3)
         then update set t.Current_flag = 0, t.Valid_End_Date = getdate()
    when not matched 
         then insert  (Valid_Start_Date, Valid_End_Date, Current_Flag,Account_Key,    Col1,   Col2,   Col3) 
         values       (getdate(),        null,           1,           s.Account_Key,s.Col1, s.Col2, s.Col3)
    output $action [ActionType], s.*
) d
where [ActionType] = 'UPDATE'

select *
from DW_Table
order by current_flag desc, Account_key
于 2019-09-10T14:15:00.967 回答
0

根据提供的代码片段,以下是您的错误消息试图做出的引用...

TARGET = [DW_TABLE]
COLUMNS = (Valid_Start_Date, Valid_End_Date, Current_Flag, Col1, Col2, Col3)

这意味着 DW_TABLE 中列出的列之一被定义为 IDENTITY KEY,因此您的 INSERT 语句不应为其指定值。

你能分享完整的合并查询和 DW_TABLE 的列定义吗?

此外,连接键显示“SOURCEC”而不是“SOURCE”。这只是一个错字吗?

于 2019-09-16T19:06:27.007 回答