在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
有用的書:
_Befor e_插入/更新,對嗎? – 2011-05-31 21:22:16
我會在自己之後使用,因爲如果您使用before觸發器,觸發器可能會更改行的值。 – 2011-05-31 22:00:55
如果唯一性失敗,是不是取消插入/更新操作太遲的後觸發? – 2011-05-31 22:23:52