将动态查询中的逻辑从Access VBA转换为SQL Server视图

时间:2016-04-26 14:03:19

标签: sql sql-server vba ms-access

我正在将Access应用程序转换为Web应用程序,但我无法将此vb / SQL转换为视图。它看起来不是那么难的问题,但它确实让我陷入了困境。

Public Function GetProjectNumber(ByVal HeaderID As Long) As String
    Dim retval As String
    Dim rst As New ADODB.Recordset
    Dim tempID As Long

On Error GoTo Err_Handler

    rst.Open "SELECT TransferID, ProjectID FROM dbo.tblProject WHERE HeaderID = " & HeaderID
    If Not (rst.EOF And rst.BOF) Then
        If IsNull(rst!TransferID) Then
            retval = rst!ProjectID
        Else
            tempID = rst!TransferID
            If rst.State = adStateOpen Then rst.Close
            rst.Open "SELECT ProjectID FROM dbo.tblProject WHERE HeaderID = " & tempID
            If rst.EOF And rst.BOF Then
                retval = "Transfer from ????"
            Else
                retval = "Transfer from " & rst!ProjectID
            End If
        End If
    End If

If rst.State = adStateOpen Then rst.Close

Exit_Handler:
    Set rst = Nothing
    GetProjectNumber = retval
    Exit Function

End Function

我尝试使用嵌套的case语句,但不能将案例应用于返回的每一行。有没有办法用IIF执行此操作?或者使其成为一种功能?

1 个答案:

答案 0 :(得分:3)

以下查询模仿表中所有记录的代码(即所有HeaderID)。

SELECT P1.HeaderID,
(CASE 
    WHEN P1.TransferID IS NULL THEN P1.ProjectID
    WHEN P2.ProjectID IS NULL THEN 'Transfer from ???' 
    ELSE "Transfer from " + P2.ProjectID
 END) AS Returns
FROM dbo.tblProject P1
LEFT JOIN dbo.tblProject P2 ON P1.TransferID = P2.HeaderID 

如果您从中创建SQL服务器视图,则可以使用特定的HeaderID轻松查询它,就像在VBA sub中一样

SELECT Returns FROM the_view WHERE HeaderID='xxxxx'

它应该返回与您的过程完全相同的结果