Dennis Forbes on Pragmatic Software Development
Subscribe to RSS
 
Friday, December 09 2005

I've pursued various Microsoft certifications over the years, starting with the MCP, and then acquiring an MCSE and MCDBA.

My motivation in pursuing these certifications was that they served as a destination of sorts, motivating me to learn products and technologies to a breadth and depth that I wouldn't have otherwise.

The knowledge has proven very handy: Even when I serve in a development/design role (especially when I serve a development/design role) the information gained is critical in making appropriate decisions. When I serve leadership and advisory roles, again I'm glad that I spent the time going through every esoteric option and alternative, because the knowledge does help to head off misdirected initiatives and wasted effort.

For those who think "Oh, but I know all of it anyways. I am a Linux super-guru and thus I can achieve anything on the Windows platform with ease". I've heard this sort of boast before, and the results weren't pretty. Go to the Microsoft certification site and take some assessment exams - you might be shocked. The platform is absolutely huge, and it is remarkable how much of it doesn't gain our attention or focus, yet it can help us make better apps, and deploy better solutions.

"If you're a software developer and development manager, why did you get administrative type certifications?" some might ask. Very good question, and the answer is found in the paragraphs above - I dealt with the coding side all day every day, so I didn't see as much of an advantage focusing on an area that I know so well (basically it would have been hundreds of dollars for Microsoft to anoint what I'd proven amply in the field), while I (like most development focused people) didn't really pay enough heed to the platform side of things. Now that I am often called upon for platform consulting as well, it was a nice foundation to build upon.

Nonetheless, now that Microsoft has revamped their certifications, I've decided to upgrade to the MCTS: SQL Server 2005 along with the MCPD. I had hoped to get the MCTS out of the way, but it looks like the exam isn't available yet (despite a November 2005 timeline). Alas. Already it has encouraged me to focus on esoteria of SQL Server 2005 that would have gone ignored.

And for those who protest "But I don't have time! I'm a very busy person!": You could very well be running to stand still. It is an epic problem in this industry that tremendous effort is expended because people don't spend enough time on the skills side of things, focusing all of their attention on the application side.

Friday, December 09 2005

If you're thinking of providing a demo or limited-use version of your software, pay for the bandwidth and host it yourself. It is an enormous waste of time for potential customers - not to mention that it's incredibly insulting - when you host at one of the big "make you follow 7 links, then sit in a queue, and then download a potentially tampered executable at a reduced speed" 3rd party file hosts that seem to be all the rage these days.

Bandwidth is relatively cheap nowadays, coming in at less than 8 cents a GB at many providers.

What does this have to do with social proof? Well if you host your demo or lite version at one of the aforementioned file hosts, my immediate presumption is that a very tiny percentage of users actually pay for the software: What else could justify such an abuse of clients?

Given this obvious conclusion, the power of social proof pushes me to lean against purchasing it either.

Monday, December 12 2005

Enjoyable weekend, packed with Christmas parties and other holiday related events. What a wonderful time of year.

I don't normally do this, but since this is hidden in the personal category, what the heck: Surely everyone has seen this by now (I believe it's over 2 years old now). Amazing amount of planning and work (not to mention cost) went into that. They went big, and superbly kept some big-bang in reserve until the end. Amazing.

This is quite a humorous video.

On the more disturbing side are these and these. Apparently this has been going on for a while: An extremely talented motorcyclist ("GhostRider". Apparently the name is based on a comic) drives through congested urban streets and highways at absolutely insane speeds, darting between unpredictable traffic, capturing it all with several bike mounted cameras (along with coordinated "crew"). Most of these take place in Sweden, and apparently this is something of a trend there. [One individual insightfully commented that this was all inspired by an infamous scene from the French movie The Rendezvous, in which a hired, and apparently still mysterious, driver goes insanely quickly through the streets of Paris one morning, endangering pedestrians, other traffic, and himself as he disregards traffic lights and controls. See for yourself].

While I don't want to support that sort of activity (go crazy on the track, just don't put innocent people in harm's way for your fun - I'd love to have the real DVDs of these, but I'm not going to financially support it as a pursuit), I am in awe of the talent, and I am absolutely disturbed by the complete fearlessness: In a number of situations a driver making a last minute lane change would have resulted in certain death.

Actually that points out one of "GhostRider's" key talents, which is reading traffic (very, very rapidly). It is remarkable how many people have no ability to do this at even a much more liesurely pace. You know - those people who always seem to be speeding, yet they keep passing you over and over and over again (because they keep screwing themselves into dumb positions, particularly when they try passing on the right on 6 lane highways).

I think these fascinate me for the same reason that I enjoy F1 - extreme engineering (the devices featured are extraordinary pieces of engineering and perfection), risk, and extraordinary skill. These aren't a bunch of kids in Honda Civics with loud exhausts - they're obviously professional drivers and bikers to some degree, and the confidence and skill is extraordinary.

  Personal 
Tuesday, December 13 2005

A lot of my work - both system consulting and software architecture/development - relies upon Microsoft technologies: Whether it's re-engineering a legacy system to take advantage of new SQL Server features for performance or functionality, overhauling a network infrastructure to leverage ActiveDirectory and the extensive platform security functionality, or developing a performant and scalable time-tracking application for an enterprise client, Microsoft is often a very important part of the equation.

Dundas Street - Burlington

Partly due to specialization (it's the tools we target), coupled with simply being the best choice in a lot of scenarios in our target market, we heavily rely on the Microsoft platform for ourselves and our customers. As a professional I can say with confidence that the platform is a secure, high performance, extremely scalable, robust one that compares very favourably against all competitors.

That wasn't always an accurate statement, though. Indeed, it is remarkable looking at the history of Microsoft and learning from their success: On paper it really is hard to believe that Microsoft maintained the market dominance that they did, and it's amazing that competitors couldn't capitalize on Microsoft's late entrance into a lot of markets, and their missteps in others.

Was Microsoft a master of timing, holding off on technologies and advances until the perfect time, or were they simply the beneficiary of a captive audience that was willing to wait however long Microsoft took, blind to the available alternatives?

I'll provide a couple of examples that I recall marvelling at as they occurred- these are hardly exhaustive, however I think it's a nice sampling.

Microsoft Maladies

  • Microsoft core offerings were crippled by real/virtual mode limits until long after the 386 and 486 were prevalent. In a nutshell, this made software development a lot less pleasant, and the resulting applications more limited and unstable - I remember being enormously unhappy learning real-mode assembly on the x86 after dealing with the elegant, 32-bit flat world of Motorola 68000 assembly. It seemed so primitive that it still existed, or that a software company continued to rely upon it long after it was obsolete and irrelevant in hardware.
  • Microsoft's "operating system" for years was simply the DOS command line, and a set of utilities and software interrupt handlers. While Mac users were busy with a rich graphical user interface, we in the DOS world were anxiously awaiting fantastic new features like DELTREE, and maybe a new version of EMM386 to deal with real mode nonsense. It amazes me now to recall actually going to a store and paying real money for a stack of 3 1/2" DOS 5 upgrade disks...6 years after I was programming applications on a richer 4MB platform, here I was excited that himem.sys could free up some of the critical 640KB of low memory.
  • Microsoft toyed with windowing systems, finally creating something credible and successful in 1990 (Windows 3.0). In contrast a variety of competitors had fully-integrated, rich, usable, robust Windowing systems many years before - The 1984 Apple Mac being an obvious example, along with the 1985 Atari ST and Amiga...even options on the Commodore 64. I was an Atari ST fanatic in those days, and I marvelled at how primitive the PC world remained even years later.
  • It wasn't until Windows 95/NT that memory protection was utilized to avoid processes stomping on each other's memory. Again, many, many years after most competitors had implemented this basic functionality. Instead we dealt with the normal occurence of misbehaving apps taking down the entire system as a fact of life.
  • It wasn't until Windows 95/NT that preemptive multitasking was available in Windows. Prior to this a single misbehaving application could capture the CPU's attention and never let it go (never yielding), which was a fairly typical event. The Amiga featured pre-emptive multitasking a decade earlier.
  • Microsoft released Windows 95 without a web browser, remarkably enough, finally releasing a barely changed version of the NCSA's Mosaic in the Plus! pack.
  • Microsoft 95 was pretty much a security nightmare. Not only was its software far-from-ready to be connected on the public internet - I remember being the unhappy victims of winnuke and friends when I made people unhappy on IRC (you can't please all of the people all of the time), it also had no real file/object security of consequence. While NT was built as a "multi-user" system from a security and kernel perspective, many of the shell and utilities were user unaware, undermining this capability.
  • Microsoft's web technologies were far behind the times until Bill Gates' famous speech that changed their direction, reacting to Netscape's lead rather than charting the course. Internet Explorer quickly ramped up and became the dominant web platform - until it became so powerful that the team was disbanded.
  • Alternative 3D rendering APIs (Glide and OpenGL) led the way in an area where eventually DirectX would emerge dominant.

I recall during my early courtship with the PC simply marvelling at how incredibly obsolete the platform seemed to be compared to competitors like the Amiga and the Mac introduced years earlier - from graphics capabilities to software to hardware: Everything about it seemed so backwards in comparison to the superior alternatives, yet customers stuck with it. This was the platform that Microsoft wed themselves to, so surely they would suffer as well, right?

Microsoft's insistence on legacy compatibility led to a platform that moved much slower than competitors - Competitors that had the liberty of just tossing it all out and starting from scratch with whatever whizz-bang feature the newest chips offered. Maybe they could run super-stable and super-fast, and offer the developers an elegant platform upon which to perform their magic...but could it run Commander Keen 1 through 3? Could it run that ancient text database app?

Not All Negatives

Of course it's easy to focus on the deficiencies and imagine that they wrote the whole story, but in reality the situation was much more complex. Windows, for instance, pioneered widely-used video card acceleration (I still remember that shiny new Diamond Speedstar 24x. 24-bit graphics, coupled with hardware acceleration of 3D primitives. It was good times running those benchmarks. Of course the Amiga fanatics will point out that it supported hardware acceleration, just as the STe featured a hardware blitter chip, but the interaction between acceleration and the GDI in Windows really set the bar), and Microsoft's push greatly accelerated the adoption of optical media. Windows For Workgroups brought inexpensive networking to a lot of shops (NetBEUI was imperfect, but it was an easy transition to TCP/IP), and Windows in general represented a "good enough" platform for a lot of users. Internet Explorer, for all of its ActiveX "holes" and CSS quirks introduced the rich web model that we rely upon today.

En Route to 64-bit x86

This all comes to mind as the x86-64 transition accelerates: More and more users are starting to switch to 64-bit capable systems, and the 2/4GB limits of our machines is actually becoming a rational limit among desktop users: Everyday users are shouldered against a limit that seemed almost theoretically large just a few short years ago.

Of course Microsoft has been releasing incomplete 64-bit options for years (for instance you could get a 64-bit version of SQL Server 2000 for the Itanium platform, barring a laundry list of exclusions and limitations, and way back with NT 3.1 Microsoft supported 64-bit processors, albeit in 32-bit mode). Now that 64-bit support is finally becoming a critical factor, Microsoft has a wide gauntlet of support ready, and is finally ready to deliver.

Once again when the market really cares, Microsoft is ready. For years some have been talking about the advantage of various operating systems, such as Linux, being availabile on cutting edge processors and 64-bit platforms. For years that has been paraded as an advantage to customers who continued to run their platform on a standard old x86-32 foundation. Yet now that those limits are being reached, and the platform needs to accommodate new levels of capability and performance, Microsoft is ready. Another deficiency overcome.

The Question

Looking at the platform now - the stability, security, and feature set of Windows 2003, a lot of it already existing in XP - it really does seem like a tremendous window of opportunity for the competition has passed: What used to be a crop full of delectable low hanging fruit is now a well protected enclave featuring armed guards.

If competitors couldn't make inroads before, how do they have a chance now? If Linux couldn't capture the desktop market against a monstrosity like Windows Me!, what chance does it really have against XP?

The most obvious answer is web applications - render the operating system irrelevant and you don't really have to compete.

Tagged: [], [], []

Tuesday, December 13 2005

VCRs and PVRs - Small Usability Improvements Yields Huge Usage Changes

How often did you use the scheduling functionality of your VCR to record your favourite television shows, decoupling yourself from the rigorous schedule imposed by the television networks?

The common answer, overwhelmingly, is never. Few bothered using the scheduling functionality, even when it would be beneficial to their quality of life.

This inspired endless jokes about the complexity of "programming the VCR". Even the few brave "wizards" who did bother scheduling recordings generally did so rarely: The hassle of managing tapes, manually setting schedule times, and then having the uncertain-quality result unavailable until completion simply wasn't worthwhile to most people. Many times it didn't work out, and they discovered that they actually recorded 8am instead of 8pm. Whoops!

Even the introduction of Guide+ - a system that allowed you to record a program by punching in a short code - changed the situation little: To many it still wasn't worth the marginal hassle.

The functionality to time shift was there, but few leveraged it.

This topic came up after becoming engaged in an interesting discussion about PVRs versus VCRs, and why the former is inspiring panic and behaviour changes among the television networks, while the latter was largely ignored. Consider that virtually every household in the West had one or more VCRs, yet only a very small percentage have a PVR today (though obviously it's a much greater percentage among the net savvy). Why the concern about functionality we've had for well over a decade?

DSC02727

The reason for the panic, of course, is that the seemingly minor usability and functional improvements of the PVR dramatically increased the usage and utility of the technology: Instead of rummaging for Guide+ numbers in the back of the newspaper, or worse - configuring start and end times manually - one simply pulls up an online listing, selects the programs they want, and selects to record them. The quality is superlative, it takes just a few moments, and they gain the added ability to quickly skip past commercials. Many choose to automatically record every new episode, saving even more time. To put the icing on the cake, there's no hassle dealing with the tapes.

simply reducing the complexity or number of steps marginally can lead to market dominance

There is a valuable lesson to be learned from this: Seemingly minor advances in usability can tremendously alter marketplace success (the VCR was, of course, a great success in marketplace saturation, but that was almost entirely on the merit of playback of pre-recorded content. Few used it to actually record content). Even when it seems like a marketplace need has been functionally satisfied, simply reducing the complexity or number of steps marginally - or reducing the barriers to entry - can lead to market dominance (or market creation). A PVR isn't just a VCR with a hard drive - It completely changed the equation.

Software For Every Need

Consider the software market: By all appearances it looks to be a saturated market - with a solution for every need - but the remarkable thing is that much of it remains completely unused and unadopted. There are countless domains where solutions sit collecting binary dust because the complexity or barrier to entry is too high.

Skype, in contrast, blazed a path of glory and achieved virtual overnight success, yet really it's just yet-another IP voice technology (like we've had since the mid-90s. Sure it added the distributed net, but that's a feature that is a marginal improvement at best). It offered a clear, usable interface, firewall avoidance, and a simple directory for finding the other person, and bam it is getting bought out for $2.6 billion - for doing what had been done by countless competitors in a seemingly commodity market for years before.

FogCreek software has had success simply taking some open source software and putting a pretty face on it, offering a small value-add (avoiding configuring your firewalls) - Making money charging money in a market that people thought was saturated with free alternatives. The web could really be considered a Gopher 2.0, but improved usability enough to be embraced by the everydayman. Bam, the webolution. HTML is absurdly trivial, yet the marginal usability advance of blogs are what made everyone a writer. CSS and JavaScript are both highly accessible technologies, and you can get started quickly by viewing the source of sites you like, again vastly accelerating the transition from initial exposure to actually doing something with it.

What About the Professionals?

Even when targetting highly-trained professionals, immediate "usability" remains critical. Remarkably many of the successful back-end technologies are those that were easy to get started with.

Extraordinary to think that multi-year projects and massive web applications of tremendous scale were built on chosen technologies because they offered a painless, 10-minute getting started setup and tutorial - letting someone start pushing out code immediately - yet in talks with peers I've found that this is frequently the case. Indeed, I will admit to this irrational behaviour myself - several times I considered implementing a project in J2ME (targeting cell phones), but the hassle of setting up a J2ME development platform, and then the pertinent modules for the various phones, served as such a discouragement that I abandoned the project rather than wasting 4 hours dealing with that. In the longer term of a project it's completely irrational, yet it happens.

Of course much of the ASP development community evolved not because ASP was the best platform that was being chosen on merit, but rather because a lot of shops had a Windows NT box sitting there with IIS on it, and they started dropping ASP scripts on it (other languages, like PHP, required additional installations = more trouble). Soon enough these were ASP shops, even though it was almost accidental. Few of them really seriously evaluated the various alternatives.

Of course this was by design: Microsoft, who I spoke about earlier, understands this resistance to learning well. They have entered countless markets with seemingly inferior offerings (at least at first), but because it's there (Microsoft used to rely upon "everything on" by default) and it's easy to use, the marketplace adopts it. SQL Server is a fantastic database system (I personally believe it was one of the best, and is now the best with SQL Server 2005), but a lot of its growth came about largely because it was a trivial install with a simple, ultra-low barrier to entry GUI: Joe Developer installs it from the MSDN discs, prods it for a while, and soon enough he's building the enterprise data system on it. All because it was so accessible and easy to use [Of course many of those database don't use transactions (or they don't properly), and they host terrible schemas, but it got it used]. On the Windows platform a lot of admins did the "install everything" technique, and slowly they sorted it all out and utilized it. This was the way that Microsoft entrenched itself into corporate networks.

Contrast this with other areas where Microsoft hasn't followed this philosophy, and where the results have been much less positive - Even for critical back-end technologies like Biztalk and Sharepoint (both of which yafla provides solutions and consulting for), where you would think it would be soberly analyzed by experts over months of analysis before deployment (and thus requiring significant upfront configuration should be a non-issue), they often see little adoption simply because the install or initial configuration discourages fly-by investigation. Without the initial investigation there is no one to champion it, so it goes unused (despite being fantastic products).

There are countless examples of products whithering because the first install required 40 steps, and then doing the first "hello world" type of project was an enormous hassle. On the flip side a lot of questionable technologies and solutions have permeated largely because it was usable immediately, with little up-front investment.

Minimize Barriers to Entry - Make Your Software Initially Easy

If you make software products, ensure that Getting Started is as painless as possible, and advanced customization options are saved until the user has some experience with the product (literally it should install and configure everything, and start the user off with a Hello World template solution): Even if your customers will need to spend hundreds of man hours specializing it for their needs, they need to see something they can poke at and interact with almost immediately, giving them a sense of accomplishment to motivate them to continue on. 

Once you've gotten the initial time investment, it's much, much easier to require a more involved understanding, and to demand that the user commit themselves to some educational time by the fireplace with the documentation.

We're a very impatient bunch these days, and this is critical if you want success.

If, on the other hand, you're looking at potential markets for software products, examine the usage patterns of PVRs versus VCRs - While the software world might seem full of existing solutions, really the field is wide open for usable solutions. Make an easier to use mousetrap and much of the world will beat a path to your door.

Tagged: [], [], [], []

Thursday, December 15 2005

Push Comes To Shove

In many ways the rampant podcasting enthusiasm reminds me of the big "push" furor back in the mid-90s, with everyone racing to incorporate the quickly abandoned channel technology (though it re-emerged as the influential and prolific, simplified RSS years later), all desperately trying to get a piece of the short-lived PointCast-style action.

The essence of podcasting - the most important benefit to many users - is really nothing more than the so-called Long Tail of audio files: Anyone can create an audio file (usually an MP3). From a listener perspective, no longer do you have to sit by the radio at a set time to listen to the talk show produced and distributed by the few elite with the money and the power to run a radio station. Instead, you can now subscribe to a wide array of content from around the world, created by both the aforementioned mega-media firms, but also by a guy in his basement talking into his microphone.

Technically podcasting is the inclusion of file references into the so-called "push" technology RSS, which usability-wise means that instead of endlessly searching around websites looking for audio files, manually downloading and then transferring files to your player, your podcast client software automatically detects when new audio files are available for the feeds you've subscribed to, it usually automatically downloads it (alternately it may provide you with a synopsis of each show, letting you manually select which ones you're interested in), and often even transfers it to your audio player (e.g. mp3 player, iPod) the next time you sync. The definition of podcasting has been expanded to include virtually any sort of media (or even non-media) attachment, expanding the scope to an unusably vague level, so I'm just going to focus on the audio aspect because that's the prevalent context.

As mentioned before regarding usability, small usability improvements can dramatically change the usage of a technology. In the case of podcasting, the theory is that while there have been audio programs available online for years, "push" enabling it would dramatically increase consumption.

Listener's Choice

Personally I don't think usability has ever been the limiting factor for audio files - It's more efficient for me to browse IT Conversations on occasion than it is for me to find a selection of good feeds to subscribe to, and then spend all of that bandwidth and memory space on a bunch of podcasts of uncertain quality and topic (even if I like a particular podcast feed in general, the likelihood that a particular episode is going to interest me is actually low). I don't even subscribe to IT Conversations' feeds - despite it having one of the best content records in the business - because the majority of the interviews aren't of interest to me: For every interview that intrigues me, many more are in a domain or with a personality that I can't allocate the time to focus upon.

I'm not going to eat the gruel just because it's what they happen to be serving today.

Is the content and distribution problem really the reason you don't have more talk radio in your life?

At a more fundamental level, though, podcasting is primarily a creation and distribution expansion of the previously mentioned talk radio. Is the content and distribution problem really the reason you don't have more talk radio in your life? Do you even know what talk radio programs exist in your area, available 24 hours a day from any tuner available?

Probably not.

Difficult to Stomach

Talk radio is something that most people aren't interested in. Talk is something that is difficult to consume without a good amount of your attention (I've found it close to useless - and destructively distracting - playing audio interviews in the background while working), it's difficult to efficiently vet (e.g. I can jump to a blog - or scan a newspaper - and know what interests me or not in seconds. A podcast requires some time to gauge its usefulness in your life), and it's often far less efficient than the alternatives. I can absorb someone's point from their writings enormously more efficiently than I can listening to them ramble on about this and that. It's generally difficult with audio files to jump to the pertinent parts that interest you (there are seldom even indexes or transcripts), so you have to take the chaff with the wheat. It's like that guy who leaves the long, rambling voicemail messages, in which are hidden a tiny nugget of useful info, instead of just sending a concise email.

If it's slow to parse, difficult to scan, and requires a fair degree of one's attention, the reasonable expectation nowadays is that it should have useful, informative video going along with it to increase the utility and value. The .NET Show is a pretty good video feed - with a great transcript that lets me jump where I want with ease to avoid the filler - though of course it's infrequent enough, and covering such a variety of topics, that any sort of automation is useless for it: I just visit the site every month or so and see if the latest outing interests me. While one month might be great, the next might be 90 minutes of someone pushing some questionable vapourware with a delivery promised in 2 years.

Of course sometimes rambling in audio interviews - the filler - is extremely valuable, and people betray information and convey knowledge that they would never have put into words - some of the conversations with industry veterans and superstars on IT Conversations are brilliant for this - but in general talk is not an efficient information medium in an information domain. Highly technical audio podcasts are truly absurd.

Everything Old Is New Again

Remember the excitement about webcams a few years back? Several sites made it easy to find people's webcams, so the presumption was that we would all start consuming. For a short while it was true, and people entertained themselves looking at downtown webcams, goofy people with webcams, and so on. Then the interest faded, and we realized that it really wasn't that interesting.

This has repeated in a variety of technology spheres, where a simple repackaging of content that otherwise had little interest earned short-term euphoria and early adopters, but quickly fizzled out as the buzz and the eliteness subsided.

The novelty quickly wore off, and the utility of the underlying content failed to maintain any level of continuing support.

Tagged: [], []

  Blogging 
Thursday, December 15 2005

I've come across this question quite a few times.

I have rows with lots of columns, and would like to split it out so that each column is a row

Imagine a scenario where you have a wide table that you'd like to normalize, at least in view or faรงade (or perhaps in a data transformation layer) - You'd like to un-pivot it, rotating columns into rows.

For a sample, I'll use the questioner's scenario of a Person table with a variety of attributes. Don't get hung-up on the table or whether it's already normalized (the sample came directly from a user who had a rather unique need), the point is simply rotating columns into rows.

Table: Person
ID FirstName LastName Age
1 Bob Jones 32
2 Jeremy Jones 2
3 Laura Croft 26
4 John Dingbat 22

You'd like to return a set like the following:

ID Property Value
1 FirstName Bob
1 LastName Jones
1 Age 32
2 FirstName Jeremy
2 LastName Jones
2 Age 2

(rows truncated for some brevity)

SQL Server 2005 offers the UNPIVOT operator of the FROM clause, which can made quick (albeit unintuitively and inflexibly) work of this specific need.

SELECT   
ID, tblPivot.Property, tblPivot.Value
FROM
(SELECT ID,
CONVERT(sql_variant,FirstName) AS FirstName,
CONVERT(sql_variant,LastName) AS LastName,
CONVERT(sql_variant,Age) AS Age
FROM Person) Person
UNPIVOT (Value For Property In (FirstName, LastName, Age)) as tblPivot

The use of the derived table in the FROM clause is purely to cast the columns to a common data type, as this is a requirement of the UNPIVOT operator. Otherwise all of the source columns would need to have the same type (precisely the same type).

Note that the IN list has to be a literal, concrete list - you can't pass a table variable or subquery. Always perplexing when they limit these sorts of operators in this way.

With SQL Server 2000 you can do this via simple unions or temporary tables

SELECT 
ID, 'FirstName' AS [Property], CONVERT(sql_variant, FirstName) AS [Value]
FROM
Person
WHERE
FirstName IS NOT NULL

UNION ALL

SELECT
ID, 'LastName', CONVERT(sql_variant, LastName)
FROM
Person
WHERE
LastName IS NOT NULL

UNION ALL
SELECT
ID, 'Age', CONVERT(sql_variant, Age)
FROM
Person
WHERE
Age IS NOT NULL

In this case we've made the common type sql_variant, though obviously you should alter according to your data. We've also decided to eliminate null values (so there aren't null property rows), though that depends upon the need.

Another option is to make a programmatically flexible alternative that automatically adapts to the schema of the table (within constraints). For instance consider the following script.

SET NOCOUNT ON
DECLARE @table sysname 
SET @table = 'Person'
DECLARE @id_field sysname 
SET @id_field = 'ID'
DECLARE @sql varchar(8000)
-- create the schema of the resulting table 
SET @sql = 'SELECT TOP 0 CONVERT(int,0) AS [ID], '
+'CAST(0 AS nvarchar(4000)) AS [Property],'
+' CONVERT(sql_variant,N'''') AS [Value] WHERE 1=0 '+CHAR(10)
SELECT @sql = @sql + 'UNION ALL SELECT '+@id_field+', N'''
+COLUMN_NAME+''',CONVERT(sql_variant, '
+'['+COLUMN_NAME+']) FROM ['+@table+'] WHERE ['+COLUMN_NAME+'] IS NOT NULL '
+CHAR(10)
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @table
AND COLUMN_NAME <> @id_field
ORDER BY COLUMN_NAME
IF (LEN(@sql) >0) 
BEGIN
EXEC(@sql)
END

In this case it uses the object schema, though you could alter it to go against a property table or the like.

Standard disclaimers about injection attacks and all of that apply (presumably you won't be calling this with untrusted input), and of course it won't work if you have composite keys, or if you have so many columns that the resulting SQL exceeds 8000 characters. Adapt accordingly. It also does no sorting, so add as you need it.

Tagged: [], []

  SQL 

Earlier EntriesLater Entries

Dennis Forbes - Dennis Forbes is a Toronto-based software architect and technology writer