I would like to use the default value for the column in the insertion of the stored procedure, so I do not need to repeat the default value in several places (this can change ... the DRY principle).
The T-SQL INSERT operation has a convenient default keyword, which I can use as follows:
Declare @newA varchar(10) Set @newA = 'Foo2'
However, if I need to do something conditional, I cannot force the case statement to return 'default'.
-- How do I use 'default' in a case statement? INSERT INTO Table_1 ( A, B ) VALUES ( @newA, CASE WHEN (@newA <> 'Foo2') THEN 'bar' ELSE default END) -- > yeilds "Incorrect syntax near the keyword 'default'."
I can insert the default value and then update as needed like this:
INSERT INTO Table_1 ( A, B ) VALUES ( @newA, default) UPDATE Table_1 SET B = CASE WHEN (A <> 'Foo2') THEN 'bar' ELSE B END WHERE ID = SCOPE_IDENTITY()
But I would really like someone to tell me: "There is a better way ..."
Here's the table definition for this example if it helps ...
CREATE TABLE dbo.Table_1 ( ID int NOT NULL IDENTITY (1, 1), A varchar(10) NULL, B varchar(10) NULL ) GO ALTER TABLE dbo.Table_1 ADD CONSTRAINT DF_Table_1_A DEFAULT 'A-Def' FOR A GO ALTER TABLE dbo.Table_1 ADD CONSTRAINT DF_Table_1_B DEFAULT 'B-Def' FOR B GO
source share