DigitalNoise
DigitalNoise

Reputation: 25

ORDER BY with IF...ELSE SQL Server 2008 r2

I've got a very basic problem that I'm trying to solve (basic to me, anyway), but I'm having trouble understanding why one bit of code works standalone, but when you wrap it in an IF statement, it doesn't.

This works just fine:

SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB

However, when I try to make use of it in an IF statement:

IF @FILTERBY = '2'
  BEGIN
    (SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB)
  END

I get the error "Incorrect syntax near the keyword 'ORDER'

I've done some searching, but I can't seem to figure out why this doesn't work. Is there another way to order the returned result set?

Upvotes: 1

Views: 767

Answers (3)

MaxiWheat
MaxiWheat

Reputation: 6261

Revove the parenthesis around your SELECT

Upvotes: 1

jlee88my
jlee88my

Reputation: 3043

Remove the ( and ):

IF @FILTERBY = '2'
BEGIN
    SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB
END

Upvotes: 1

Adam Plocher
Adam Plocher

Reputation: 14243

Take the parenthesis off

Like so:

IF @FILTERBY = '2'
  BEGIN
    SELECT DISTINCT H.FB FROM I_HSE H WHERE H.AC IN (@AC) ORDER BY H.FB
  END

Upvotes: 2

Related Questions