Compare two tables in SQL Server with exceptions -
i have 2 tables this
tableyesterday:
column1 column2 column3 column4 ------------------------------------------------------ john 5584 samsung 2017-08-31 23:43:06.867 bob 4512 apple 2017-08-31 23:43:06.867 hana 1881 nokia 2017-08-31 23:43:06.867 hanz 4866 alcatel 2017-08-31 23:43:06.867 nicol 48633 android 2017-08-31 23:43:06.867 ---gone tabletoday
column1 column2 column3 column4 ------------------------------------------------------ john 5584 samsung 2017-09-01 23:43:06.867 ---same entry bob 4542446 apple 2017-09-01 23:43:06.867 ---change in column2 hana 1881 halophone 2017-09-01 23:43:06.867 ---change in column3 hanz 4866 alcatel 2017-09-01 23:43:06.867 ---same entry mark 486654 alcatel 2017-09-01 23:43:06.867 ---new entry i need select today's changes , insert tableofchanges. these 2 rows have selected:
tableofchanges
bob 4542446 apple 2017-09-01 23:43:06.867 hana 1881 halophone 2017-09-01 23:43:06.867 i created queries, cannot include column4 in final select. however, if select/insert without column4, not see column4 in result:
insert tableofchanges select column1, column2, column3 [dbo].[tabletoday] except select column1, column2, column3 [dbo].[tableyesterday] tabletoday.column4 = tableyesterday.column4 or
insert [dbo].[tableofchanges] (column1, column2, column3, column4) select column1, column2, column3, column4 [dbo].[tableyesterday] (not exists (select column1, column2, column3, column4 [dbo].[tabletoday] ([dbo].[tableyesterday].column1 = column1) , ([dbo].[tabletoday].column1 = column1) , ([dbo].[tableyesterday].column2 = column2) , ([dbo].[tabletoday].column2 = column2) , ([dbo].[tableyesterday].column3 = column3) , ([dbo].[tabletoday].column3 = column3))) thank fix queries
you want records of today record same key different attributes exists in yesterday's data. supposing key column1, insert statement be:
insert tableofchanges select column1, column2,column3 dbo.tabletoday t exists ( select * tableyesterday y y.column1 = t.column1 , (y.column2 <> t.column2 or y.column3 <> t.column3 ); if column2 or column3 can null, you'll have adjust where clause this, because <> doesn't detect changes or null.
Comments
Post a Comment