Public Function GenerateSQL(strTask As String, Optional qWhere As String, Optional strTBL As String) As String
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim rsf As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim strSRC As String, strDEST As String, strWHEREQ As String, strQRYD As String
Dim strQRY As String
Set dbs = CurrentDb
On Error GoTo Err_handler
Set rs = dbs.OpenRecordset("Select * from tblSQL", dbOpenSnapshot)
rs.Filter = "fldTaskName = '" & strTask & "'"
Set rsf = rs.OpenRecordset()
With rsf
If .RecordCount > 1 Then
MsgBox "More than one match found"
GoTo ExitFunction
Else
strSRC = !fldSRC
End If
If !fldSRCQ <> "" Then ' Use tblSQL unless empty
strQRY = !fldSRCQ
Else
strQRY = FindDefaults(strSRC)
End If
strQRYD = !fldDESTQ
If !fldWHEREQ <> "None" Then
strWHEREQ = !fldWHEREQ
End If
If qWhere <> "" Then
strWHEREQ = qWhere
End If
Select Case !fldType:
Case "SELECT":
If ObjectExists("Query", "qry" & strTask) Then
DoCmd.DeleteObject acQuery, "qry" & strTask
End If
GenerateSQL = "PROCEDURE qry" & strTask & "; " _
& !fldType & " " & strQRY & " FROM " & strSRC & " " & strWHEREQ
'Set qdf = dbs.CreateQueryDef("qry" & strTask, GenerateSQL)
'DoCmd.OpenQuery "qry" & strTask
Case "DELETE":
GenerateSQL = "DELETE " & !fldSRCQ & " FROM " & strSRC & " " & strWHEREQ
'DoCmd.RunSQL GenerateSQL
Case "INSERT":
GenerateSQL = "INSERT INTO " & !fldDEST & " " & !fldDESTQ & " SELECT " & !fldSRCQ & " FROM " & strTBL & " " & strWHEREQ
Case "UPDATE":
GenerateSQL = "UPDATE " & !fldSRC & " " & !fldSRCQ
End Select
End With
ExitFunction:
Set rsf = Nothing
Set rs = Nothing
Set dbs = Nothing
Exit Function
Err_handler:
Dim strXX As String
Select Case Err.Number:
Case 3075: 'Syntax error in SQL statement
strXX = "The following SQL statement has syntax error."
strXX = strXX & vbCrLf & "Please verify the SQL string and try again."
strXX = strXX & vbCrLf & vbCrLf & GenerateSQL
MsgBox strXX, vbCritical + vbOKOnly, "Error in SQL Statement"
End Select
Err.Clear
End Function