Question

I am working on a project in which I need to adjust rules that fire for different point values on transactions to determine what happens to them. I have a table of rules, their current point values, and their new point values. I have a table of transactions. And I have a table of rule-transaction occurrences, to make it possible to navigate the many-to-many relationship between rules and transactions. I need to know the total current and new scores for each transaction, to do some further analysis. I can put this in a temp table during my analysis, but when I did that it was haltingly slow to work with. So, I decided to stage the scores in the Transactions table in new columns.

The code below updates the Transactions table to have the correct values in CurrentScore and NewScore columns. My concern is that the temp table I'm using, temp1, is slower than a @temp1 table variable. I couldn't test that possibility, though, as the following:

UPDATE dbo.Transactions
SET dbo.Transactions.CurrentScore = @temp1.CurrentScore
FROM dbo.Transactions INNER JOIN
@temp1 ON dbo.transactions.id=@temp1.transid

...produces a syntax error. The working code is below. Any ideas, or can table variables not be used in this context?

IF Object_ID('temp1') IS NOT NULL
DROP TABLE temp1
CREATE TABLE temp1 (TransID Int,CurrentScore Int, NewScore Int,
    CONSTRAINT PK_temp1 PRIMARY KEY (TransID))

INSERT INTO dbo.temp1 (TransID,CurrentScore,NewScore) 
SELECT dbo.transactions.ID, 
ISNULL(SUM(dbo.Rules.CurrentScore),0), 
ISNULL(SUM(dbo.Rules.NewScore),0)
    FROM dbo.Rules INNER JOIN
    dbo.RulesTripped ON dbo.rulestripped.ruleid=dbo.rules.id RIGHT OUTER JOIN
    dbo.Transactions ON dbo.rulestripped.transid=dbo.transactions.id
    GROUP BY dbo.transactions.id

UPDATE dbo.Transactions
SET dbo.Transactions.CurrentScore = temp1.CurrentScore,
    dbo.Transactions.NewScore = temp1.NewScore
FROM dbo.Transactions INNER JOIN
dbo.temp1 ON dbo.transactions.id=dbo.temp1.transID

DROP TABLE temp1
Was it helpful?

Solution

Try using aliases.

UPDATE T
SET CurrentScore = T1.CurrentScore
FROM dbo.Transactions T
     JOIN @temp1 T1 ON T.id=T1.transid

As for

My concern is that the temp table I'm using, temp1, is slower than a @temp1 table variable. I couldn't test that possibility

Well, it depends. For example, if the tempdb is under heavy load then result may be even opposite.
For full information about temp tables and table variables please read Martin Smith's answer on What's the difference between a temp table and table variable in SQL Server?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top