I've got code similar to the following in a stored procedure that inserts a row into a table, I'd like to set the last column (FieldD) to @prmSomeValue unless it is null, otherwise just use the default value defined for that column.
IF (@prmSomeValue IS NULL)
INSERT INTO MyTable (fieldA,FieldB,FieldC)
SELECT A,B,C
FROM MyOtherTable
ELSE
INSERT INTO MyTable (fieldA,FieldB,FieldC,FieldD)
SELECT A,B,C,@prmSomeValue
FROM MyOtherTable
This works, but violates the DRY principle. I'm trying to find some way to do this with a single insert statement. Something along the lines of the following pseudocode.
INSERT INTO MyTable (fieldA,FieldB,FieldC,FieldD)
SELECT A,B,C,ISNULL(@prmSomeValue,DEFAULT)
FROM MyOtherTable
Anyone have any ideas?
Update - One more twist
The default constraint is not a literal value, but a function as shown below.
...DEFAULT (suser_sname()) FOR [FieldD]
Update
I finally punted and chose the lesser of evils and just copied the default value function into my query instead of falling through to the default configured for the column. I don't love it, but it gets the job done with less repetition in my query.
INSERT INTO MyTable (fieldA,FieldB,FieldC,FieldD)
SELECT A,B,C,ISNULL(@prmSomeValue,suser_sname())
FROM MyOtherTable
Select the column for which you want to specify a default value. In the Column Properties tab, enter the new default value in the Default Value or Binding property. To enter a numeric default value, enter the number. For an object or function enter its name.
Use the DEFAULT clause in the CREATE TABLE statement to specify the default value for the database server to insert into a column when no explicit value for the column is specified. This syntax fragment is part of the Column definition.
WITH VALUES --Add if Column is Nullable and you want the Default Value for Existing Records. Another way : Right click on the table and click on Design,then click on column that you want to set default value. Then in bottom of page add a default value or binding : something like '1' for string or 1 for int.
Since essentially this is what SQL Server is doing, you could do something like this to at least avoid two nearly identical statements (pseudo-code):
INSERT (columnA,B,C) ... ;
IF @prmSomeValue IS NOT NULL
UPDATE ... ;
I don't think there is a way to COALESCE with the default value.
I would say your method is fine. A simple check followed by one insert. If you are worried about DRY, encapsulate the call so that it be called repeatedly.
I would say that inserts/updates on a db may be costly on some tables (depends on the design goal) so if you have to write extra code to to handle this scenario then I see no problem with the trade off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With