0

我有一个表,其中有一列可 ping 的计算机名称,作为更大表的一部分提供给我。计算机名称可以包含点域名和/或 IP 地址。我需要将计算机名和域名分开到它们自己的列中。

例如:

ComputerFullName   | ComputerName | Domain
comp1              |              |
1.2.0.1            |              |
comp3.place.com    |              |
1.2.1.45.place.com |              |

我可以使用以下查询来填写域:

UPDATE Example 
SET Domain = SWITCH(
   ComputerFullName LIKE '#*.#*.#*.#*.*', MID(ComputerFullName, INSTR(1, REPLACE(ComputerFullName, '.', ' ', 1, 3), '.') + 1)
   , ComputerFullName LIKE '#*.#*.#*.#*', NULL
   , INSTR(1, ComputerFullName, '.') <> 0, MID(ComputerFullName, INSTR(1, ComputerFullName, '.') + 1)
);

我尝试了几个查询来更新 ComputerName 列,最有希望的是:

UPDATE Example 
SET ComputerName = SWITCH(
   ComputerFullName LIKE '#*.#*.#*.#*.*', LEFT(ComputerFullName, INSTR(1, ComputerFullName, Domain) - 2)
   , ComputerFullName LIKE '#*.#*.#*.#*', ComputerFullName
   , INSTR(1, ComputerFullName, '.') <> 0, LEFT(ComputerFullName, INSTR(1, ComputerFullName, '.') - 1)
   , TRUE, ComputerFullName
);

此尝试和所有其他尝试均返回错误消息,提示“Microsoft Office Access 无法更新更新查询中的所有记录...由于类型转换失败,Access 未更新 2 个字段...”

结果表如下所示:

ComputerFullName   | ComputerName | Domain
comp1              |              |
1.2.0.1            |              |
comp3.place.com    | comp3        | place.com
1.2.1.45.place.com | 1.2.1.45     | place.com

我想要的表是:

ComputerFullName   | ComputerName | Domain
comp1              | comp1        |
1.2.0.1            | 1.2.0.1      |
comp3.place.com    | comp3        | place.com
1.2.1.45.place.com | 1.2.1.45     | place.com

有什么建议么?


在使用以下答案时,我意识到为什么我的上述查询不起作用。即使条件为假,Access 也会评估 SWITCH 语句中的每个可能值。因此,当没有域时,LEFT 函数的长度参数为负数。

4

1 回答 1

2

I think what @HansUp was referring to was calling a function from within your query to split your names. Try this function:

Function SplitName(ByRef CFN As String, PartWanted As Integer) As String
    Dim CFN2 As String
    Dim I As Integer
    CFN2 = Replace(CFN, ".", "")
    If IsNumeric(CFN2) Then 'assume it's an IP address
        CFN = CFN & "|"
    Else
        Select Case Len(CFN) - Len(CFN2) 'we count the dots
            Case Is > 1 'at least 2 dots means computer & domain names
                I = InStrRev(CFN, ".")
                I = InStrRev(CFN, ".", I - 1)
                Mid(CFN, I) = "|"
            Case Is = 1 ' 1 dot means domain name only
                CFN = "|" & CFN
            Case Else '0 dots means computer name only
                CFN = CFN & "|"
        End Select
    End If
    SplitName = Split(CFN, "|")(PartWanted)
End Function

The PartWanted parameter would be either a 0 (to get the computer name) or 1 (to get the domain name). So your query would look like:

UPDATE Example 
SET Computername = SplitName([ComputerFullName],0), Domain = SplitName([ComputerFullName],1);

This runs pretty fast. I tested it and it took 13 seconds to call this function 2 million times (this didn't include the actual updating, just the calling).

于 2012-11-28T04:04:31.250 回答