I am trying to Merge 2 tables (imported from another server) using ROW_NUMBER because I only want the most current Update. Using Left Join because there may not be a match in Right table. I know what the error means but have not been able to figure out how to fix it.I get the error in the 'SET' & 'INSERT' commands.The error I get is:Msg 4104, Level 16, State 1, Line xxThe multi-part identifier "E2.HomeEmail" could not be bound.
MERGE EMPLOYEE AS EM USING (Select T.EID, T.Col2, T.COL3, T.DateChanged, E2.HomeEmail from (Select EID, Col2, Col3, DateChanged, ROW_NUMBER() OVER(PARTITION BY EID ORDER BY DateChanged DESC) AS RowNum from TEMPTABLE) AS T left join EMPLMAIL AS E2 on T.EID = E2.EID where DateChanged >= dateadd(day,datediff(day,0,getdate())-1,0) and RowNum = 1) AS i ON (EM.EID = i.EID) WHEN MATCHED THEN UPDATE SET EM.Col1 = i.Col1, EM.Col2 = i.Col2, EM.HomeEmail = (CASE when E2.HomeEmail is NULL then '' else E2.HomeEmail END), EM.DateChanged = i.DateChanged WHEN NOT MATCHED THEN INSERT (EID, Col1, Col2, HomeEmail, DateChanged) VALUES (i.EID, i.Col1, i.Col2, (CASE when E2.HomeEmail is NULL then '' else E2.HomeEmail END), i.DateChanged) ;
TEMPTABLE Table - ImportedEID intCol1 char(2)Col2 char(2)DateChanged datetimeDATA:1234 'AA' 'ZZ' 2011-01-05 10:48:10.0001234 'AA' 'ZZ' 2011-01-05 12:48:10.6133333 'NN' 'XX' 2011-01-05 12:48:10.6135555 'QQ' 'BB' 2011-01-05 12:48:10.6137878 'YY' 'YY' 2011-01-05 12:48:10.613EMPLMAIL Table - ImportedEID intHomeEmail char(50)DATA:1234 'Mine@email'3333 NULL7878 'Your@email'RESULTS:EMPLOYEE TableEID intCol1 char(2)Col2 char(2)HomeEmail char(50)DateChanged datetimeDATA:1234 'AA' 'ZZ' 'Mine@email' 2011-01-05 12:48:10.6133333 'NN' 'XX' [BLANKS] 2011-01-05 12:48:10.6135555 'QQ' 'BB' [BLANKS] 2011-01-05 12:48:10.6137878 'YY' 'YY' 'Your@email' 2011-01-05 12:48:10.613Thanks.Forgot to mention that when I pull the 'Select' statements out of the MERGE it returns the desired results in Microsoft SQL Server Management Studio.