检查记录是否存在等待插入

时间:2014-05-28 18:43:37

标签: database asp-classic

我正在尝试检查数据库中是否存在记录。如果存在丢弃插入功能。如果记录不存在插入。

我的效果相反。

<% 
Set OBJdbConnection = Server.CreateObject("ADODB.Connection")  
OBJdbConnection.open MM_Listings_STRING

'1. Check if contractor is linked
SQLQuery1 = "Select * FROM Agent_Contractor WHERE ContractorID = " &_
Request.Form("ContractorID") & " AND AgentID = " & Session("AgentID") 

Set Results = OBJdbConnection.Execute(SQLQuery1)

'1. If linked response write. 
If Results.EOF  Then
  Response.Write "Contractor Already Linked"
else
  '1. Insert
  SQLQuery3 = "INSERT INTO Agent_Contractor (" &_
  "ContractorID, " &_
  "AgentID) VALUES (" &_
  Request.Form("ContractorID") & ", " &_
  Session("AgentID") & ")"

  OBJdbConnection.Execute(SQLQuery3)    
  Response.Write "Contractor Linked successfully."
end if
%>

2 个答案:

答案 0 :(得分:4)

你的陈述在你的代码中是倒退的。

“如果BOF或EOF属性为True,则没有当前记录。”根据{{​​3}}

因此,如果Results.EOF为真,则不会链接承包商。

答案 1 :(得分:0)

您可以在NOT EXISTS中使用WHERE条件。请看下面的示例代码:

"INSERT INTO Agent_Contractor (ContractorID, AgentID) " &_
"SELECT '" & Request.Form("ContractorID") & "', '" &_
Session("AgentID") & "' FROM Agent_Contractor WHERE " &_
"NOT EXIST (SELECT * FROM Agent_Contractor WHERE ContractorID = '" &_
Request.Form("ContractorID") & "' AND AgentID = '" & Session("AgentID") & "')"

我不确定我是否能获得权利,因为我无法运行它,但我想指出逻辑。你可以对此进行调整。