我正在写一个我坚持使用它的查询。
要求我们只需要在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
提前致谢
答案 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
答案 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;