July 23, 2014 at 7:38 pm
Hello,
Can we insert into multiple table using merge statement ? If not then what are the alternatives ... please suggest.
I'm using SQL Server 2008 R2 and below is my MERGE query... can somebody kindly let me know where am I going wrong.
Problem:
-> I'm checking if the record exist in Contact table or not. If it exist then I will insert into employee table else I will insert into contact table then employee table.
WITH Cont as
( Select ContactID from Contact where ContactID=@ContactID)
MERGE Employee as NewEmp
Using Cont as con
ON NewEmp.ContactID=NewEmp.EmployeeID
When NOT Matched
THEN
--1st insert into Contact table
INSERT ([ContactID],[NameStyle] ,[Title],[FirstName],[MiddleName],[LastName],[Suffix],[EmailAddress]
,[EmailPromotion],[ModifiedDate])
VALUES (@ContactID,@NameStyle,@Title,@FirstName,@MiddleName ,@LastName,@Suffix,@EmailAddress,@EmailPromotion
,@ModifiedDate)
--2nd insert into Employee table
INSERT ([EmployeeID],[NationalIDNumber],[ContactID],[LoginID] ,[ManagerID],[JobTitle],[BirthDate]
,[MaritalStatus],[Gender],[HireDate],[SalariedFlag],[VacationHours],[SickLeaveHours],[CurrentFlag]
,[ModifiedDate] )
VALUES (@EmployeeID,@NationalIDNumber,@ContactID,@LoginID,@ManagerID,@JobTitle,@BirthDate,@MaritalStatus
,@Gender,@HireDate,@SalariedFlag,@VacationHours,@SickLeaveHours,@CurrentFlag,@ModifiedDate)
When Matched
THEN --Insert in Employee table only
INSERT ([EmployeeID],[NationalIDNumber],[ContactID],[LoginID] ,[ManagerID],[JobTitle],[BirthDate]
,[MaritalStatus],[Gender],[HireDate],[SalariedFlag],[VacationHours],[SickLeaveHours],[CurrentFlag]
,[ModifiedDate] )
VALUES (@EmployeeID,@NationalIDNumber,@ContactID,@LoginID,@ManagerID,@JobTitle,@BirthDate,@MaritalStatus
,@Gender,@HireDate,@SalariedFlag,@VacationHours,@SickLeaveHours,@CurrentFlag,@ModifiedDate)
;
July 23, 2014 at 10:32 pm
Problem:
-> I'm checking if the record exist in Contact table or not. If it exist then I will insert into employee table else I will insert into contact table then employee table.
Re-reading your question, I don't think MERGE is what you want. As I understand it, your logic should be really simple:
IF NOT EXISTS (SELECT 1 FROM Contact WHERE SomeField = @SomeValue)
BEGIN
INSERT INTO Contact(fieldlist) VALUES (valuelist);
END
INSERT INTO Employee(fieldlist) VALUES (valuelist);
July 24, 2014 at 1:02 am
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply