Mark Marina
Mark Marina

Reputation: 733

If/Else Statements in VB.NET (SQL) Query?

I just wanted to know what's the best way to add If/Else statements in a SQL query within VB.Net code?

This is my current query (doesn't work):

SELECT 
   FIRSTNAME, LASTNAME 
FROM 
   TBL_USERS 
ORDER BY 
   If(SortSelect() Is ""lastname"", LASTNAME, FIRSTNAME) 

Thanks in advance.

Upvotes: 0

Views: 3214

Answers (3)

Marc
Marc

Reputation: 16512

My opinion about this is to NEVER put the IF in the SQL statement. It makes it too hard to read. Probably because it's all on the same line.

In your case, there's only one, but when you got many conditions, it gets almost impossible to read.

You should declare a string for your condition like this

Dim strQuery as string
Dim strOrderBy as string

If(SortSelect() = "lastname") then
   strOrderBy = "Order By lastname"
Else
   strOrderBy = "Order By firstname"
endif


strQuery = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS " & strOrderBy

Upvotes: 2

Andomar
Andomar

Reputation: 238086

Dim sql as string = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS ORDER BY "
if (SortSelect() = "lastname")
    sql = sql & "lastname"
else
    sql = sql & "firstname"
end if

Upvotes: 1

Joe G Joseph
Joe G Joseph

Reputation: 24046

you could try something like this:

SELECT FIRSTNAME, LASTNAME 
FROM TBL_USERS 
ORDER BY Case when <SortSelect>= 'lastname' then LASTNAME else  FIRSTNAME end

Upvotes: 2

Related Questions