When I run this, I keep getting:
Msg 515, Level 16, State 2, Line 8
Cannot insert the value NULL into column 'uNSID', table 'Flickr.dbo.User_Grps'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
This is my SQL statement:
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
What do I need to do to stop it from sucking in the null records?
Also, how would I configure counters so at the end I can get something like Updated x,xxx records & added xxx
?
Edit to add --------------
@Kevin: This is my code after I modified it as I understood your response.
When I run it as is, I get the following errors:
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".
When I comment out the part between the -- ############################################
lines, I get the following error:
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