Question

I have a stored procedure that I created and sometimes there are parameters that pass in a NULL value. I set up the stored procedure to take this into account, but every time I pass in a NULL value it doesn't return anything even if some of the other parameters are passed in. Can you please help? Here is my stored procedure. I'm not sure if it's the join that isn't correct or what.

Thanks.

   @ProductID int = NULL,
   @CollectionID int = NULL,
   @ApplicationID int = NULL,
   @StyleID int = NULL
AS
   SELECT        
      dbo.CrossoverDesignTable.ColorNum, dbo.CrossoverDesignTable.CrossoverID,     
      dbo.ImagesWebsite.Description, 
      dbo.DesignNameTable.DesignDescription + ' ' +  dbo.CrossoverDesignTable.ColorNum AS DesignColor, 
      dbo.CollectionTable.CollectionDescription
   FROM            
      dbo.CrossoverDesignTable 
   INNER JOIN
      dbo.DesignNameTable ON dbo.CrossoverDesignTable.DesignNameID = dbo.DesignNameTable.DesignNameID 
   INNER JOIN
      dbo.ImagesWebsite ON dbo.CrossoverDesignTable.ProductImageID = dbo.ImagesWebsite.ProductImageID 
   INNER JOIN
      dbo.CollectionTable ON dbo.CrossoverDesignTable.CollectionID = dbo.CollectionTable.CollectionID
   WHERE        
      (dbo.CrossoverDesignTable.ProductID = @ProductID OR @ProductID IS NULL) 
      AND (dbo.CrossoverDesignTable.CollectionID = @CollectionID OR dbo.CrossoverDesignTable.CollectionID IS NULL) 
      AND (dbo.CrossoverDesignTable.ApplicationID = @ApplicationID OR @ApplicationID IS NULL) 
      AND (dbo.CrossoverDesignTable.ShowOnWeb = 'Yes') 
      AND (dbo.CrossoverDesignTable.StyleID = @StyleID OR @StyleID IS NULL) 

   RETURN
Was it helpful?

Solution

What I do in these scenarios is change the default for @ProductId to -1

DO NOT SEND ANY VALUE FOR THE PARAMETER, IF YOU SEND A NULL THEN IT WILL USE THAT VALUE. DEFAULT VALUES ARE ONLY USED WHEN THE PARAMETER IS NOT SENT.

@ProductID int = -1,
@CollectionID int = NULL,
@ApplicationID int = NULL,
@StyleID int = NULL

WHERE (@ProductID = -1 OR dbo.CrossoverDesignTable.ProductID = @ProductID)
  AND .....

OTHER TIPS

Assuming -1 is a value you don't have, I recommend you use this:

ISNULL(dbo.CrossoverDesignTable.ProductID, -1) = ISNULL(@ProductID, -1)

instead of:

dbo.CrossoverDesignTable.ProductID = @ProductID OR @ProductID IS NULL

and do the other comparisons in the same way.

If you want to keep your approach, you should do it this way, I think.

( (@ProductID is null) AND (dbo.CrossoverDesignTable.ProductID is null) )  
OR (dbo.CrossoverDesignTable.ProductID = @ProductID)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top