HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Reduce the code in a WHERE clause without using dynamic SQL

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withoutthesqlwherereduceusingdynamiccodeclause

Problem

How can I write the following T-SQL query part in a shorter way without using dynamic SQL?

WHERE
    ( (@Max IS NULL OR @Type <> 'Products')
        OR (@Max IS NOT NULL AND @Type = 'Products'
            AND ProductCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Products')
        OR (@Min IS NOT NULL AND @Type = 'Products'
            AND ProductCount  'Vendors')
        OR (@Max IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Vendors' )
        OR (@Min IS NOT NULL AND @Type = 'Vendors'
            AND VendorCount  'Order')
        OR (@Max IS NOT NULL AND @Type = 'Order'
            AND OrderCount >  @Max ) )

    AND ( (@Min IS NULL OR @Type <> 'Order')
        OR (@Min IS NOT NULL AND @Type = 'Order'
            AND OrderCount <  @Min ) )

Solution

You will have to test this carefully, but the following query should work:

WHERE 
( 
  @Max IS NULL 
  OR @Type = 'Products' AND ProductCount > @Max
  OR @Type = 'Vendors'  AND VendorCount  > @Max
  OR @Type = 'Order'    AND OrderCount   > @Max
)
AND
(
  @Min IS NULL
  OR @Type = 'Products' AND ProductCount < @Min
  OR @Type = 'Vendors'  AND VendorCount  < @Min
  OR @Type = 'Order'    AND OrderCount   < @Min
)

Code Snippets

WHERE 
( 
  @Max IS NULL 
  OR @Type = 'Products' AND ProductCount > @Max
  OR @Type = 'Vendors'  AND VendorCount  > @Max
  OR @Type = 'Order'    AND OrderCount   > @Max
)
AND
(
  @Min IS NULL
  OR @Type = 'Products' AND ProductCount < @Min
  OR @Type = 'Vendors'  AND VendorCount  < @Min
  OR @Type = 'Order'    AND OrderCount   < @Min
)

Context

StackExchange Code Review Q#2763, answer score: 7

Revisions (0)

No revisions yet.