Have the following update statement in SQL Server:
UPDATE MY_TABLE
SET COLUMN1 = FN_GETFIRSTVALUE(T.VALUE1),
COLUMN2 = FN_GETSECONDVALUE(T.VALUE1, T.COLUMN1)
FROM MY_TABLE AS T
INNER JOIN ...
So FN_GETSECONDVALUE accepts an input parameter which is returned from FN_GETFIRSTVALUE. I thought about using a table function… but I can’t see how I could update two columns with this. Is there another / better way to do this? I don’t want to call the function twice, or split it into a select / update.
The smallest change to your example would be as follows…
SQL server is good at re-using results and so the first function does not necessarily get executed twice. It is, however, still a bit messy to even write the call to the function twice.
Instead you can write the re-use yourself using
APPLY…Even better, you can re-write your function as a Table Valued Function. Even if it only returns one field in one record…
In both cases this performs much better if the Table Valued functions as defined as Inline-Functions (just a single query) than if the are defined as Multi-Statement-Functions (including internal variables, IF statements, etc).
Finally, depending on your needs you can even wrap both functions into one…
(Where the function returns one record with 2 fields, named
val1andval2.)So, all in all, you have a whole host of options here. And that’s just using
APPLY, there are other option with Common Table Expressions…So many options…