I have a query which compares the old database with new database on Customers table who belongs to a specific department and retrieves the difference between those database tables. I have a query as below
DECLARE @departmentid int = 2001
SELECT Distinct DB.[CUSTOMER_ID],DB.[CUSTOMER_AGE]
FROM [PROD\SQL01].[PRD_Live].[dbo].[Customers] DB
WHERE DB.[DEPARTMENT_ID]= @departmentid and
DB.[CUSTOMER_ID] NOT IN (SELECT Distinct [CUSTOMER_ID]
FROM [NEWPRD_Live].[dbo].[Customers]
WHERE [DEPARTMENT_ID]=@departmentid)
There are 40 departments id values (like 2001,2002,...,2040) that has to be set in the variable @departmentid and currently I am executing the above query by modifying the department id every time manually and executing the query for 40 times for 40 departments. Is it possible to set all the departments to a one variable and execute the query by setting each department id at a time in a loop and get all the results at a time?