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

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

t-sql query

Hi experts,

I'm using sql server 2008 R2.

I have a query where in the WHERE clause I have the following if statements.

SELECT * 
FROM MyTaBLE h, MyOtherTable d
WHERE
          If (@Region <> '0')
              begin
                     h.Region in (RTrim(@Region)) AND
              end
          If (@EmployeeSocial <> '')
              begin
                     h.EmployeeSocial = @EmployeeSocial AND
            end
      h.Region = d.Region

Open in new window


Is there a better way to write the if statements that are in my WHERE clause without using if statements?

FYI, my parameters are of these datatypes:

@Region varchar(800), @EmployeeSocial char(9)
0
maqskywalker
Asked:
maqskywalker
  • 2
1 Solution
 
Anthony PerkinsCommented:
Something like this perhaps:
SELECT  *
FROM    MyTaBLE h
        INNER JOIN MyOtherTable d ON h.Region = d.Region
WHERE   (@Region <> '0' AND h.Region = RTRIM(@Region))
        AND (@EmployeeSocial <> '' AND h.EmployeeSocial = @EmployeeSocial)

Open in new window

0
 
Anthony PerkinsCommented:
Incidentally you should not need to do a RTRIM() .  Typically the following are always true:
'Anthony' = 'Anthony       '

If you are bound and determined to use RTIM() than do this:
SET @Region = RTRIM(@Region)
SELECT  *
FROM    MyTaBLE h
        INNER JOIN MyOtherTable d ON h.Region = d.Region
WHERE   (@Region <> '0' AND h.Region = @Region)
        AND (@EmployeeSocial <> '' AND h.EmployeeSocial = @EmployeeSocial)

Open in new window

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

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