kerrybenno
asked on
SQL retrieving records where a field isNull
In Excel I am retrieving data in vba using sql.
I have the following code;
Function SummarySQL()
Dim FirstDate As Date
Dim Sector As String
Dim Team As String
Dim TabCode As String
FirstDate = Range("FirstDate").Value
Sector = Range("Sector").Value
Team = Range("Team").Value
TabCode = "Additional Resources"
If Sector = "Show All" Then
Sector = "%"
End If
If Team = "Show All" Then
Team = "%"
End If
SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
"AND [Sector] Like '" & Sector & "'" & " " & _
"AND [TabCode] Like '" & TabCode & "'" & " " & _
"AND [Team] Like '" & Team & "'" & ";"
End Function
Sometimes the Sector field will have been left empty, so where it's returning all with %, I also need it to return the nulls too. When Sector <> % I don't want the nulls.
i hope this makes sense.
Thanks in advance.
I have the following code;
Function SummarySQL()
Dim FirstDate As Date
Dim Sector As String
Dim Team As String
Dim TabCode As String
FirstDate = Range("FirstDate").Value
Sector = Range("Sector").Value
Team = Range("Team").Value
TabCode = "Additional Resources"
If Sector = "Show All" Then
Sector = "%"
End If
If Team = "Show All" Then
Team = "%"
End If
SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
"AND [Sector] Like '" & Sector & "'" & " " & _
"AND [TabCode] Like '" & TabCode & "'" & " " & _
"AND [Team] Like '" & Team & "'" & ";"
End Function
Sometimes the Sector field will have been left empty, so where it's returning all with %, I also need it to return the nulls too. When Sector <> % I don't want the nulls.
i hope this makes sense.
Thanks in advance.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Sorry I am wrong in previous. Try replacing as this
If Sector = "Show All" Then
Sector = " [Sector] Like % "
End If
If Team = "Show All" Then
Team = "%"
End If
If Sector <> " [Sector] Like %'" Then
Sector = " Sector is not null "
End If
SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
"AND " & Sector & " & _
"AND [TabCode] Like '" & TabCode & "'" & " " & _
"AND [Team] Like '" & Team & "'" & ";"
If Sector = "Show All" Then
Sector = " [Sector] Like % "
End If
If Team = "Show All" Then
Team = "%"
End If
If Sector <> " [Sector] Like %'" Then
Sector = " Sector is not null "
End If
SummarySQL = "SELECT * FROM [" & DataRange & "] WHERE [Month Year] = " & CDbl(FirstDate) & " " & _
"AND " & Sector & " & _
"AND [TabCode] Like '" & TabCode & "'" & " " & _
"AND [Team] Like '" & Team & "'" & ";"
If Sector = "Show All" Then
Sector = "% " and " Sector is not null "
End If