I have a query optimization problem. Say there is a table in which there are all invoices. Using TVP (Table Valued Parameter) I would like to select multiple records by providing 1..n identifiers or return all records by providing a single identifier with a value of -1.
DECLARE @InvoiceIdSet AS dbo.TBIGINT;
INSERT INTO @InvoiceIdSet VALUES (1),(2),(3),(4)
SELECT TOP 100
I.Id ,
Number ,
DueDate ,
IssuedDate ,
Amount ,
Test3
FROM dbo.Invoices I
JOIN @InvoiceIdSet S ON S.ID = I.Id OR S.ID=-1
Regardless of which selection method I use, the query is fairly efficient until I start using the OR operator, and at that moment it starts to take a very long time to return a few records, but all records are returned very quickly.
Any pointers and suggestions would be highly appreciated.


The first plan is without OR, the second is with OR.
UPDATE:
, .
UserDefinedTableType, :
CREATE TYPE [dbo].[TBIGINT] AS TABLE(
[ID] [bigint] NOT NULL PRIMARY KEY CLUSTERED
)
select :
SELECT TOP 100
I.Id ,
Number ,
DueDate ,
IssuedDate ,
Amount ,
Test3
FROM dbo.Invoices I
WHERE I.ID IN ( SELECT S.ID
FROM @InvoiceIdSet S
WHERE S.ID <> -1
UNION ALL
SELECT S.ID
FROM dbo.Invoices S
WHERE EXISTS ( SELECT NULL
FROM @InvoiceIdSet
WHERE ID = -1 ) )
, , ( ) ( ).


, 1M.
, .
.