<>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;
变化:
- Used @tempTable rather than
tempTable (in memory v. written to disk) as required by udf
- passed @fk1 as a parameter so I can select for uniqueness within one group of fk1 values.
- 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.