2

I'm rookie in SQL Server.

I have a table dbo.Example which has 4 columns like this :

|Barcode|Goods |  Stock   |   Person |
-----------------------------------------
|0020307|Book  |Available |   Mike   |
|0090010|Table |NULL      |   Jane   |
|0140397|Chalk |NULL      |   Mike   |
|0190017|Glass |NULL      |Christoper|
|0080017|Hammer|Available |   Ron    |

I tried to create a stored procedure with parameters which it has null values in [Stock] column.

CREATE PROCEDURE examproc
    @person NVARCHAR(50) = NULL,
    @stock nvarchar(50) = NULL 
AS
    SELECT * 
    FROM dbo.Example
    WHERE person = ISNULL(@person, person)
      AND Stock = ISNULL(@stock, Stock) OR Stock IS NULL

And execute the procedure like this with parameter :

EXEC examproc @person = 'Mike'

But the result is not what I expected:

|Barcode|Goods |  Stock   |   Person |
-----------------------------------------
|0020307|Book  |Available |   Mike   |
|0090010|Table |NULL      |   Jane   |
|0140397|Chalk |NULL      |   Mike   |
|0190017|Glass |NULL      |Christoper|

I know there is something wrong with my SQL statement, and I'm still confused.

I need a suggestion..

Thanks...

1 Answer 1

3

You need to be super careful when mixing AND and OR in a WHERE clause - try this:

CREATE PROCEDURE examproc
    @person NVARCHAR(50) = NULL,
    @stock nvarchar(50) = NULL 
AS
    SELECT * 
    FROM dbo.Example
    WHERE person = ISNULL(@person, person)
      AND (Stock = ISNULL(@stock, Stock) OR Stock IS NULL)

and you can further simplify that by just leaving out the second condition (Stock IS NULL) - that's already handled by the first stock condition:

CREATE PROCEDURE examproc
    @person NVARCHAR(50) = NULL,
    @stock nvarchar(50) = NULL 
AS
    SELECT * 
    FROM dbo.Example
    WHERE Person = ISNULL(@person, person)
      AND Stock = ISNULL(@stock, Stock) 
Sign up to request clarification or add additional context in comments.

Comments

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.