0

I have a table where I'd like to set two of its columns' default values to the same value. I'm using a SQL function which generates a unique value. I can set a column default for one of the columns easily enough using the function:

[PreCode] NVARCHAR(20) NOT NULL DEFAULT([dbo].GetPreCode()),

But how would I use the same value in my other column? I'd assume that if I used the same syntax as above for the other column that the function would generate another unique value instead of using the value that was generated for the first column. How can I get both columns to have the same default value from a single call to the SQL function?

8
  • 1
    If the purpose of that function is to generate a unique value every time it's called, how do you expect to return the same value for multiple calls? Commented Mar 7, 2017 at 16:36
  • You can't. There's no way you can pass any context to the function about what row you're generating data for, and this is a hard requirement if you want the function to return identical values in one single row. If you know for sure only one row is ever inserted, you can do shady stuff like key off sys.dm_tran_current_transaction in the function, but it's probably far more sane to do this in the code that performs the actual inserts, wrap it in a stored procedure, or use an AFTER INSERT trigger. Commented Mar 7, 2017 at 16:37
  • 2
    Use a INSTEAD OF INSERT trigger and set it quietly Commented Mar 7, 2017 at 16:38
  • @RickS, that's exactly why I'm asking the question. Commented Mar 7, 2017 at 16:44
  • 2
    You would need to call the function exactly once, and store that value in a variable, and apply it to both columns. You can do this with a trigger (I prefer INSTEAD OF but you can also do it with an AFTER). If you have full control over the DML (e.g. all writes go through a stored procedure or data access layer), you could change that to generate the value, but you'd still need a trigger if you want to be sure that the values get set correctly when people go around your DAL. Yes, a trigger can detect whether a value has been supplied. Just take care up front that it handles mutli-row inserts. Commented Mar 7, 2017 at 16:47

1 Answer 1

1

You can use an INSTEAD OF INSERT trigger to set it, or you can have the second column be a computed column and set the value to that of the first.

You can try setting the second columns default value to the value of the first, but I'm not sure if it would wait for the first to be set before setting that of the second or if it would set it to NULL before applying a value to the first.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.