如何避免在ms sql中重复同一行?

时间:2013-05-30 07:19:21

标签: sql-server

如何避免在ms sql中多次插入同一行?

     SqlCommand cmd1 = new SqlCommand("insert student_vs_testsession_details(student_id,testsession_id,testsession_status,test_type) values('" + id + "','" + Test + "','','" + s_testtype + "') where  NOT EXISTS(select student_id from student_vs_testsession_details where testsession_id='" + lb_testid.Text + "' and student_id='"+id+"')", con);

1 个答案:

答案 0 :(得分:1)

您应该将(student_id, testsession_id)作为表的主键,然后无法为这对属性插入两个具有相同值的元组。 有关详细信息,请参阅SQL server reference。我相信语法应该是这样的:

CREATE TABLE student_vs_testsession_details (
    student_id integer,
    testsession_id integer,
    ...,
    CONSTRAINT MY_PRIMARY_KEY_CONSTRAINT
           PRIMARY KEY CLUSTERED (student_id, testsession_id)
           WITH (IGNORE_DUP_KEY = ON)
);

或者您可以add the primary key constraint使用ALTER TABLE声明。

[编辑]

如果您不想使用主键约束,可以创建UNIQUE约束(see Reference),如下所示:

CREATE TABLE student_vs_testsession_details (
    student_id integer,
    testsession_id integer,
    something_else varchar(10),
    CONSTRAINT MY_UNIQUE_CONSTRAINT
           UNIQUE (student_id, testsession_id)
);

或添加约束:

ALTER TABLE student_vs_testsession_details ADD CONSTRAINT MY_UNIQUE_CONSTRAINT
    UNIQUE (student_id, testsession_id);