且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止sql server中的重复值

更新时间:2023-01-22 16:53:19

你好,



最简单的方法是在你不想要重复值的列上定义一个唯一索引。这样,如果进行了这样的尝试,它自己的数据库服务器将抛出异常。



其他方法是检查SQL语句。例如。
  SELECT  COUNT( 1  FROM  table_name  WHERE  dup_col_name = value_to_insert 

如果此查询返回的计数大于0,则表示 value_to_insert 已存在于表中,您不应继续插入。



问候,


避免插入多个数据的最简单方法是编写存储过程 [ ^ ]。有关存储过程的更多信息,请参阅 MSDN [ ^ ]。



你需要这样的东西:

  CREATE   PROCEDURE  GetMachineCode 
@ mc NVARCHAR 30
AS
BEGIN
- 从tblMachinaryType中选择*,其中MTCode =' + txtMachinaryCode.Text.Trim()+'
DECLARE @ tmpmc NVARCHAR 30

SELECT @ tmpmc = MTCode
FROM tblMachinaryType
WHERE MTCode = @ mc

IF (ISNULL( @ tmpmc ))
BEGIN
INSERT INTO tblMachinaryType(MTCode)
VALUES ( @ mc
END

- 返回受INSERT INTO语句影响的行数
RETURN @@ ROWCOUNT

END 跨度>


I want to enter data in database from a textbox. The name of the table is tblMachinaryType. But I don''t want to insert duplicate data. I mention my method below : But it does not result that I want
Please give me solution as early as possible.

private void SaveData()
    {
        DataTable DTLocal = null;
        DataView DVLocal = null;
        DataRow DRLocal = null;
        string strSQL = "";
        try
        {
            DTLocal = new DataTable();
            DVLocal = new DataView();
            strSQL = "Select * from tblMachinaryType where MTCode = '" + txtMachinaryCode.Text.Trim() + "'";
            ConManager.DBConnection("TERMSHR");
            ConManager.OpenDataTableThroughAdapter(strSQL, out DTLocal, true);
            DTLocal.TableName = "MachinaryType";
            DVLocal.Table = DTLocal;
 
                DRLocal = DTLocal.NewRow();
                DataTable dt = new DataTable();
                string strsql = "select * from tblMachinaryType";
                ConManager.OpenDataTableThroughAdapter(strsql, out dt, true);
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i][1].ToString().Trim() != txtMachinaryType.Text.Trim())
                        {
                            DRLocal["MTCode"] = txtMachinaryCode.Text.Trim();
                            DRLocal["MachinaryType"] = txtMachinaryType.Text.Trim();
                        }

                    }
                }

               // DRLocal["MTCode"] = txtMachinaryCode.Text.Trim();
               // DRLocal["MachinaryType"] = txtMachinaryType.Text.Trim();
                DTLocal.Rows.Add(DRLocal);
                       
 
            ConManager.BeginTransaction();
            ConManager.SaveDataTableThroughAdapter(ref DTLocal, true);
            ConManager.CommitTransaction();
            ConManager.CloseConnection();
        }
        catch (System.Exception ex)
        {
            throw ex;
 
        }
        finally
        {
            //         

        }
    }

Hello,

The simplest way would be to define a unique index on the column in which you don''t want duplicate values. This way the database server it self will throw an exception if such an attempt is made.

Other way is to check with a SQL statement. eg.
SELECT COUNT(1) FROM table_name WHERE dup_col_name = value_to_insert

If this query returns a count greater than 0 then it means that value_to_insert is already present in the table and you should not proceed with insert.

Regards,


The simplest way to avoid inserting multiple data is to write stored procedure[^]. More about stored procedures, you''ll find on MSDN[^].

You need something like this:
CREATE PROCEDURE GetMachineCode
    @mc NVARCHAR(30)
AS
BEGIN
    --Select * from tblMachinaryType where MTCode = '" + txtMachinaryCode.Text.Trim() + "'"
    DECLARE @tmpmc NVARCHAR(30)
    
    SELECT @tmpmc = MTCode
    FROM tblMachinaryType
    WHERE MTCode = @mc

    IF (ISNULL(@tmpmc)) 
    BEGIN
        INSERT INTO tblMachinaryType (MTCode) 
        VALUES(@mc)
    END

    --return the number of rows affected by INSERT INTO statement
    RETURN @@ROWCOUNT

END