从excel中向sql中插入数据时,如何保证数据不会重复?我已经创建了主键约束,当重复时,老是报错。但我已经作了处理:当与数据相同时,让程序只是更改插入时间。

解决方案 »

  1.   

    With save_rst
      If .RecordCount > 0 Then
         .MoveFirst
      End If
     j = rowstart_set
     Do Until j = (rowend_set - rowstart_set + 1)
      For i = colweekstart_set To colweekend_set
            If Cells(j, JAN_COL_OFFSET) <> "" And Cells(j, STR_COL_OFFSET) <> "" Then
                Do Until .EOF
                
                    If CInt(Cells(j, STR_COL_OFFSET)) = .Fields("StoreCode") And _
                     Val(Cells(j, JAN_COL_OFFSET)) = Val(.Fields("JANcode")) And _
                     Val(Cells(rowstart_set - 2, i)) = Val(.Fields("YearWeek"))And_  
                     Val(Cells(j, 7)) = Val(.Fields("CostPrice")) And _
                     Val(Cells(j, 8)) = Val(.Fields("SellingPrice")) And _
                     Val(.Fields("DataType")) = 1 And _
                     Val(Cells(j, i)) = Val(.Fields("SellingQuantity")) Then
                       
                     .Fields("amenddate") = Now()
                     .Update
                     .MoveNext
                      GoTo 1
                    Else
                    
                       .MoveNext
                       
                   End If
               Loop
                
                  
                      .AddNew
                      .Fields("DataType") = 1
                      .Fields("StoreCode") = CInt(Cells(j, STR_COL_OFFSET))
                      .Fields("JANcode") = Val(Cells(j, JAN_COL_OFFSET))
                      .Fields("YearWeek") = Val(Cells(rowstart_set - 2, i))
                      .Fields("CostPrice") = Val(Cells(j, i))
                      .Fields("SellingPrice") = Val(Cells(j, i))
                      .Fields("SellingQuantity") = Val(Cells(j, i))
                      .Fields("amenddate") = Now()
         
          Else
              Exit For
          End If
    1  Next i
      j = j + 1
    Loop
    End With
      Set save_rst = Nothing
      Set save_cn = Nothing
    新手,让各位见笑了
      

  2.   

    其中,字段名storecode ,jancode,yearweek,datatype是组合主键
      

  3.   

    在最前面加
    On Error Goto ErrHandler最后加Exit SubErrHandler:
       If Err.Number = -2147467259 Then Resume Next   If Err.Number <> 0 Then MsgBox "错误" & Err.Number & ":" & Err.Description