English 中文(简体)
某些价值相同的一组记录中的独一无二的制约因素
原标题:Unique constraint within a group of records where some value is the same

<>DBMS>: 2005年,MS Sql服务器

我在表一栏中仅限一个记录具有特殊价值(各行在某一栏中具有价值)。 这是可能的吗?

Example: I have records in myTable which have a non-unique foreign key (fk1), and a bit column called isPrimary to mark out that this particular one should be used by our app for special logic.

它抽象地看待这一点:

myTable
-------------
pk1       (int, not null)
name      (varchar(50), null)
fk1       (int, not null)
isPrimary (bit, not null)

我想确保有one和只有一个记录,每个独特价值为 fk1,其法定旗帜为1。

Data example: This should be legal:

pk1     name     fk1    isPrimary
----    -----    -----  ----------
1       Bill     111    1
2       Tom      111    0
3       Dick     222    1
4       Harry    222    0

但是,这应当<>而不是(超过1k=111):

pk1     name     fk1    isPrimary
----    -----    -----  ----------
1       Bill     111    1
2       Tom      111    1
3       Dick     222    1
4       Harry    222    0

这两种情况(在fk=222的地方)都不应如此。

pk1     name     fk1    isPrimary
----    -----    -----  ----------
1       Bill     111    1
2       Tom      111    0
3       Dick     222    0
4       Harry    222    0

是否有办法用表上的限制来做到这一点?

UPDATE I ve gone with Martin Smith s answer for now, though I ll be pushing for JohnFx s refactor in an upcoming release, as it s the best long-term solution. However I wanted to post my updated UDF based on Raze2dust s answer, in case future readers decide that is a better fit for their needs.

CREATE FUNCTION [dbo].[OneIsPrimaryPerFK1](@fk1 INT, @dummyIsPrimary BIT)
RETURNS INT
AS 
BEGIN
    DECLARE @retval INT;
    DECLARE @primarySum INT;
    SET @retval = 0;
    DECLARE @TempTable TABLE (
    fk1 INT,
    PrimarySum INT)

INSERT INTO @TempTable
    SELECT fk1, SUM(CAST(isPrimary AS INT)) AS PrimarySum
    FROM FacAdmin
    WHERE fk1 = @fk1
    GROUP BY fk1;

    SELECT @primarySum = PrimarySum FROM @TempTable;
    IF(@primarySum=1)
        BEGIN
            SET @retval = 1
        END
    RETURN @retval
END;

变化:

  1. Used @tempTable rather than

    tempTable (in memory v. written to disk) as required by udf

  2. passed @fk1 as a parameter so I can select for uniqueness within one group of fk1 values.
  3. tricky had to also pass isPrimary even though it isn t necessary for the logic of the function, otherwise the SQL2005 optimizer will not run the check constraint when isPrimary is updated.
最佳回答
问题回答

自我对第一个问题提出批评以来,我们开始作出新的回答。

你可以重新思考你的桌子设计,避免使你成为执行你业务规则的制约因素,从而解决这个问题。

如何从MyTable中删除大专栏,在提到主要人物的另一张表格中增加一栏?

这样,结构本身就可以强制规定,个人在家庭预算表中只有1个入境点。

2005年5月5日至5日,日内瓦 然而,2005年解决该问题的办法有几个:

  1. Create an Indexed view that filters for IsPrimary = 1 and add a unique index to that view.
  2. Create a trigger where you ensure only one can be primary.
  3. Encapsulate your logic into a stored proc and force users to go through the stored proc to insert or update from your table.

您可以尝试创建一种功能,然后使用检查限制:

CREATE FUNCTION ChkFn()
RETURNS INT
AS 
BEGIN
   DECLARE @retval INT
   DECLARE @distinct INT
   DECLARE @top INT
   SET @retval = 0
   SELECT fk1 AS ForeignKey, SUM(isPrimary) AS PrimarySum
    INTO #TempTable 
    FROM myTable
    GROUP BY fk1
   SELECT @distinct = COUNT(DISTINCT(PrimarySum)) FROM #TempTable
   SELECT @top = top PrimarySum FROM #TempTable
   IF(@distinct=1 AND @top=1)
    BEGIN
    @retval = 1
    END
   RETURN @retval
END;
GO

ALTER TABLE myTable
ADD CONSTRAINT chkFkPk CHECK (dbo.ChekFn() = 1 );
GO

问它,让我知道它是否奏效。 然而,这并不令人信服。





相关问题
what is wrong with this mysql code

$db_user="root"; $db_host="localhost"; $db_password="root"; $db_name = "fayer"; $conn = mysqli_connect($db_host,$db_user,$db_password,$db_name) or die ("couldn t connect to server"); // perform query ...

Users asking for denormalized database

I am in the early stages of developing a database-driven system and the largest part of the system revolves around an inheritance type of relationship. There is a parent entity with about 10 columns ...

Easiest way to deal with sample data in Java web apps?

I m writing a Java web app in my free time to learn more about development. I m using the Stripes framework and eventually intend to use hibernate and MySQL For the moment, whilst creating the pages ...

join across databases with nhibernate

I am trying to join two tables that reside in two different databases. Every time, I try to join I get the following error: An association from the table xxx refers to an unmapped class. If the ...

How can I know if such value exists in database? (ADO.NET)

For example, I have a table, and there is a column named Tags . I want to know if value programming exists in this column. How can I do this in ADO.NET? I did this: OleDbCommand cmd = new ...

Convert date to string upon saving a doctrine record

I m trying to migrate one of my PHP projects to Doctrine. I ve never used it before so there are a few things I don t understand. In my current code, I have a class similar to this: class ...

热门标签