tb1
need to have some coluna
which refers to tb2
, even if this is not a constraint
(a.ka. foreign key
).
So let’s say tb1
have the column tb2_id
what reference tb2_id
in tb2
, you can do so.:
SELECT *
FROM TB1
WHERE NOT EXISTS(SELECT tb2_id FROM tb2 WHERE TB1.tb2_id = tb2.tb2_id)
You can also try.:
SELECT TB1.*
FROM TB1
LEFT JOIN tb2 ON TB1.tb2_id = tb2.tb2_id
WHERE tb2.tb2_id IS NULL
And finally another alternative.:
SELECT *
FROM TB1
WHERE tb2.tb2_id NOT IN (SELECT tb2_id FROM tb2)
In terms of performance, the LEFT JOIN
with IS NULL
should be the slowest, the difference between the NOT IN
and the NOT EXISTS
should be marginal. I would stick with the NOT EXISTS
for being semantically closer to what it aims to do.
And in case you don’t have one indice
for tb2_id
in tb1
, I advise you to create one, because the NOT EXISTS
will be greatly affected by the absence of a.
You can read more on.: Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
EDIT
As you are using a Linked server, try using the OPENQUERY command to query its data.
DECLARE @QUERY_QDE AS NVARCHAR(MAX)
SET @QUERY_QDE = N'SELECT C.[CHAMADO], , C.[COLUNA_1], C.[COLUNA_2], ..., C.[COLUNA_N] FROM [dbo].[TB_QDE_CHAMADO] C';
SELECT CHAMADO_QDE.*
FROM OPENQUERY([XXX.XXX.XXX.XXX], @QUERY_QDE) AS CHAMADO_QDE
WHERE NOT EXISTS (
SELECT CHAMADO_AXA.[CHAMADO]
FROM [_dbAXA].[dbo].[TB_QDE_CHAMADO] AS CHAMADO_AXA
WHERE CHAMADO_QDE.[CHAMADO] = CHAMADO_AXA.[CHAMADO]
)
In this case, you will need to specify all columns in your query, because the OPENQUERY
doesn’t understand a wildcard.
Finally, [XXX.XXX.XXX.XXX]
is the address of your LINKED SERVER
One detail I forgot to mention, is that tb1 comes from Linked server
– Diego Pozzolini
Is there any key to connect the two tables ?
– Motta
I recommend reading: Not IN or Not EXISTS which to use?
– Marconi
there is the field [Called] a unique number, but when I try to use it has error
– Diego Pozzolini