SQL refactoring: replace insert cursor with table variable

I lost my copy of the classic programmer’s cookbook Refactoring several years ago, alas, but its philosophy of careful replacement of smelly code with clean code to improve the performance and maintainability of a software program is one that has stayed with me long after I ceased being an active programmer. One regret I had about the book was that it primarily addressed refactoring for object oriented languages (all the examples were in Java). But one of the biggest opportunities for cleaning up code is in non-object oriented languages such as Transact SQL. Recently I had an opportunity to clean up some legacy stored procedure code that I was adapting for an integration project I was working on, and one particular refactoring struck me as especially useful.

A common mistake when writing stored procedures is to overuse cursors. The cursor provides a way to operate on one row of data at a time, which is logical to a programmer used to thinking about working with arrays by looping through them. But SQL is fundamentally a language that is about set operations, and you can realize tremendous gains if you can stop operating on one row at a time and instead operate on a bunch of them at once. Microsoft provided a way to do that in SQL Server 2000 by introducing the table datatype.

Table variables help us by giving us an entire rowset in memory that acts precisely like a table in the database. An article by Alex Grinberg on SQL Server Central illustrates some of the applications of the table variable. I used one of the ideas to replace a cursor that was being used to import data into a table in our system using a counter table.

In fact, the counter table probably caused the use of the cursor in the first place, because a developer had helpfully written a stored procedure to get the next ID value from the table (a common construct for database structures that need to be cross-platform and therefore can’t use features like ). Such a function is a good idea in a client application because it enforces a consistent method for creating IDs for new records, but because it enforces getting only one ID at a time it leads inexorably to row-at-a-time inserts and other abuses of SQL.

So the first step in converting this insert cursor into a sensible insert was to create a new procedure that allowed me to get a bunch of IDs out at once. Where the original procedure had as inputs the table for which the counter was being incremented and the new ID as output, this one also took the number of keys, the starting key value, and the ending key value. Thus even for a very large number of rows, I was only performing a single transaction to get a block of keys to work with.

Now the cursor replacement. The original logic of the stored procedure declared a select cursor against the staging table containing the data to be imported, then opened the cursor, got a new id, and inserted the contents of the cursor plus the ID into the destination table. So for each row of data to be imported we performed two transactions, an update on the counter table and an insert to the destination table. For 500 rows, this was taking about 25 seconds—not huge, but definitely a place where there could be a big improvement. Here are the steps I used to replace the insert cursor:

  1. Declare a table variable, @tbl, with the same columns as the cursor, plus
    an ID column defined with the IDENTITY property.
  2. Populate @tbl with an INSERT INTO…SELECT FROM statement that draws data from the staging table. Now each row in @tbl has the values from the staging
    table plus a temporary ID, ranging from 1 to the number of rows. (We didn’t specify a seed for the ID field; more on that in a second.
  3. Count the number of rows in @tbl (select count(*) from
    @tbl
    ).
  4. Call the updated counter procedure with the number of rows in @tbl, getting
    back the first ID in the range (call it @startid.
  5. Finally, insert into the destination table, selecting from @tbl and adding
    @startid to the identity column in @tbl. Since the IDENTITY column
    started at 1, we want to subtract 1 from @startid for each row as well, or else
    we’ll exceed the range of keys reserved.

Here’s some sample code:

DECLARE @tbl TABLE (col1 int, col2 int, col3 int, temp_id IDENTITY (1,1))

INSERT INTO @tbl (col1, col2, col3)
SELECT stagecol1, stagecol2, stagecol3 FROM staging_table WHERE ...

DECLARE @startid int
DECLARE @total int

SELECT @total = COUNT (*) FROM @tbl

exec p_increment_counter_multi 'dest_table', @total, @startid OUTPUT

INSERT INTO dest_table ( dest_id, destcol1, destcol2, destcol3 )
SELECT temp_id + @startid - 1, col1, col2, col3 FROM @tbl

So instead of two transactions for each row in the staging table, we end up with four transactions total, one of which is a select to populate the table variable and one which just gets the total number of rows. The performance benefits can be substantial: In my particular procedure, for 500 source rows, the time to execute the procedure went from 25 seconds to 6 seconds.

Of course, you could have done the same thing using a temporary table, though it appears that table variables are slightly more efficient in memory. But the basic principle is the same: an application-level counter column is no reason to insert one row at a time.

The same principle, with a twist, can be applied to update cursors as well; more on that in a while.

Tsar: Band – Girls – Money

tsar band photo courtesy tvt

Sometime in the mid 1990s a lot of bands stopped feeling good. Blame the rap-metal bands, blame Radiohead, but good old fashioned rock party music largely disappeared from the airwaves. If there is any justice in the world (a dubious proposition at best), the new record from Tsar should bring back the heyday of window-open singalong guitar party rock in a way it hasn’t been heard since that album that the guys from Guns ’n’ Roses never recorded with the kids from Green Day.

Tsar are very good at a very old rock and roll tradition: exploring someone else’s sound and making it your own. The band has been kicking around LA since 2000 (and has been a darling of the blogosphere for at least that long, thanks to Tony Pierce’s tireless hype), and releases its first album for TVT this month. So the big question is: does the band live up to the hype?

Do they ever. Band Girls Money is a straight-ahead high octane dose of jet fuelled ear candy. Tsar claim to be descended from glam idols T. Rex and sugar poppers the Archies (and they work the glamdrogynous look in the cover art), but there are equal parts John Lennon and Cracker-era David Lowery in Jeff Whalen’s insanely fluid vocals, and the guitars simultaneously recall the high points of pre-Thin White Duke Bowie, the Ramones, and the Jesus & Mary Chain.

Incidentally, if this reads like a critics’ game of “List the Influences,” that’s because every track invokes a different set of very specific rock references. “Superdeformed” is the most explicit, checking the Beatles in both the chorus (though this writer would dispute the claim that “the Beatles never got you high”) and in Whalen’s Lennonesque “all riiiight,” which sounds like an alternate take of the chorus for “Revolution.” But other tracks hit different reference points: “Straight” plays like the Ramones doing a “One Tree Hill” soundtrack song (in a good way), “Wanna Get Dead” has the aforementioned JnMC vibe (specifically, “Coast to Coast” from Automatic), and the rhythm section intro leading into the sustained guitar note that opens “The Love Explosion” plays for all the world like a sped-up version of the opening to Radiohead’s “There There.” But the songs are all clearly original—the reference points are there as hommages, not as imitations, and for the most part if you blink you miss them. You know, aside from the part where Tsar are reinventing the whole glam genre.

Then there’s Whalen’s lyrics… They aren’t deep, mostly cocky cock-rock (“He’s got the band, the girls, and the money”, “It’s hard to stand up with all the girls on your lap”), but they would probably be a lot of fun to sing along with if the band included a lyrics sheet.

Which is one of my only two complaints about this disc. The other, the DRM on it that prevented it from going on my iPod so I could take it with me everywhere, is a little less forgivable. But the rock is so good, I’m almost over that. And if you know me, you know that’s saying a lot.

If Spoon’s Gimme Fiction is this summer’s party album choice for the intelligent indie pop fan, Tsar’s Band Girls Money is this summer’s party album choice for everybody else—and for the intelligent indie pop fan when he thinks no one else is looking. This band is some serious rock’n’roll fun.

Originally posted on Blogcritics.

Exploding manholes = change of plans

Boston.com: Cambridge streets close after reports of exploding manholes. No one was hurt after a piece of N-Star equipment underground failed, causing manhole explosions in Central Square. More to the point, it also caused massive power failures, crippling the Red Line and bringing traffic to a standstill in much of Cambridge.

You know, tonight was going to be the night I went to Harvard Square for the Monday night trivia contest at John Harvard’s. I guess God doesn’t want me to go; the last time I had an opportunity to go, it was two days after my hand injury.

Can’t stand the heat

It was a great weekend, but hot. As in, I’m surprised I didn’t melt right off the stage Saturday night in my new tux. Lisa has business in New York this week and went yesterday with her parents back to NJ, taking the dogs with her. Definitely the right move. They would be having some trouble at this point, it’s so hot.

Yesterday I escaped the heat for a while by going to the movies, where I caught the Hitchhiker’s Guide at the Arlington Capitol Theatre (verdict: about a 3 out of 5. Marvin wasn’t as effectively used as he could have been, but there was a fair amount of magic in the rest of the story), then came home and napped in the air conditioning of the bedroom for a few hours. But the portable AC unit was having a hard time keeping up with the heat too.

Last night I dreamt that our new AC system had been completely installed and that we didn’t have to patch any of the walls afterwards. Oh well. Back to reality.

Stars and Stripes Forever (and two more shows for me)

Having sung my first Boston Pops concert last night, I can honestly say that this is the greatest city in the world. How many places do patrons come armed with little American flags to wave when the orchestra will play “Stars and Stripes Forever” as an encore? And how many audiences roar with approval when the chorus stands up to sing the final verse of “Stars and Stripes Forever” (which I really appreciated, by the way).

Incidentally, I now know the actual lyrics to “Stars and Stripes Forever”—and, contrary to popular belief, they don’t start “Be kind to your fine feathered friends/for a duck may be somebody’s mother.” Below are the lyrics that the Tanglewood Festival Chorus sings when the Pops plays the march; print them out and bring them to Tuesday or Wednesday’s show and sing along:

Hurrah for the flag of the free.
May it wave as our standard forever
The gem of the land and the sea,
The banner of the right.
Let despots remember the day
When our fathers with might endeavor
Proclaimed as they marched to the fray,
That by their might and by their right
It waves forever.

The cure for Boston workaholism

In Christopher Baldwin’s moodily brilliant Bruno, there’s a great moment early in the strip’s run where a Minneapolis (or St. Paul) punk says to Bruno: “…but I’m not an emotionally constipated self-degrading punk on a reckless streak. Are all New Englanders so uptight?”

Her reply: “Lemmings march into a drowning watery grave, elephants go to the secret sacred burial grounds; depressed, introverted, workaholic intellectuals migrate to New England. Go figure.”

Which, as Laurie Anderson says, explains quite a few things.

Of course, one of the compensating factors about being in Boston with all the other introverted, workaholic intellectuals is the Boston Symphony Orchestra and the Boston Pops. So I thought I’d mention that my debut with the Pops (as a member of the Tanglewood Festival Chorus) is tomorrow. The theme is “Red, White, and Blue,” and the music includes some really nice pieces by American composers as well as about the American experience. There are no tickets available online for tomorrow’s performance—you’ll have to go to the box office—but tickets may be purchased online for the Tuesday and Wednesday shows. Hope to see you there.

MSN Toolbar Tabs – first reactions

screen shot of tab widgets from MSN toolbar

There are other tabbed browsing add-ons for IE, but when I saw that the MSN toolbar had added a tabbed browsing enhancement, I decided to check it out. After all, I still know people at MSN I can yell at if there’s something wrong. And, actually, yeah, there’s a few things I would change.

First things: I can’t stress how glad I am to have tabs rather than the damned taskbar group (multiple browsers collapsed into one toolbar button with a number on it). There’s no good way to do blogging and newsreading with toolbar groups. Tabs are a hell of a lot more usable. I also appreciate that the toolbar supports the standard CTRL-T keyboard shortcut for creating a new tab.

But there are quite a few missing features from the MSN implementation. For one thing, there’s no option to make new links open automatically as a tab in an existing browser window. So if you click a link from email or another application, it still spawns a new browser window. And links defined to open in new windows still do; there’s no way to override that behavior to make the new window open in a tab instead, as there is with Firefox or with Safari. Also, there is no “open in new tab” on the right-click context menu, which renders the tab feature a lot less useful.

Verdict: on a scale of 1 to 5, a 2. The new tab support is better than having no tabs at all, but to call it half baked is too generous. It feels like the team focused on tabs as a feature, rather than looking at the customer problem, which is window clutter and impaired productivity, and thinking about what is required to address that in a tabbed browser implementation. Microsoft is traditionally good at thinking through user scenarios; I look forward to the next version.

Knowing it’s worth it

The HouseInProgress folks are taunting me (probably not on purpose) with their latest post about air conditioning. Our weather looks like that too (well, not that bad—it’ll at least be staying in the 80s), only our AC installation doesn’t start until the 20th. Looks like the Old Man and the Street is in the same boat; their installation happens next week. At least we know we’ll be happy and cool when we’re done.

Apple on Intel: what it means for customers

I’ve had some time to reflect on yesterday’s Apple-Intel announcement and the subsequent commentary, including the surfacing of my offhand comment about delaying a Mac mini purchase on a BusinessWeek blog (thanks to Dave’s quoting it, I suspect). My conclusion is that, from a customer perspective, I shouldn’t be worried about the move—should in fact be celebrating, cautiously. Why?

First, Apple wouldn’t be making this move unless it knew it could deliver serious price/performance benefits to its customers. After all, as Intel’s CEO was kind enough to point out on stage yesterday, they are having to eat a fair amount of crow over this deal. So the new machines are going to be freakin’ awesome.

Second, as Dave and others point out, the choice of processor inside is a non-issue to many customers, as long as their apps still run—and quickly. Along those lines, my potential Mac mini purchase, which I wanted to get for a home music server, is an excellent example of a machine that would deliver the same benefit to me today with a PowerPC chip and a year from today with a Pentium chip.

Third, if Apple has any brains at all they’ll avoid an Osborne effect by doing a good job of telling a forward migration story … and discounting existing PowerPC based models. On the former point, I was impressed by both the purported ease of porting and the promised emulation layer (mostly—see below for some caveats); Apple needs to keep the momentum going by publicly tracking apps that are proven forward compatible and by working with developers to ease migration paths for customers of apps that have problems.

The potential caveats I mentioned? First, there is a risk that some existing apps won’t move forward. Daring Fireball points out one potential source of problems, found on a page in the Universal Binary Programming Guidelines: AltiVec code, code that inserts preference panes in System Preferences (my God, what is it about System Preferences?), kernel extensions (didn’t Apple just announce that API?), applications that explicitly depend on a G4 or G5 processor being present; and Classic (this just in: Classic is still dead, finally).

Another potential source of problems is the whole “endian” issue, which affects files containing binary data, and which Microsoft Mac BU’s Rich Schaut explains much better than I can do here.

As a user, I still think that I’m right to be enthused, and Dave is right—the upper layers of the OS is where most of the excitement is. But not all. And I think we’re all still permitted a moment of silent mourning for the demise of some great technologies: Classic, AltiVec, and Open Firmware (thanks to Steve Kirks for the last pointer).

Okay, enough mourning. Time to start watching for Mac mini prices to dive.

Manila 9.5 hits the streets

Congrats to the UserLand crew on shipping Manila 9.5. This release adds a ton of industrial strength features to UserLand’s industrial strength web app, including email validation of new members, version control, and multi-level access control. There are also some killer blog features, including (finally) support for adding enclosures to RSS feeds (aka podcasting), support for the MetaWeblogAPI’s newMediaObject method (meaning that posting an image from MarsEdit to a Manila blog should now become possible) and some good spam management features for both trackback and comments.

Congrats to the team. I look forward to trying out some of the features, once my web host makes the new version available. (Pointer via Scripting News.)

It’s true: Mac OS X on Intel

I found Paul Boutin’s liveblog on Engadget from the WWDC just in time to read these words:

10:28am PDT – “It’s time for a third transition. And yes, (puts up slide that says): It’s true.” Next slide is one word: “Why?”

10:29am PDT – “I stood up two years ago and promised this (3.0G PowerMac), and we haven’t been able to deliver.” Steve says it’s bigger than that, though. No roadmap for the future based on PowerPC – they can’t see a future.

10:30am PDT – Intel offers not just increased performance, but reduced power consumption. Transition will be complete by WWDC ’07.

10:31am PDT – PowerPC – 15 integer perf units (not sure what) per watt. Intel does 70 per watt. “Mac OS X has been living a secret double life” for the past 5 years.

10:32am PDT – Satellite shot with crosshairs shows building where a team has been working on the “Just in Case…” scenario. Every release of Mac OS X has been compiled for Intel for the past 5 years. Here comes the demo!

10:33am PDT – “As a matter of fact, this system I’ve been using here…” the keynote’s been running on a P4 3.6GHz all morning”

Pretty big news. Sets the conventional wisdom on its head.

Makes me want to put those plans for a Mac mini purchase on hold.

It’s good to see that even in this brave new world, some things, like the hilarity of Theo Gray from Wolfram Research, remain unchanged.

(Update: here is the official press release.)

(Almost) live WWDC updates

It appears that the WWDC keynote isn’t being streamed over Quicktime (at least, not that I’ve been able to find). However, MacRumors has set up a special auto-refreshing live site where they’ll be posting the latest keynote coverage (technical details of their AJAX based approach here). There’s also an IRC channel if you can’t wait for a schedule refresh, or if you like your news piping hot and mixed with lots and lots and lots of chatter.

Apple to switch to Sun chips

sun chips. get it? hah hah.

With all the discussion about what Greg called the Pentiac rumor—the rumor that Apple is imminently going to announce a switch from IBM to Intel chips, or a new product line based on Intel chips, or that it just had lunch with Intel, or something—I couldn’t resist pointing to a leak about the real announcement to come today. Thanks, Steven Frank, for the laugh (make sure to click the link for the full sized image). (And thanks to MacSlash for the link.)

Spies in space

I love this story about the discovery of spacesuits for spies (or, less sensationally, training suits from the Air Force’s short-lived MH-7 program) in a locked, forgotten room at Cape Canaveral. As a comment on Slashdot pointed out, it’s a great metaphor for the fate of much of our space engineering work from the 1960s.

A few other memories were dredged up by the Slashdot crowd, including the X-20 Dynosoar, a reusable space plane design conceived in 1957 and cancelled in 1963. I remember seeing models of some of the other proposed Air Force space craft in the visitors center at NASA Langley when I was a kid.

Manned espionage platforms speak of a vision of the future that failed to understand how quickly electronics technology would advance to provide communications and surveillance capabilities without costly human intervention. It’s a more Asimovian view of the future than the Philip K. Dick version we got instead.