ORDER BY查询抛出错误

时间:2016-10-28 16:33:31

标签: sql vb.net sql-order-by

我正在使用SQL Server数据库,并选择记录来显示合同信息。协议可以是活动的,不活动的,等待响应或等待付款。

我的用户希望网格按此顺序显示结果:

  • 等待回复
  • 等待付款
  • 逾期
  • 有效
  • 无效

我尝试使用以下代码来实现此目的,但它会在默认字词附近引发错误,说明语法错误。

按声明排序有什么问题?

Try
    sql = "SELECT ContractID, CustAcc, DateStart, DateRenew, Fee, Agreement, OtherDetails, " _
        & "DateSent, TimeSent, ReminderName, ReminderEmail FROM dbo.tblContracts " _
        & "ORDER BY FIELD(Agreement, 'AWAITING RESPONSE', 'AWAITING PAYMENT', 'ACTIVE', 'INACTIVE')"
    conAd = New OleDb.OleDbDataAdapter(sql, con)
    conset = New DataSet
    conAd.Fill(conset)
    ugModules.DataSource = conset
Catch ex As Exception
    errorLog(ex.Message, ex.StackTrace)
    MsgBox("Failed to retrieve contract information, refer to error log")
End Try

编辑

按照@Solarflare的建议改变我的代码后,我现在得到了以下代码;

sql = "SELECT ContractID, CustAcc, DateStart, DateRenew, Fee, Agreement, OtherDetails, " _
& "DateSent, TimeSent, ReminderName, ReminderEmail FROM dbo.tblContracts " _ 
& "ORDER BY CASE Agreement WHEN 'AWAITING RESPONSE' THEN 1 WHEN 'AWAITING PAYMENT' THEN 2 " _
& "WHEN 'OVERDUE' THEN 3 WHEN 'ACTIVE' THEN 4 WHEN 'INACTIVE' THEN 5 END"

然而,结果并不像预期的那样。结果如下

所以INACTIVE主要位于顶部,其次是AWAITING RESPONSE和INACTIVE等 - 为什么会这样?

1 个答案:

答案 0 :(得分:0)

ORDER BY应该在SQL Server中使用CASE语句。