简体   繁体   中英

Getting an error when trying to merge missing items between two databases on SQL Server 2005

So, kind of an SQL Newbie here and I am trying to get something to work on Microsoft SQL Server 2005 (yay for old outdated databases powering businesses still).

I can get it to work properly on my local dev machine (running SQL Server 2019) but when I run it on the 2005 server it errors out.

Query:

MERGE CustomDB.[dbo].StockCounts AS [Target] 
USING (SELECT ID, 
              ProductNo 
       FROM   CompanyDBReplication.[dbo].STOCKPRODUCT) AS [Source] (ID, 
      ProductNo) 
ON [Target].ID = [Source].ID 
WHEN NOT MATCHED THEN 
  INSERT (id, 
          ProductNo, 
          CountDate, 
          CountID) 
  VALUES ([Source].ID, 
          [Source].ProductNo, 
          NULL, 
          NULL); 

Error:

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near '.'.  
Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'AS'.

Now I don't know enough about the differences here of why this would error out nor how I would go about searching this (I really don't do SQL ever and sort of had to Google this to make it work in the first place).

Basically I want to copy/merge items from a source database into the target database and add new ones that might get added to the source if they are not found in the target.

If someone can help me either fix this one to work on SQL Server 2005 or propose/give me an example of a different solution that will accomplish the same thing and work on SQL Server 2005 that would be awesome and I would forever be indebted.

The source of where I got this solution is here: https://stackoverflow.com/a/34892729/5877943

Merge statement appeared only in MSSQL 2008, you can use an outer join instead. Something like this.

INSERT INTO CustomDB.[dbo].StockCounts (
    id, 
    ProductNo, 
    CountDate, 
    CountID
)
SELECT        
    [Source].ID, 
    [Source].ProductNo, 
    NULL, 
    NULL
FROM CompanyDBReplication.[dbo].STOCKPRODUCT) AS [Source]
LEFT JOIN CustomDB.[dbo].StockCounts AS [Target] ON [Target].ID = [Source].ID
WHERE [TARGET].Id IS NULL;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM