0

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.

0

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

you could try something like this:

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

2 Comments

SortSelect() looks like a VB function... how can you use that in an SQL string?
@Andomar: you are right..what I mean is, he should create the query in VB.net, with proper value for SortSelect and pass it to the database
1
Dim sql as string = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS ORDER BY "
if (SortSelect() = "lastname")
    sql = sql & "lastname"
else
    sql = sql & "firstname"
end if

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.