I have two local and remote databases with one way access from local to remote. and we can only insert and update remote database from local database. I wrote a merge query but couldn't EXEC at remote because the remote database cannot access to source database so I want to convert it to insert and update commands. If there is a row in remote Database, it should be updated and if it does not exist, it should be inserted
My Merge code is
MERGE INTO [RemoteIp].[dbname].[dbo].[MTest] AS [Target]
USING (SELECT * FROM [dbo].[Products]
) AS [Source] ([ProductID],[ProductName],[Rate])
ON ([Target].[PID] = [Source].[ProductID])
WHEN MATCHED AND (
NULLIF([Source].[ProductID], [Target].[PID]) IS NOT NULL OR NULLIF([Target].[PID], [Source].[ProductID]) IS NOT NULL OR
NULLIF([Source].[ProductName], [Target].[ProductName]) IS NOT NULL OR NULLIF([Target].[ProductName], [Source].[ProductName]) IS NOT NULL OR
NULLIF([Source].[Rate], [Target].[Rate]) IS NOT NULL OR NULLIF([Target].[Rate], [Source].[Rate]) IS NOT NULL) THEN
UPDATE SET
[Target].[PID] = [Source].[ProductID],
[Target].[ProductName] = [Source].[ProductName],
[Target].[Rate] = [Source].[Rate]
WHEN NOT MATCHED BY TARGET THEN
INSERT([PID],[ProductName],[Rate])
VALUES([Source].[ProductID],[Source].[ProductName],[Source].[Rate]);
I Try This For Insert and Update
IF EXISTS(SELECT * FROM [RemoteIP].[DBName].[db].[Mtest])
BEGIN
--update existing row
UPDATE
[RemoteIP].[DBName].[db].[Mtest]
SET
[RemoteIP].[DBName].[db].[Mtest].pid = products.ProductID,
[RemoteIP].[DBName].[db].[Mtest].ProductName = products.ProductName,
[RemoteIP].[DBName].[db].[Mtest].Rate = products.Rate
FROM
Mtest tr INNER JOIN products sr
ON tr.pid = sr.ProductID
END
ELSE
BEGIN
--insert new row
INSERT INTO [RemoteIP].[DBName].[db].[Mtest] (pid, ProductName, Rate)
VALUES ([products].[ProductID], [products].[ProductName], [products].[Rate])
I get this error when run my query in
The multi-part identifier …… could not be bound in line 4
The next step is to check the syntax of the UPDATE
command. Once you aliased [RemoteIP].[DBName].[db].[Mtest]
as tr
, there is no more [RemoteIP]....
within the scope of the command. There is only tr
. Try this:
UPDATE
tr
SET
pid = sr.ProductID,
ProductName = sr.ProductName,
Rate = sr.Rate
FROM
[RemoteIP].[DBName].[db].[Mtest] tr INNER JOIN products sr
ON tr.pid = sr.ProductID