I have a query which compares data in two tables:
SELECT DISTINCT
MT.Column1,
MT.Column2,
MT.Column5,
MT.Column7,
MT.Column9
FROM tblMyTable MT
WHERE
EntryDate >= @StartDate AND EntryDate <= @EndDate AND
NOT EXISTS (
SELECT ID FROM tblOtherTable
WHERE SomeString LIKE
'X' + CAST(MT.Column1 AS VARCHAR(16)) +
'Y' + CAST(MT.Column3 AS VARCHAR(16)) +
'Z' + CAST(MT.Column4 AS VARCHAR(16)) + '%'
)
It works OK. But when I'm trying to use CAST(var AS NVARCHAR), the query executes over 10 minutes and doesn't seem to finish in the nearest future. But when I change to CAST(var AS VARCHAR) as above, the query finishes in 2-3 seconds.
CASTed columns are defined as:
- Column1 int, not null,
- Column3 varchar(50), not null
- Column4 varchar(9),not null
but in fact all contain ONLY numbers, 9-15 digits in length
I wonder what could be the reason for such performance loss?
UPDATE:
Execution plan shows the folowing: