过滤掉 objCom.CommandText 中返回的 NULL 字段

Filter out NULL fields returned in a objCom.CommandText

使用下面的脚本,我能够按预期列出 OU 中的用户,但是输出列出了所有内容,包括自定义 ipphone 字段中缺少数据的用户。我需要帮助修改代码以不在 ipphone 字段中列出缺少分机号码的用户。 "This indicates a user has left the company and should not show up on the phone list"

<%@ Language=VBScript  %>
<% response.Buffer = True %>
<html><head>
<title></title>
</head>
<body>
<h1>Directory</h1>
<%
' Define the AD OU that contains our users

usersOU = "LDAP://OU=IT,OU=Hollister,OU=Houston,OU=NFSmith,DC=nfsmith,DC=info"

' Make AD connection and run query
Set objCon = Server.CreateObject("ADODB.Connection")
objCon.provider ="ADsDSOObject"

objCon.Properties("User ID") = "domain\user"
objCon.Properties("Password") = "password"
objCon.Properties("Encrypt Password") = TRUE
objCon.open "Active Directory Provider"

Set objCom = CreateObject("ADODB.Command")
Set objCom.ActiveConnection = objCon
objCom.CommandText ="select givenName,sn,telephonenumber,ipphone FROM '"+ usersOU +"' where ipphone='*' ORDER by givenName"

Set objRS = objCom.Execute

' Loop over returned recordset and output HTML

Response.Write "<table>" + vbCrLf
Do While Not objRS.EOF Or objRS.BOF
    Response.Write "  <tr>"
    Response.Write "<td>" + objRS("givenName") + "</td>"
    Response.Write "<td>" + objRS("sn") + "</td>"

    Response.Write "<td>" + objRS("telephonenumber") + "</td>"
    Response.Write "<td>" + objRS("IPphone") + "</td>"

    Response.Write "</tr>" + vbCrLf
    objRS.MoveNext
    Response.Flush
Loop
Response.Write "</table>"
' Clean up
objRS.Close
objCon.Close
Set objRS = Nothing
Set objCon = Nothing
Set objCom = Nothing
%>
</body>
</html>

在写入输出之前检查值是否为Null

Do Until objRS.EOF
    If Not IsNull(objRS("ipPhone")) Then
        Response.Write "  <tr><td>" + objRS("givenName")
        Response.Write "</td><td>" + objRS("sn")
        Response.Write "</td><td>" + objRS("telephoneNumber")
        Response.Write "</td><td>" + objRS("ipPhone")
        Response.Write "</td></tr>" & vbCrLf
        Response.Flush
    End If

    objRS.MoveNext
Loop

如果您根本不需要 NULL 记录,为什么不告诉您的 SQL 查询将它们排除在外?

所以你有

objCom.CommandText ="select givenName,sn,telephonenumber,ipphone FROM '"+ _
   usersOU +"' where ipphone='*' ORDER by givenName"

添加条件:

objCom.CommandText = "SELECT givenName, sn, telephonenumber, ipphone FROM '" & _
    usersOU & "' WHERE ipphone = '*' AND ipphone IS NOT NULL ORDER BY givenName"

(我不确定 ipphone = '*' 的用途是什么,但我不常使用 Active Directory。)

另一种方法,即在代码中测试 IsNull(objRS("ipPhone")),如果您想在字段为 null 的情况下执行其他操作,则此方法很有用 — 也许添加一个 "inactive" class,诸如此类。