SQL约束在两列中有一个唯一值
问题描述:
我需要确保两列中的值是唯一的(这不是“两列”索引问题)。SQL约束在两列中有一个唯一值
Table A
Column A1 Column A2
Memphis New York -> ok
San Francisco Miami -> ok
Washington Chicago -> ok
Miami Las Vegas -> Forbidden ! Miami already exists
这可能吗?
我的例子是与城市,但不集中在那。我真正的需要是关于生成的十六进制ID。
答
您需要添加一个约束触发器,在插入/更新后查找它。
答
在SQL Server中,可以通过索引视图的帮助实施唯一性。你还需要一个数字表(如果你还没有的话)与你的Table A
在同一个数据库中。
这里是我的测试脚本一些意见:
CREATE TABLE MyNumbersTable (Value int);
-- You need at least 2 rows, by the number of columns
-- you are going to implement uniqueness on
INSERT INTO MyNumbersTable
SELECT 1 UNION ALL
SELECT 2;
GO
CREATE TABLE MyUniqueCities ( -- the main table
ID int IDENTITY,
City1 varchar(50) NOT NULL,
City2 varchar(50) NOT NULL
);
GO
CREATE VIEW MyIndexedView
WITH SCHEMABINDING -- this is required for creating an indexed view
AS
SELECT
City = CASE t.Value -- after supplying the numbers table
WHEN 1 THEN u.City1 -- with the necessary number of rows
WHEN 2 THEN u.City2 -- you can extend this CASE expression
END -- to add more columns to the constraint
FROM dbo.MyUniqueCities u
INNER JOIN dbo.MyNumbersTable t
ON t.Value BETWEEN 1 AND 2 -- change here too for more columns
GO
-- the first index on an indexed view *must* be unique,
-- which suits us perfectly
CREATE UNIQUE CLUSTERED INDEX UIX_MyIndexedView ON MyIndexedView (City)
GO
-- the first two rows insert fine
INSERT INTO MyUniqueCities VALUES ('London', 'New York');
INSERT INTO MyUniqueCities VALUES ('Amsterdam', 'Prague');
-- the following insert produces an error, because of 'London'
INSERT INTO MyUniqueCities VALUES ('Melbourne', 'London');
GO
DROP VIEW MyIndexedView
DROP TABLE MyUniqueCities
DROP TABLE MyNumbersTable
GO
有用的书:
+0
该解决方案是否与9.999.999.999.999.999不同的值兼容? – Zofren 2011-06-03 22:15:20
+0
@Zofren:说实话,我不知道。 – 2011-06-04 09:08:30
_Befor e_插入/更新,对吗? – 2011-05-31 21:22:16
我会在自己之后使用,因为如果您使用before触发器,触发器可能会更改行的值。 – 2011-05-31 22:00:55
如果唯一性失败,是不是取消插入/更新操作太迟的后触发? – 2011-05-31 22:23:52