The title only explains my first attempt, I couldn't think how to word the issue/my need exactly.
I have table job:
CREATE TABLE [dbo].[job]
(
[jobId] INT IDENTITY(1,1) PRIMARY KEY,
[contractId] INT NOT NULL,
[districtId] INT NULL,
[address] NVARCHAR (255) NULL
);
I'm trying to create a function where all of the column values can be optionally passed through to do a filter search.
So far I have:
DECLARE
@jobId INT,
@contracId INT,
@districtId INT,
@addressPart NVARCHAR(255)
SELECT
[jobId],
[contractId],
[districtId],
[address]
FROM
[dbo].job
WHERE
jobId = ISNULL(@jobId,jobId)
AND contractId = ISNULL(@contracId, contractId)
AND [address] LIKE '%' + ISNULL(@addressPart, [address]) + '%'
This works, however because the districtId
can be null in the Job
table doing the same ISNULL where clause as for contractId
results in the query to only ever return records where districtId
is not null, as the '=' condition doesn't work for null values.
I've tried using COALESCE
AND COALESCE(districtId, 0) = COALESCE(@districtId, 0)
But that results in the query only selecting records where districtId
is null if no districtId
is specified. It does select the the row with the districtId
if a 'district' is set. But this is ultimately no good as if any other variable is set which would match a record, if that record has null districtId
it won't be selected.
I've also tried using OR
AND (districtId = ISNULL(@districtId, districtId) OR districtId IS NULL)
But this returns everything when the districtId
is null, but then if a districtId
is set, it'll get that record, but also still return all records that have districtId
null.
I can't even think how to do this with a dirty CASE statement, as I'd need to do districtId =
and as soon as I do that '=' its not going to work as it need to on some level check for null is null which '=' can't do.