仅插入一条记录,该记录在没有任何数据的数据库中不存在

时间:2018-07-23 08:17:19

标签: sql vbscript access-vba

我正在尝试在VBScript中进行编码,以便将当前记录添加到Access数据库中。只有在数据库中有数据时它才起作用,但是当没有任何数据时,它将不起作用。

If (ReportFile.AtEndofStream = False) Then
    LineItems = Split(LineFromFile, vbTab)
    con.Execute _
        "INSERT INTO SalesOrder ( SONo )" & _
        " SELECT DISTINCT ('" & LineItems(0) & "')" & _
        " FROM SalesOrder" & _
        " WHERE ((((Select Count(SONo) FROM SalesOrder WHERE SalesOrder.SONo = '" & LineItems(0) & "'))=0));"
End If

1 个答案:

答案 0 :(得分:0)

我认为您想在WHERE子句中使用EXISTS,并且不应在WHERE子句之前从SalesOrder表中进行选择,因为该表为空,将不返回任何行。
我假设您使用DISTINCT是因为,当SalesOrder多于一行时,您将为每一行插入相同的LineItems(0)值,从而导致主键冲突:

这是我在Management Studio中所做的:

Create Table SalesOrder (SONo int Primary Key)
go
INSERT INTO SalesOrder ( SONo )
select SONo
from (select SONo = 2) a
WHERE NOT EXISTS (Select 1 FROM SalesOrder WHERE SalesOrder.SONo = a.SONo)
go

所以我认为您的vbscript代码应为:

If (ReportFile.AtEndofStream = False) Then
    LineItems = Split(LineFromFile, vbTab)
    con.Execute _
        "INSERT INTO SalesOrder ( SONo )" & _
        " SELECT  (select SONo = '" & LineItems(0) & "') a" & _
        " WHERE NOT EXISTS (Select 1 FROM SalesOrder " & _ 
        "                   WHERE SalesOrder.SONo = a.SONo);"
End If