SQL Server database question.
Table schema:
CREATE TABLE [dbo].[TestTable]
(
[ID] [INT] NOT NULL,
[PhaseID] [INT] NULL
) ON [PRIMARY]
Data:
INSERT INTO TestTable
VALUES (1, NULL), (2, 1), (3, 2), (4, NULL)
I am running a SQL query which is supposed to retrieve the record which matches the PhaseId column exactly (it could be null or an integer).. but seem to be missing something.
DECLARE @ID INT, @PhaseID INT
SET @ID = 1
SET @PhaseID = 1
SELECT *
FROM TestTable
WHERE PhaseID = @PhaseID OR @PhaseID IS NULL
If @PhaseID parameter is integer this works fine.
DECLARE @PhaseID INT
SET @PhaseID = 1 --works
But if @PhaseID is null, it returns all the records whereas I need the query to return only the first record & 4th record.
DECLARE @PhaseID INT
SET @PhaseID = NULL
SELECT *
FROM TestTable
WHERE PhaseID = @PhaseID OR @PhaseID IS NULL -- does not work returns all 4 records
How can this be achieved please?
I have referred a few other questions already but have not been successful. SQL Query Where Clause for Null OR Match (only return 1)?
Where PhaseID IS NULLnotWhere @PhaseID IS NULL