SQL Server Compare 2 tables in 2 databases

hxzsmxv2  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(109)

I'm trying to compare 2 table that have all the same columns in them in 2 different databases. The databases are on the same machine, and this is all in SQL database. I'm trying to retun results from table 2 that do not exist in table 1. The important column is called Stock.

Lets assume the names as are follows. DB1 and DB2 as the 2 databases. The table name for both is Vendor THe column is Stock

If I use this example I get no results

Select * From DB2.Vendor
Where (Stock != Stock)
Except 
Select * From DB1.Vendor

Second Idea (this gives me an error)

Select * From DB2.Vendor
Union 
Select * From DB1.Vendor
Group by Vendor.Stock

If you have a diffrent suggestion great Thanks in advance.

tnkciper

tnkciper1#

You can Left join or Exists

Left join

select a.*
from TestDB2.dbo.Vendor a
left join  TestDB1.dbo.Vendor b on a.Stock=b.Stock 
where b.Stock is  null

Exists

select *
from TestDB2.dbo.Vendor a
where  not exists (select * from TestDB1.dbo.Vendor b where  a.Stock=b.Stock )

相关问题