在sql表中插入两个相同的值,如果在第三次插入相同的值则不允许插入该记录

时间:2017-09-28 06:16:28

标签: sql tsql

create table sample(id int primary key,name varchar(100))
insert into sample values(1,'a')
,(2,'a')
,(3,'d')
,(4,'b')
,(5,'b')

--insert into sample values(6,'a'),(7,'b')

此记录不允许插入table.it disply错误

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是检查表,如果插入的值在insert语句之前已经存在于表中两次。

--Preparation
DECLARE @sample  TABLE
(
    id INT IDENTITY PRIMARY KEY --USE IDENTITY to auto increment your primary key
    ,name VARCHAR(100)
)
--Initial Values
INSERT INTO @sample
VALUES
('a')
,('a')
,('d')
,('b')
,('b')

DECLARE @name VARCHAR(100)
SET @name = 'a'

IF(SELECT COUNT(id) FROM @sample WHERE name = @name) <= 1
BEGIN
    INSERT INTO @sample
    VALUES (@name)
END
ELSE
BEGIN
    SELECT 'Error: Name ''' + @name + ''' already exists twice. Only two same values are allowed in name field!'
END