在另一个表中找到重复的插入

时间:2009-12-02 16:17:45

标签: sql sql-server sql-server-2005 vb6

我有一个代码可以将我的数据加载到sql表中。我想要知道有任何方法可以将数据加载到其他表中,如果有任何重复值。如果是,你可以帮助我吗?我的疑问是:

  

“插入t_DATA_DneFrc(RTN,AccountNbr,FirstName,MiddleName,LastName,Amount)值('”& rcdDNE(“RTN”)&“','”& rcdDNE(“AccountNbr”)&“ ',''& rcdDNE(“FirstName”)&“','”& rcdDNE(“MiddleName”)&“','”& rcdDNE(“LastName”)&“','”& ; rcdDNE(“Amount”)&“')”

将数据插入t_DATA_DneFrc表。现在我想要更改查询,如果有重复插入该行t_DATA_DneFrcDuplicate。这可能吗?

 ' Write records to Database

frmDNELoad.lblStatus.Caption = "Loading data into database......"

Dim lngRecCount As Long
lngRecCount = 0
rcdDNE.MoveFirst

 With cmdCommand
    .ActiveConnection = objConn
    .CommandText = "insert into t_DATA_DneFrc (RTN, AccountNbr, FirstName, MiddleName, LastName, Amount) values ('" & rcdDNE("RTN") & "', '" & rcdDNE("AccountNbr") & "', '" & rcdDNE("FirstName") & "', '" & rcdDNE("MiddleName") & "', '" & rcdDNE("LastName") & "', '" & rcdDNE("Amount") & "')"
    .CommandType = adCmdText

End With

Set rcddnefrc = New ADODB.Recordset
With rcddnefrc
    .ActiveConnection = objConn
    .Source = "SELECT * FROM T_DATA_DNEFRC"
    .CursorType = adOpenDynamic
    .CursorLocation = adUseClient
    .LockType = adLockOptimistic
    .Open
End With

Do Until rcdDNE.EOF
    lngRecCount = lngRecCount + 1
    frmDNELoad.lblStatus.Caption = "Adding record " & lngRecCount & " of " & rcdDNE.RecordCount & " to database."
    frmDNELoad.Refresh
    DoEvents
    Call CommitNew
    rcdDNE.MoveNext
Loop

frmDNELoad.lblStatus.Caption = "DNE Processing Complete."
frmDNELoad.Refresh

End Function
Sub CommitNew()

'     Add records to DneFrc table
With rcddnefrc
    .Requery
    .AddNew
    .Fields![RTN] = rcdDNE.Fields![RTN]
    .Fields![AccountNbr] = rcdDNE.Fields![AccountNbr]
    .Fields![FirstName] = rcdDNE.Fields![FirstName]
    .Fields![MiddleName] = rcdDNE.Fields![MiddleName]
    .Fields![LastName] = rcdDNE.Fields![LastName]
    .Fields![Amount] = rcdDNE.Fields![Amount]
    .Update
End With

1 个答案:

答案 0 :(得分:3)

您需要运行第二个查询,该查询应该类似于

insert into t_DATA_DneFrcDuplicate 
      (RTN, AccountNbr, FirstName, MiddleName, 
       LastName, Amount, Occurances)
  select RTN, AccountNbr, FirstName, MiddleName, 
         LastName, Amount, COUNT(*)
  from   t_DATA_DneFrc
  group by RTN, AccountNbr, FirstName, MiddleName, 
           LastName, Amount
  having COUNT(*) > 1

(这是Oracle语法;希望同样适合您。)