3

値が 2 つの列で一意であることを保証する必要があります (これは「2 つの列」インデックスの問題ではありません)。

Table A
Column A1       Column A2

Memphis         New York     -> ok
San Francisco   Miami        -> ok
Washington      Chicago      -> ok
Miami           Las Vegas    -> Forbidden ! Miami already exists 

出来ますか ?

私の例は都市ですが、それに焦点を合わせないでください。私の本当の必要性は、生成された 16 進数の ID です。

4

2 に答える 2

3

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

役に立つ読み物:

于 2011-06-01T00:03:19.897 に答える
2

挿入/更新後に検索する制約トリガーを追加する必要があります。

于 2011-05-31T15:40:47.853 に答える