Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 124
  • Last Modified:

Select records based on a passed parameter in the WHERE clause

I'm looking for the proper syntax to use in a WHERE clause.  I'm pulling data from a non-normalized table that is used for reporting purposes, and I only want to pull those records where the IgnoreXXX field for the particular product = 0.

The syntax below seems to be working properly, but I'm just looking for either confirmation that this would be the preferred syntax, or a better syntax if there is one.
SELECT P1.Prod_ID
, P1.Entity_ID
, P1.docDate 
, Vol = Case WHEN @Product = 'Gas' THEN P1.Gas
             WHEN @Product = 'Oil' THEN P1.Oil
             WHEN @Product = 'Water' THEN P1.Water
             Else NULL End
, Ignore = Case When @Product = 'Gas' THEN P1.IgnoreGas
             WHEN @Product = 'Oil' THEN P1.IgnoreOil
             WHEN @Product = 'Water' THEN P1.IgnoreWater
             ELSE NULL End
FROM tbl_sysProduction as P1
WHERE (CASE WHEN @Product = 'Gas' Then P1.IgnoreGas
            WHEN @Product = 'Oil' THEN P1.IgnoreOil
            WHEN @Product = 'Water' THEN P1.IgnoreWater
            ELSE 0 END) = 0

Open in new window

0
Dale Fye
Asked:
Dale Fye
1 Solution
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
If that works for you then go for it, otherwise...

WHERE (@product = 'Gas' AND p1.IgnoreGas = 0) OR
   (@product='Oil' AND P1.IgnoreOir = 0) OR
   (@Product='Water AND P1.IgnoreWater = 0) OR
   (@Product NOT IN ('Gas', 'Oil', 'Water')
0
 
Dale FyeAuthor Commented:
Thanks, Jim.

I like your version.
0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now