Ms-Access
CASE SELECT 的 VB.Net 錯誤
以下 VB.Net 程式碼在 SQL Server 上執行良好,但在 Access 上出現錯誤:
sql = "SELECT sr.itemcode, sr.itemname, SUM(CASE WHEN sr.transdate='4/14/2016' THEN sr.temunits] END) AS [Units Sold], " & _ "SUM(sr.itemunits) AS [Total Units Sold] " & _ "FROM [tblINV_SalesRecord] AS sr WHERE sr.transdate <= '4/14/2016' GROUP BY sr.itemcode, sr.itemname"
錯誤是:
IErrorInfo.GetDescription Failed with E_FAIL(0x80004005), -System.Data
MS Access 不支持 CASE 表達式。最通用的等價物是Switch 功能。使用該函式,像這樣的 SQL CASE 表達式
CASE WHEN *condition1* THEN *value1* WHEN *condition2* THEN *value2* ... END
可以這樣重寫:
Switch( *condition1*, *value1*, *condition2*, *value2*, ... )
更具體,可能更適合您的情況,等效的是IIf 函式。它適用於需要基於單個條件返回兩個值之一的情況。換句話說,它替換了以下 CASE 模式:
CASE WHEN *condition* THEN *true_value* ELSE *false_value* END
就像這樣:
IIf(*condition*, *true_value*, *false_value*)
在您的特定情況下,CASE 表達式沒有 ELSE 子句。這意味著這
ELSE NULL
是隱含的,儘管ELSE 0
在這裡可能更合適。因此,您可以像這樣重寫查詢:sql = "SELECT sr.itemcode, sr.itemname, " & _ "SUM(**IIf(sr.transdate='4/14/2016', sr.temunits, 0)**) AS [Units Sold], " & _ "SUM(sr.itemunits) AS [Total Units Sold] " & _ "FROM [tblINV_SalesRecord] AS sr WHERE sr.transdate <= '4/14/2016' " & _ "GROUP BY sr.itemcode, sr.itemname"