So I have a query I've written that I thought was working, but just found out today that it isn't. The goal is to sync a user database on one SQL server with another on a MYSQL server so our web server can query it quicker than if it were trying to retrieve results from the SQL Server. The query in question is supposed to delete any user off of the MYSQL server if they are not found in the SQL server. I can take all the individual pieces of this query (deleting from the linked server, selecting the proper records from each table, verifying the non-existence of certain records, etc.), run them by themselves, and they work fine; however as soon as I put them together in this query, somehow the records I expect to get deleted are not.
DELETE WebADUsers
FROM OPENQUERY(ENET, 'SELECT * FROM ActiveDirectory.Users') AS WebADUsers
WHERE WebADUsers.EmployeeID NOT IN
(
SELECT u.[employeeID]
FROM [SGDB].[IT_ActiveDirectory].[dbo].[Users] u
)
So essentially a user with the ID '02681' exists on the MYSQL (ENET) server, but that EmployeeID does not exist in the SQL (SGDB) server. He is not getting deleted from the ENET server. I have tried accomplishing the same task by deleting myself out of the SGDB server, but the ENET record will persist after running this query with a result of "0 rows affected." I could have swore this query was working, but I guess not. Does anyone see what I'm doing wrong, or at least have a couple ideas for me to try? I'd really appreciate it.
Things I've tried:
Creating a subset of the OPENQUERY() and using that instead. It had no effect unsurprisingly. Example -
DELETE WebADUsers
FROM (SELECT * FROM OPENQUERY(ENET, 'SELECT * FROM ActiveDirectory.Users')) AS WebADUsers
WHERE WebADUsers.EmployeeID NOT IN
(
SELECT u.[employeeID]
FROM [SGDB].[IT_ActiveDirectory].[dbo].[Users] u
)
In this example I instead try to put everything into a temp table and then see if I could delete from the temp table with the same WHERE conditions. It successfully imports all the correct data, and the same user record we've been discussing is not in the SGDB server's user database, so it should work correctly and delete the user from the #tempad table... It doesn't though. Deletes 0 rows. Example 2 -
IF OBJECT_ID('tempdb..#tempad') IS NOT NULL
DROP TABLE #tempad
SELECT *
INTO #tempad
FROM OPENQUERY(ENET, 'SELECT * FROM ActiveDirectory.Users')
DELETE w
FROM #tempad w--OPENQUERY(ENET, 'SELECT * FROM ActiveDirectory.Users') AS WebADUsers
WHERE w.EmployeeID NOT IN
(
SELECT u.[employeeID]
FROM [SGDB].[IT_ActiveDirectory].[dbo].[Users] u
)