【问题标题】:avoiding duplicate data while inserting插入时避免重复数据
【发布时间】:2014-12-20 17:26:33
【问题描述】:

我想避免在具有自动增量 ID (Viewer_ID) 的表中插入重复值。我在 jsp 页面上工作,我写了准备好的声明。我怎样才能做到这一点??在我的表中创建索引或编写存储过程或通过jsp页面中的特定查询解决这个问题更好吗???如果我想编写存储过程,如何在我的 jsp 页面中使用它???谢谢

PreparedStatement pst = con.prepareStatement( Insert into Viewer (F_Name, L_Name, Competition_ID, City ,Phone, E-mail, Reserve_ID) values (?,?,?,?,?,?,?);

编辑:

if not exists (select F_Name, L_Name, City, Phone
, [E-mail] from Viewer where F_Name = " + fname + "
and L_Name = " + lname + " and City = " + city + " and Phone 
= " + phone + " and [E-mail] = " + email +  ") begin Insert 
into Viewer (F_Name, L_Name, Competition_ID, City ,Phone, [E-mail], Reserve_ID) values (?,?,?,?,?,?,?) end

请告诉我为什么这个查询不起作用???

出现此错误:无效的列名'????'

【问题讨论】:

  • 哪一列不应该重复?只需将其定义为unique at table。
  • @Riad 除了 Competition_ID 和 Reserve_ID 是其他表中的外键并且自动递增之外的所有这些!
  • 然后制作一个复合键...使用alter table add unique .....
  • 你能提供更多关于编写查询的细节吗?

标签: sql sql-server jsp stored-procedures


【解决方案1】:

为什么不试试 像

SET @SQL='if not exists (select F_Name, L_Name, City, Phone, [E-mail] 
                from Viewer 
             where F_Name = ' + @fname + '            '
                      and L_Name = ' + @lname + ' 
                  and City = ' + @city + '
                  and Phone = ' + @phone + '
                  and [E-mail] = ' + @email + ' )   ''
EXCUTE @SQL
                  begin 
                  Insert into Viewer (F_Name, 
                                      L_Name, 
                                  Competition_ID, 
                                  City ,Phone, 
                                  [E-mail], 
                                  Reserve_ID) values (?,?,?,?,?,?,?) end

【讨论】:

  • 对不起,我不能用它。因为引号不可读,让我感到困惑!还有一个问题是,我可以在preparedStatement中使用它吗???
  • 插入变量(@fname,@lname,?,@city,@phone,@email,?)并完成?具有新的价值观。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多