Skip to main content
Spurious Logic

ka-Pow!!!

Take that! unnecessary table variable! Removed by the power of common table expressions!

I have a table in the form:

IDSellerDescription
1Alicewidget1
2Alicewidget2
3Bobwidget1
4Bobwidget3
5Bobwidget4

But what I really need is a table with an extra column with a sales id for each seller, like this;

IDSellerSales IdDescription
1Alice1widget1
2Alice2widget2
3Bob1widget1
4Bob2widget3
5Bob3widget4

In a past life I would have written the alter script to add in the column, with an empty field (null or -1); created a temporary table to iterate over every 'Alice' sale and set those values, followed by those for 'Bob'. And this is what you get when you're thinking procedurally. Using Common Table Expressions and a Partition makes this far more efficient (at the cost of more complicated code).

WITH cte (ID, seller, sales_id) AS    (       SELECT          ID,          seller,          ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID)       FROM sales WITH (NOLOCK)    ) UPDATE S SET S.sales_id = C.Pattern_ID FROM sales S INNER JOIN cte C    ON S.ID = C.ID AND S.seller = C.seller

And hey! a legitimate reason to actually use a

on a webpage without designers shaking their goate-ed heads at my foolishness.