[英]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? 我只是想知道在VB.Net代码中的SQL查询中添加
If/Else
语句的最佳方法是什么?
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. 提前致谢。
you could try something like this: 您可以尝试这样的事情:
SELECT FIRSTNAME, LASTNAME
FROM TBL_USERS
ORDER BY Case when <SortSelect>= 'lastname' then LASTNAME else FIRSTNAME end
My opinion about this is to NEVER put the IF
in the SQL statement. 我对此的看法是永远不要将
IF
放在SQL语句中。 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
Dim sql as string = "SELECT FIRSTNAME, LASTNAME FROM TBL_USERS ORDER BY "
if (SortSelect() = "lastname")
sql = sql & "lastname"
else
sql = sql & "firstname"
end if
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.