在插入SQL Server之前检查重复项 [英] Check duplicate entry before inserting into SQL Server

查看:114
本文介绍了在插入SQL Server之前检查重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想在SQL Server数据库中插入一些条目。但是我需要在插入之前进行检查。关键是该表包括两列 id name 。如果条目与SQL Server数据库中的条目完全相同,则所提供的代码应检查两列,并防止插入该条目。

I just want to insert some entries into a SQL Server database. But I need to check before inserting. The key point is that the table includes two columns id and name. The presented code should check both columns and prevent the entry to be inserted if the entry is exactly the same as in the SQL Server database.

意思是数据表的两列与要插入的两个条目相同。我查看了论坛,但找不到适合我项目的任何有用的解决方案。

Meaning that two columns of data table are same as two entries going to be inserted. I checked the forums but couldn't find any useful solution for my project.

private void button4_Click(object sender, EventArgs e)
{
      try
      {
           objConnection.Open();
           string query = "INSERT INTO TutorTable(Tid, Tname) VALUES(N'" + tidTextBox.Text + "','" + tnameTextBox.Text + "')";

           SqlDataAdapter SDA = new SqlDataAdapter(query, objConnection);

           SDA.SelectCommand.ExecuteNonQuery();

           objConnection.Close();
           MessageBox.Show("ok!");
       }
       catch(Exception ex)
       {
           MessageBox.Show("error");
       }

       objConnection.Close();      
}


推荐答案

这篇文章解释了该问题的解决方案。

This post explains a solution to the problem.

基本上,您可以首先使用以下方法检查特定行的存在:

Essentially you can check the existence of a particular row first using:

IF NOT EXIST( SELECT 1 FROM TutorTable WHERE Tid = @tid)
BEGIN
    <your insert statement...>
END

(这也使用了参数而不是rene建议的直接值)

(This is also using a parameter instead of directly values as suggested by rene)

然后您可以从 ExecuteNonQuery 来查看实际插入了多少行。

You can then check the return value from ExecuteNonQuery to see how many rows were actually inserted.

这篇关于在插入SQL Server之前检查重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆