2

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)?

1
  • 2
    Check the column not the variable: Where PhaseID IS NULL not Where @PhaseID IS NULL Commented Oct 2, 2018 at 16:14

3 Answers 3

1

You need PhaseID instead of @PhaseID :

Select * 
from TestTable
Where (PhaseID = @PhaseID OR PhaseID IS NULL);

However, i would over thinking with :

. . .
WHERE (@PhaseID IS NOT NULL AND PhaseID = @PhaseID) OR
      (@PhaseID IS NULL AND PhaseID IS NULL);
Sign up to request clarification or add additional context in comments.

1 Comment

(@PhaseID IS NOT NULL AND PhaseID = @PhaseID) OR (@PhaseID IS NULL AND PhaseID IS NULL) works perfectly :)
1

You can do this with Dynamic SQL.

DECLARE @PhaseID INT
SET @PhaseID = 1

DECLARE @Sql NVARCHAR(MAX)
SET @Sql = 'SELECT * FROM TestTable WHERE '

IF @PhaseID IS NOT NULL
SET @Sql = @Sql + 'PhaseID = @_PhaseID'
ELSE
SET @Sql = @Sql + 'PhaseID IS NULL'

EXEC sp_executesql @Sql,N'@_PhaseID int',@_PhaseID = @PhaseID

Comments

-1

Currently you are doing @PhaseID is NULL which brings back 4 rows because you are referencing the parameter for the IS NULL check.

Declare @PhaseID int
SET @PhaseID = NULL

Select * 
from #Data
Where PhaseID = @PhaseID OR @PhaseID IS NULL

This brought back row 1 & 4 by using PhaseID as the column reference rather than referencing the parameter.

Select * 
from #Data
Where PhaseID = @PhaseID OR PhaseID IS NULL

3 Comments

But op wants 2 rows (1 & 4)
@AlexK. Amended the answer. Cheers.
This isn't going to work, you're going to get the NULL records when @PhaseID is set to an integer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.