I’d like to use the column’s default value in an stored procedure insert, so that I don’t have to repeat the default value in multiple places (it could change… DRY principle).
The T-SQL INSERT operation has a handy ‘default’ keyword that I can use as follows:
Declare @newA varchar(10)
Set @newA = 'Foo2'
-- I can use "default" like so...
Insert into Table_1 (
A,
B)
Values (
@newA,
default)
However, If I need to do something conditional, I can’t seem to get 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 could insert the default, and then update as needed like so:
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’d really like somebody to tell me “There’s a better way…”
Here’s a 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
defaultonly works from within aVALUES()block, which does not seem to be an acceptable value in aCASEstatement; you could use an if statement to determine what to insert:I think this is better than updating after an insert, so that you only insert correct data into your table. It also keeps the number of INSERTS/UPDATES to 1. You should also be careful when you using @@IDENTITY due to scoping. Consider looking into SCOPE_IDENTITY().