I want a table to include these columns:
UserID, int, IDENTITY
GroupID, int
I would like for the default value of the GroupID to be equal to the UserID.
The problem is the default only accepts a constant value. Any way to
accomplish this?
Thanks.You can create a trigger to set the GroupID to the UserID value.
CREATE TABLE Foo (
UserID INT IDENTITY NOT NULL PRIMARY KEY,
GroupID INT,
datacol CHAR(1));
GO
CREATE TRIGGER SetGroupID
ON Foo
AFTER INSERT
AS
UPDATE Foo
SET GroupID = I.UserID
FROM Foo AS F
JOIN Inserted AS I
ON F.UserID = I.UserID
AND I.GroupID IS NULL;
GO
INSERT INTO Foo (datacol) VALUES('a');
INSERT INTO Foo (GroupID, datacol) VALUES(5, 'b');
SELECT UserID, GroupID, datacol
FROM Foo;
HTH,
Plamen Ratchev
http://www.SQLStudio.com
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment