插入时避免重复数据

时间:2014-12-20 17:26:34

标签: sql sql-server jsp stored-procedures

我想避免在具有自动增量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

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

发生此错误:列名无效' ????'

1 个答案:

答案 0 :(得分:0)

为什么不试试

之类的东西
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
相关问题