Given the following table variable, which contains let’s say some 10K records:
DECLARE @SomeTable TABLE
(
ID int IDENTITY (1, 1) PRIMARY KEY NOT NULL,
Name varchar(100),
CustomerMailingAddress1 varchar(100),
CustomerMailingAddress2 varchar(100),
CustomerMailingAddress3 varchar(100),
CustomerMailingAddress4 varchar(100),
ContactInfo1 nvarchar(256),
ContactInfo2 nvarchar(256)
)
Currently the table variable gets updated within a sproc as follows:
UPDATE st
SET
ContactInfo1 = ci.ContactInfo1,
ContactInfo2 = ci.ContactInfo2
FROM @SomeTable st, dbo.ContactInfoFunc() AS ci
The table function dbo.ContactInfoFunc() simply retrieves the MAX record according to primary key of a table with a single record (it’s company contact info which will seldom if ever change).
Performance-wise is the above update more expensive? In other words, would there be any advantage to rewriting the update to eliminate the join to the table function output as follows:
DECLARE @ContactInfo1 nvarchar(256), @ContactInfo2 nvarchar(256)
SELECT @ContactInfo1 = ContactInfo1, @ContactInfo2 = ContactInfo2
FROM dbo.ContactInfoFunc()
UPDATE st
SET
ContactInfo1 = @ContactInfo1,
ContactInfo2 = @ContactInfo2
FROM @SomeTable st
Or is it a toss-up? Would the query optimizer be smart enough to cache the output of the table function or would it spin its wheels executing the function for each row being updated?
Not sure what else you’re doing with the table variable, but why do you need to update it at all? Let’s assume you just end up doing a
SELECTfrom it at the end. So your code could easily be:Now, my answer would be different if the function actually took parameters, and the output depended on those parameters. Then it might make sense to perform a
CROSS APPLYperhaps… but again not to perform anUPDATE, just as a function of the finalSELECT…