I am trying to add a column (MSSQL 2005) to a table (Employee) with a default constraint of a primary key of another table (Department). Then I am going to make this column a FK to that table. Essentially this will assign new employees to a base department based off the department name if no DepartmentID is provided.
This does not work:
DECLARE @ErrorVar INT DECLARE @DepartmentID INT SELECT @DepartmentID = DepartmentID FROM Department WHERE RealName = 'RocketScience' ALTER TABLE [Employee] ADD [DepartmentID] INT NULL CONSTRAINT [DepartmentIDOfAssociate] DEFAULT (@DepartmentIDAssociate) SELECT @ErrorVar = @@Error IF (@ErrorVar <> 0) BEGIN GOTO FATAL_EXIT END
The Production, Test, and Development databases have grown out of synch and the DepartmentID for the DepartmentName = ‘RocketScience’ may or may not be the same so I don’t want to just say DEFAULT (somenumber). I keep getting “Variables are not allowed in the ALTER TABLE statement” no matter which way I attack the problem.
What is the correct way to do this? I have tried nesting the select statement as well which gets “Subqueries are not allowed in this context. Only scalar expressions are allowed.”
In Addition, what would be really great I could populate the column values in one statement instead of doing the
{ALTER null}
{Update values}
{ALTER not null}
steps. I read something about the WITH VALUES command but could not get it to work. Thanks!!!
You could wrap the code to find your department ID into a stored function and use that in your DEFAULT constraint statement:
And then:
Does that help?
Marc