SQL Server比较具有相同列的两个表行并返回更改的列

时间:2022-10-18 10:19:46

I want to compare two tables with the same columns:

我想比较两个具有相同列的表:

  • product - Id, Name, Description
  • 产品 - ID,名称,描述

  • Temp_Product - Id, Name, Description
  • Temp_Product - Id,Name,Description

Now update done by user will be saved into Temp_Product. When admin will see the details of that product I need to show the changes done by user. I want to compare both tables with a query and return columns that have changed from Product to Temp_Product.

现在用户完成的更新将保存到Temp_Product中。当管理员看到该产品的详细信息时,我需要显示用户完成的更改。我想将两个表与查询进行比较,并返回已从Product更改为Temp_Product的列。

Please suggest me better way to do this?

请建议我更好的方法吗?

2 个解决方案

#1


2  

Select p.id,p.name as orgn,t.name as altn,p.descripion as orgd,t.description as altd
from product p
join tmp_product t
on t.id=p.id and (t.name<>p.name or t.description <> p.description)

#2


1  

I want to compare both tables with a query and return columns that have changed from Product to Temp_Product

我想将两个表与查询进行比较,并返回已从Product更改为Temp_Product的列

Since the two tables have the same structure, you can use the EXCEPT set oeprator for this:

由于这两个表具有相同的结构,因此您可以使用EXCEPT set oeprator:

SELECT * FROM Temp_Product
EXCEPT
SELECT * FROM Product;

SQL Fiddle Demo

#1


2  

Select p.id,p.name as orgn,t.name as altn,p.descripion as orgd,t.description as altd
from product p
join tmp_product t
on t.id=p.id and (t.name<>p.name or t.description <> p.description)

#2


1  

I want to compare both tables with a query and return columns that have changed from Product to Temp_Product

我想将两个表与查询进行比较,并返回已从Product更改为Temp_Product的列

Since the two tables have the same structure, you can use the EXCEPT set oeprator for this:

由于这两个表具有相同的结构,因此您可以使用EXCEPT set oeprator:

SELECT * FROM Temp_Product
EXCEPT
SELECT * FROM Product;

SQL Fiddle Demo