3

I have an SSRS report where a parameter can take 3 values. The select query is the same in all cases but the where clause needs to check different date fields based on the parameter value. Is this possible in the same query?

Query:

SELECT OrdNO, OrdType, customer, SalesRep, FundDate, DisbursementDate, Branch, SalesPrice 
FROM Orders

-- Case @ReportType=1, use FundDate
   where (FundDate >= @FromDate and FundDate <= @ToDate)

-- Case @ReportType=2, use DisbursmentDate
   Where (DisbursementDate >= @FromDate and DisbursementDate <= @ToDate)

-- Case @ReportType=3, use both dates
   where (FundDate >= @FromDate and FundDate <= @ToDate) or (DisbursementDate >= @FromDate and DisbursementDate <= @ToDate)

2 Answers 2

3

Yes, something like the below.

SELECT * 
FROM DataTable
WHERE (@SearchField = 'CreateDate' AND CreateDate BETWEEN @StartDate AND @EndDate)
OR (@SearchField = 'ModifyDate' AND ModifyDate BETWEEN @StartDate AND @EndDate)

Or, to use the example WHERE clauses you specified, how about the below?

SELECT *
FROM DataTable
WHERE (
        @ReportType = 1
        AND FundDatte >= @FromDate
        AND FunDate <= @ToDate
        )
    OR (
        @ReportType = 2
        AND DisbursementDate >= @FromDate
        AND DisbursementDate <= @ToDate
        )
    OR (
        @ReportType = 3
        AND (
            (
                FundDatte >= @FromDate
                AND FunDate <= @ToDate
                )
            AND (
                DisbursementDate >= @FromDate
                AND DisbursementDate <= @ToDate
                )
            )
        )
1
  • Thank you! It seems so obvious when presented like that. I was struggling with various case statement scenarios. Commented Feb 11, 2016 at 14:22
0

It depends but more than likely yes (with some potential performance issues due to different query plans being cached). Can you give a little more detail on what exactly the type of values are entered in the parameter? Are the 3 values all going to be dates, is the parameter itself a string value that you need to convert to the appropriate type, and is your query in a stored procedure?

1
  • I edited my original post to include the sample query Commented Feb 11, 2016 at 1:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.