当我运行它时,我不断得到:
消息 515,级别 16,状态 2,第 8 行
无法将值 NULL 插入列“uNSID”,表“Flickr.dbo.User_Grps”;列不允许空值。更新失败。
该语句已终止。
这是我的 SQL 语句:
MERGE
INTO User_Grps as ug
USING [ExcImport-S2 (3)] as i
ON (
ug.uNSID = i.uNSID
and ug.prime_ID = i.prime_ID
and i.uNSID is not null
)
WHEN MATCHED and i.uNSID is not null THEN
UPDATE SET ug.uNSID = i.uNSID
, ug.gNSID = i.gNSID
, ug.gAlias = isnull(i.gAlias,ug.gAlias)
, ug.Prime_ID = i.Prime_ID
WHEN NOT MATCHED THEN
INSERT (uNSID
, gNSID
, gAlias
, Prime_ID
)
VALUES (i.uNSID
, i.gNSID
, i.gAlias
, i.Prime_ID
);
GO
我需要做些什么来阻止它吸入空记录?
另外,我将如何配置计数器以便最后我可以得到类似的东西Updated x,xxx records & added xxx
?
编辑添加 --------------
@Kevin:这是我修改后的代码,因为我理解了您的回复。
当我按原样运行它时,我收到以下错误:
Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '$ACTION'.
Msg 137, Level 15, State 1, Line 5 Must declare the scalar variable "@InsertCount".
Msg 1087, Level 15, State 2, Line 9 Must declare the table variable "@RowCounts".
当我注释掉行之间的部分时-- ############################################
,我收到以下错误:
Msg 2627, Level 14, State 1, Line 13 Violation of PRIMARY KEY constraint 'PK_User_Grps'. Cannot insert duplicate key in object 'dbo.User_Grps'. The duplicate key value is (GT10464608)
SET NOCOUNT ON ;
DECLARE @RowCounts TABLE
(
MergeAction NVARCHAR(10)
) ;
DECLARE @InsertCount INT ,
@UpdateCount INT;
Merge
into User_Grps as ug
using [ExcImport-S2] as i
on (
ug.uNSID = i.uNSID
and ug.prime_ID = i.prime_ID
and i.uNSID is not null
)
WHEN MATCHED THEN
UPDATE SET ug.gNSID = i.gNSID
, ug.gAlias = isnull(i.gAlias,ug.gAlias)
, ug.last_ud = GETDATE ( )
WHEN NOT MATCHED THEN
-- UPDATE SET @i += 1;
INSERT (uNSID
, gNSID
, gAlias
, Prime_ID
, Last_UD
)
VALUES (i.uNSID
, i.gNSID
, i.gAlias
, i.Prime_ID
, GETDATE ( )
);
-- ############################################
OUTPUT