需要在列中仅允许两个重复值

时间:2015-04-13 07:37:00

标签: sql

我正在写一个我坚持使用它的查询。

要求我们只需要在DB

中输入两个重复值

实施例

Id   Name
1    Marry
2    Marry
3    Marry --> this entry should not be allowed only Id 1&2 should not be allowed to enter
4    John

提前致谢

2 个答案:

答案 0 :(得分:0)

SQL-Server 中选择最多包含2个重复项的数据可能类似于:

CREATE TABLE #Temp
(
    Id INT,
    Name NVARCHAR(60)
)
GO
INSERT INTO #Temp (Id, Name) VALUES (1, 'Marry'), (2, 'Marry'), (3, 'Marry'), (4, 'John')
GO
SELECT Id, Name 
FROM (
        SELECT ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Id) RN, *
        FROM #Temp  
        GROUP BY Name, Id
     ) x
WHERE RN < 3
ORDER BY Id
GO
DROP TABLE #Temp

<强>输出:

Id  Name
1   Marry
2   Marry
4   John

SQL FIDDLE

答案 1 :(得分:0)

你可能想要使用这样的触发器:

CREATE TRIGGER trigger_name
BEFORE INSERT
   ON your_table
DECLARE
  rowsCount NUMBER;
BEGIN
  SELECT COUNT(*)
    INTO rowsCount
    FROM your_table
   WHERE NAME = NEW.NAME;

  IF rowsCount >= 2 THEN
    -- Stop action, depends on your DBMS. It can be exception or set NEW to be NULL or whatever you like.
  END IF;
END;