如果VB.NET(SQL)查询中的/ Else语句?

时间:2012-11-07 14:40:10

标签: asp.net sql vb.net

我只是想知道在VB.Net代码中的SQL查询中添加If/Else语句的最佳方法是什么?

这是我当前的查询(不起作用):

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

提前致谢。

3 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情:

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

答案 1 :(得分:2)

我对此的看法是永远不要将IF放在SQL语句中。这使得阅读太难了。可能是因为它都在同一条线上。

在你的情况下,只有一个,但是当你有很多条件时,几乎不可能阅读。

您应该为此条件声明一个字符串

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

答案 2 :(得分: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