Let’s say I have a table defined as follows:
CREATE TABLE SomeTable
(
P_Id int PRIMARY KEY IDENTITY,
CompoundKey varchar(255) NOT NULL,
)
CompoundKey is a string with the primary key P_Id concatenated to the end, like Foo00000001 which comes from “Foo” + 00000001. At the moment, entries insertions into this table happen in 2 steps.
- Insert a dummy record with a place holder string for CompoundKey.
- Update the CompoundKey with the column with the generated compound key.
I’m looking for a way to avoid the 2nd update entirely and do it all with one insert statement. Is this possible? I’m using MS SQL Server 2005.
p.s. I agree that this is not the most sensible schema in the world, and this schema will be refactored (and properly normalized) but I’m unable to make changes to the schema for now.
Your could use a computed column; change the schema to read:
This way, SQL Server will automagically give you your compound key in a new column, and will automatically maintain it for you. You may also want to look into the
PERSISTkeyword for computed columns which will cause SQL Server to materialise the value in the data files rather than having to compute it on the fly. You can also add an index against the column should you so wish.