0

I am trying to configure a "default value" for a column that has the same value as another column in a corresponding row. So I've tried doing this:

UPDATE table 
SET field1 = field2

But I don't want to do this manually, it should happen automatically whenever a new row gets inserted.

At first I thought this would be an easy task. But the best solution I found so far was a sql script stored in a job which gets started by our SQL server agent.

Is there a solution that works like a default value? Or is my idea stupid, since I try to create a "default value" based on a value which doesn't even exist until the insert happens? In that case: I'm asking for a friend...

Thank you for your help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
J. N.
  • 3
  • 3

1 Answers1

0

Your best shot will be to use a trigger right there. You can do something like this:

CREATE TRIGGER [dbo].[YourTrigger] ON  [dbo].[YourTable] FOR INSERT
AS 
BEGIN
     DECLARE @ID AS INT
     SET @ID = SELECT yourID FROM INSERTED

     UPDATE YourTable
     SET field1 = field2
     WHERE yourID = @ID
END
NicoRiff
  • 4,803
  • 3
  • 25
  • 54
  • Thank you for your answer. I will create a trigger loke this. It looks like it solves my problem. – J. N. Oct 18 '17 at 15:20