Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Select where cboValue or all if null 1

Status
Not open for further replies.

vmon

IS-IT--Management
Feb 14, 2002
74
0
0
US
How do I select records using a passed parameter that may have a valid value or be null. If it is null then I want to select all records. This is what I tried without sucess.

Thanks,
vmon

SELECT * FROM tblItem WHERE tblItem.LocId = ISNULL(@cboLocId, %)
 
vmon,

Couple of thoughts - I assume a stored procedure... (1) Use a default value on the parameter. (2) Use an IF statement to detect the null value and fire an alternate select statement.

ttba
 
This is how I have an example program working, with a space between IS, and NULL.

SELECT * FROM tblItem WHERE tblItem.LocId = IS NULL(@cboLocId, %)
 
SELECT * FROM tblItem
WHERE tblItem.LocId = ISNULL(@cboLocId, tblItem.LocId)

This will not return rows where tblItem.LocId is NULL, since NULL is never equal or not equal to another value.

--John [rainbow]
-----------------------------------
Behold! As a wild ass in the desert
go forth I to do my work.
--Gurnie Hallock (Dune)
 
I take from your question that you are trying to write a stored procedure, if so then you may try this:

if (@cboLocId not null)
Begin
SELECT * FROM tblItem WHERE tblItem.LocId = @cboLocId
End
else
Begin
SELECT * FROM tblItem
end
GO

to know more from BOL:

IS [NOT] NULL
Determines whether or not a given expression is NULL.

Syntax
expression IS [ NOT ] NULL

Arguments
expression

Is any valid Microsoft® SQL Server™ expression.

NOT

Specifies that the Boolean result be negated. The predicate reverses its return values, returning TRUE if the value is not NULL, and FALSE if the value is NULL.

Result Types
Boolean



AL Almeida
NT/DB Admin
"May all those that come behind us, find us faithfull"
 
oooh noticed an error in mine. The equal sign needs to go away I think

SELECT * FROM tblItem WHERE tblItem.LocId IS NULL(@cboLocId, %)
 
The equivalence operator IS NULL is not the same as the function IsNull(). Don't confuse them.

In my opinion, this is the best way to solve the problem. It is fast, efficient, doesn't use a function on every row like some methods do:

Code:
SELECT *
   FROM tblItem
   WHERE
      @cboLocId IS NULL
      OR tblItem.LocId = @cboLocId

-------------------------------------
There are 10 kinds of people in the world: those who know binary, and those who don't.
 
Very good ESquared! Prior responses questioned my ISNULL versus IS NULL. I have read up on both now. Thanks again.

vmon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top