SQL Server 2005 Object Naming Standards - Part VI: Triggers

I was working on the new application database recently, and it came time to create some triggers to keep date/time and a few other fields up to date. Therefore, it seems like a good time to talk about trigger naming standards. They’re simple, because I’m convinced trigger use should be limited (see Trigger-holic, below). At most, I would expect to find three triggers on a given table; one each for the three triggering events, insert, update and delete. Also, the impact of the trigger should be fairly limited — at the very most — to the table with which the trigger is associated.

With that admonition, the standard trigger name consists of three parts; the name of the table with which the trigger is associated, followed by the event(s) that fire the trigger, followed by the letters Trg. For example, the trigger on the table Dog executed every time a record in inserted or updated, would be called DogInsertUpdateTrg. If the table was called Breed, and the trigger was fired on delete, then the trigger name would be BreedDeleteTrg. As with other naming standards, the three parts of the trigger name as distinguished through the use of camel case. As usual, you’ll see that I have traded a succinct name for one that is a little more verbose, but easy to understand.

Also, keep in mind triggers are associated with schema names, and it is suggested that the trigger schema and the table with which it is associated be the same. For example, if the schema was VetOMatic, then you would want the trigger(s) on this table to be associated with the same schema. The examples above, triggers would be fully specified as VetOMatic.DogInsertUpdateTrg and VetOMatic.BreedDeleteTrg. Don’t get me wrong — VetOMatic is a terrible schema name, but it works for illustrative purposes. More on SQL Server 2005 schemas in a future post.

I’m a Recovering Trigger-holic A long while back, when I first introduced to SQL Server 2005 triggers, I went kind of ‘trigger-crazy’, figuring they were the cure that virtually everything that ailed me. I even went so far as to have triggers create and delete records in related tables to ensure referential integrity was being maintained. It turned out to be a very bad idea. When I eventually handed over the database to someone else to maintain, they were totally flummoxed by records appearing out of, and/or disappearing into nowhere. What I learned from this experience is logic implemented by triggers is not self-evident. More specifically, they don’t show up on the database diagram on SQL Server Management Studio. That’s my primary method of communicating database structure, and the diagrams do nothing to communicate the trigger logic. So these days, I’m limiting trigger use to maintaining date and time stamps, and also, by linking changes to database content to a session record.

OK, that last part was really not much to do with the naming of triggers, but useful information anyway, hopefully. As always, thank you very much for reading, and by all means, let me know what you think.

The Trouble with Using Functions as Column Default Values

Column defaults are a handy way of ensuring a given column is populated with a specific value unless another value is supplied as part of the insert or update logic. A popular choice, for example, is to use GETDATE() or GETUTCDATE() to populate a mandatory DATETIME column. This is fine, unless you need more sophisticated logic for the default. For example, I have a function that retrieves a unique identifier for a session, based on the indigenous SQL Server 2005 SYSTEM_USER function. In other words, the default will vary depending on who you are.

For discussion purposes, let’s call this function getSessionCurrent(). This worked just great until I tried to change the definition of the function slightly. SQL Server 2005 has a genuine, pathological hatred for changing functions that are referenced in column defaults. Well, actually, I don’t know about the pathological hatred part, but it doesn’t let you change the function without dropping all references to it, first. The only work around of which I’m aware is removing all references to the function in the column defaults, change the function, and then add all the references back again. What a hassle, and hence a reason not to use functions for default values. But wait…

A better way to do it is to make a stub function the default, and then have that function call another function to actually do the work required. In the case of the above, I broke the function into two components; getSessionUser(), which is what I used as the default in the column definition. Basically, it has one line which in turn hands the call off to another function called getSession(). The latter is where the actual retrieval of the session information is done. When it concludes, it hands back the value to getSessionUser(), which in turns uses it as the default. You can mess with getSessionUser() to your heart’s content now, without changing the reference to the function in the table.

Not a big deal, but something to make your life a little easier. I will provide more information on the specifics of these two functions in a future post. For the time being, thank you very much for reading, and by all means, let me know what you think.

SQL Server 2005 Object Naming Standards - Part V: Keys and Indexes

Recently, I was reviewing and rationalizing a group of keys and indices for a revamped database design, so I thought it was a good time to talk about applicable naming standards for these types of objects.

The default names SQL Server 2005 comes up with aren’t all that bad, actually.  For example, the primary key for the table Dog will be, unless you specify otherwise, PK_Dog.  If you create a foreign key on this table to a table called Breed, it will be called FK_Dog_Breed.  In addition to these basic keys, let’s assume you create a unique index on Dog.nm; that index will be called IX_Dog.  So far, so good, particularly given most tables will have some combination of these three objects, and nothing else.  You could therefore do much worse than just leave well enough alone and go with the SQL Server 2005 default index names.

Things get somewhat uglier, however, in the situation where multiple additional keys or indices of a given type associated with a given table.  For example, assume in addition to the above, you decide to add a unique index on Dog.lbl  — this index will end up being called IX_Dog1.  I’m not a big fan of the tacked-on number suffix to differentiate one object name from another.  It makes the name unique, of course, but does absolutely nothing to convey any sort of meaning as to what role the object plays.  As noted in previous posts, system documentation often doesn’t get written — much less read — so the more self-evident meaning you can pack into a succinct object name, the better.

Key/Index Base Names  Very similar to the approach taken with other SQL Server 2005 database objects, key/index object names are rooted in a simple, ultra-short base name; pkey and fkey for primary and foreign keys respectively, and idx for other indexes.  If the index is unique, the base name is uidx.  It’s highly unlikely you will use any of the base names by themselves, however — unless you have only one of each type of index for your entire database.  This is virtually never the case.  So, in keeping with the other object naming standards, one or more prefixes are added to distinguish one object from another.

Table Name Prefix  The first prefix for all key/index names is the table name with which the object is associated.  Continuing with the example above, the names will therefore be DogPkey, DogFkey and DogIdx and DogUidx.  You might think that the first letter shouldn’t be capitalized, but you’d be wrong.  The use of the capitalized first letter visually connotes the table name.  As usual camel case is used to distinguish the various components of the object name, and therefore pkey becomes Pkey when the prefix is added.

Additional Primary Key Prefixes  There really should be only one primary key, so there are no additional standards  primary keys.  In other words, if you find yourself wanting to name two indexes firstDogPkey and secondDogPkey, you should think long and hard as to whether you’re not trying to paper over some fundamental flaw in your database design.

Foreign Key Prefixes  Foreign keys define a relationship between two tables.  You have referred to one of them with the table name prefix described above.  Now, add the name of the table that is being referenced with the foreign key.  A foreign key to the Breed table will therefore be BreedDogFkey.

Index Prefixes  The column, or columns, that form the basis for the index should be used as prefixes for indexes.  nmDogUidx is a unique index on the Dog.nm column.  lblDogIdx is an index on Dog.lbl

Compound Index Prefixes  Let’s assume you have a unique index that ensures a dog’s name is unique within a given breed.  This will be enforced with an index that refers to the nm, and id_Breed columns in the table Dog.  The two  columns that make up the index should be prefixed to the object name, in the order the columns appear in the table.  Technically, this means the name of the index should be nmId_BreedDogUkey.  However, the id_ makes the object name much less readable, and doesn’t add a lot in terms of meaning, so it’s dropped.  Hence the ‘correct’ name for this index would be nmBreedDogUidx.

Multiple Foreign Keys to the Same Table   All is well except in the situation where you have two indexes defining foreign key relationships to the same table — and it does happen, from time-to-time.  For instance, let’s assume you have two columns in Dog called uid_Session_create and uid_Session_modify.  Both are foreign keys to the Session table.  In which case, you have to add yet another prefix to the index name; hence, createSessionFkey, modifySessionFkey.  Note that in this case, the prefix is not capitalized, this is because it descriptive in nature (attribute-ish, if you will) rather that identifiying another object.

That’s it — it always seems like it takes much longer to explain the standard than to apply it.  Like other standards described previously, once you use them for a while, they become second nature, and very easy to apply.  Thank you very much for reading and, by all means, let me know what you think.

Charlie Rose a Limited Partner in KPCB?

In his most recent interview with Tom Perkins, who was on to discuss his book Valley Boy, Charlie Rose dropped a bombshell which is rather stunning in his implications.  Mr. Rose quietly mentioned he is a limited partner in KPCB.  That is his prerogative, of course, and to his credit, he did disclose the information to the public. 

On the other hand, it would appear to put him in a position of conflict with at least some of his guests.  In other words, the next time he has Google’s Larry, Sergey or Eric on the show, for example, will they really have something interesting and new to say, or is Charlie looking for an uptick in his investment?

I have the greatest respect for Mr. Rose, but it does seems like an oversight for somebody with Charlie’s good judgement to allow a little profit sully his journalistic independence, even if that compromise is one of appearance, rather than substance.

Valley Boy: The Education of Tom Perkins

ValleyBoy The most revealing moment of Valley Boy, Tom Perkins’ recently published autobiography, comes on page 143 where the author describes a brief, informal conversation with Dave Packard.  In the conversation,  Packard rhetorically asks; "[H]ow did I ever let you get away from HP?"  Perkins identifies this as the single most significant compliment of his entire life.  So, even for those who achieve almost unimaginable material success, there is still a mysterious rosebud which is the essential key to happiness.  No matter where life takes us, perhaps the thing we will always seek the most is the approval of our parents.

This is fascinating, given that Mr. Perkins is the P in KPCB, the legendary Kleiner Perkins Caulfield and Byers that arguably invented Silicon Valley-style venture capital.  At the very least, they perfected it, and raised it to the pantheon of unadulterated, unapologetic, American-style free enterprise.  Perkins and KPCB hits have been spectacular to say the least — ever hear of a couple of little outfits called Amazon and Google? — but there have also been some fairly spectacular failures, as well.  Perkins is surprisingly candid talking about them.  Despite what anybody might say or think about Perkins, he is, at the very least, blessed with crystal clear self-perception.

What’s harder to know is whether any of Perkins’ accomplishments have provided any level of satisfaction for him.  Right up until the very last line of the main text, when he finishes describing the construction and launch of the magnificent Maltese Falcon, he hints that there are still more rivers to cross and dragons to slay.  There are also earlier signs of the same condition; he spends quite a few pages describing his passion for old, supercharged sports cars.  He then wraps the chapter up with how he sold them all for no better reason than it was the ‘peak of the market’.  There’s an inherent sadness in this state of affairs, where love is for sale and measured in dollars and cents.  Perkins is passionate, yet passionless.

Valley Boy describes some rollicking adventures, which makes it somewhat of a pulpy, page-turner at times.  His run-in with a bond trader that nearly lost Kleiner and Perkins’ entire founding stake, and his collision with a coke-fiend, former-friend CEO seem taken more from Perkins’ Sex and the Single Zillionaire than from real life.   They must be true, though, because it’s hard to imagine in a life so full of astounding, verifiably true stories, Perkins would resort to making anything up.  One wonders, though, why the tech-savvy author wouldn’t have taken the time to Google "natasha steinmetz celebrity wire" before quoting the entire interview in Chapter Ten.  The latter leaves the reader with the impression Perkins may have adopted the ‘memoire’ format pioneered by James Frey.

It’s possible for those who achieve great wealth to make the transition from insufferable upstart to establishment magnate, and somehow pick up a clear understanding of noblesse oblige along the way.  Bill Gates will undoubtedly be remembered for his founding role in Microsoft, but in very long term, he will likely be just as well known for his work at the Bill & Melinda Gates Foundation.  Perkins has undoubtedly done his fair-share of philanthropic work, and has given a substantial chunk of his fortune to this end.  He talks extensively about his hands-on work with the San Francisco ballet, for example — but his underlying motivation is less clear.  Being the ‘best damned philanthropist in history’ might just be it.  But, in the end, the good work still gets done — and that’s what it’s all about, right?  However, even in the altruistic sphere, Perkins must dominate and control the work in order to be effective.  Effective, yes, but less appealing than you might like.

You would think that Perkins, having achieved near mythological status in his own career, would be satisfied to be married to someone equally successful in their own, respective domain.  Yet, in his brief marriage to Danielle Steele,  Perkins is compelled to compete with her, which seems driven by near anti-social competitiveness rather than any desire to write a ’sex novel’ (as Perkins calls it).  Fair enough, but really, what is the point?  Perkins provides little if any insight in this regard, and yet it is likely this same flaw in his character that made him so successful in the first place.  This is what we really want to know about Perkins, and yet we are left to figure out the answer ourselves.

Structurally, the format of Valley Boy is jarring.  As Perkins himself readily admits in the preface, it’s really a series of anecdotes, seemingly sequenced in the order in which they came out of his head.  It’s quirky, or maybe just lazy.  I’m paraphrasing, but essentially he tells the reader that if they’re looking for logic in the way the book is structured, there isn’t any — rather, these are the stories that would come up in dinner conversation.  And mighty good stories, they are.  If you ever found yourself Mr. Perkins’ dinner guest, you’d be well advised to shut up and listen; you’ll be entertained, certainly, and you may just learn something along the way.

To say that Tom Perkins is complicated is as blindingly obvious as it is true.  The reader is left to figure out the puzzle though — the anecdotes that make up Valley Boy have to be pieced together in the readers mind to try and get an integrated picture of the author.  Like Picasso, some will see seminal modern art, and others will just see a bunch of ugly, squiggly lines.  It may be cliché, but its both, and neither, at the same time.

If you’re looking for a history lesson on Silicon Valley, two recently published books, Bill & Dave by Michael S. Malone and Andy Grove by Richard S. Tedlow are well-researched, well-written, fact-laden and thoroughly readable works.  However, if you’re just about to jump a flight to Palm Springs and need something to read by the pool, Valley Boy will be right up your alley.  The chapters are certainly short enough that you’ll get through at least one before dozing off under that beautiful Coachella Valley sun.

Whither NTEXT versus NVARCHAR(MAX)?

Prior to SQL Server 2005, handling long strings of text, Unicode text and binary objects was accomplished with TEXT, NTEXT, and VARBINARY data types, respectively.  Looking back on it and if memory serves me correctly, they were frustratingly difficult to use.  In particular, you couldn’t use them as parameters in stored procedures, or do the normal stuff you expect to be able to do with strings.  If you look up the word ‘afterthought’ in the dictionary, it says See TEXT, NTEXT and/or VARBINARY.  Enough said.

Thankfully, SQL Server 2005 brought with it three new data types VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX).  To come right to the point, I can’t think of one reason why anyone would write a new line of code today with any of the old data types.

In case you doubt the soundness of the argument, here’s one, immediate benefit; you can use SUBSTRING on VARCHAR(MAX) or NVARCHAR(MAX).  If you have first-hand experience of the torture you had to subject yourself to in order to achieve SUBSTRING functionality with the old types, you’ll agree with my assessment.  If not, you may be underwhelmed by the fact that the new types finally work like they’re supposed to.   Regardless, you’ll benefit from their capabilities.

Admittedly, it’s handy that Microsoft left the old datatype in the code base.  There is a lot of user developed code out there that depends on them being there, and it wouldn’t be acceptable to have that all  break.  However, I can see the benefit of a switch that would mask out these functions, so you could quickly pin down where references have been made and update them.  Or alternatively, you could use the DatabaseObject view I presented a while back to quickly look through your database objects to see where there are references to the old data types.

While a slightly different subject, please don’t get me started on VARCHAR vs. NVARCHAR.  In this flat world, it’s reasonable to assume that anything you do will wind up in another (human) language at some point or another — and one that may demand Unicode.  So why would you write a new line of code using VARCHAR?  Memory, disk space, and processing speed has become so cheap the paradigm really has shifted.  It no longer makes any sense to use VARCHAR based on some notion of preservation of resources.

As always, thank you for reading, and let me know what you think.

Moto Q/Windows Mobile’s Biggest Oversight

I have been using Motorola’s Moto Q on Telus for quite some time now — a few months at least — and I’m reasonably satisfied with it. It certainly meets my requirements taking into account relatively low voice-call volume, and the text/email interfaces are reasonably good.

However, there is one thing that it doesn’t do which seems like a really significant oversight — there is no way to modify an existing task! My work style is very list driven; it’s sad, I admit, that pretty much everything for me is a list of tasks. What’s true, of course, is tasks and priorities change all the time.  So if the only recourse is to delete the task, and then re-add it with the updated information, that seems like a lot of fuss to get the job done.

Of course, it’s entirely possible that a dud like me has simply missed the part of the manual that covered this. Or if I really am correct, and it really doesn’t do this, maybe there is some sort of work around or fix? In either case, if you’ve encountered this problem and solved it, by all means let me know.

Actually, come to think of it, there’s one other thing that really is abominable — ActiveSync.  But I’ll lament that some other time.

ZoomIt: Pan, Zoom and Annotate Your Live Presentations

Recently, I saw a great utility when it was used by John Bristowe in a Microsoft Canada road show.  ZoomIt  by Mark Russinovitch is used to quickly pan, zoom and annotate your live presentations. If you’re one of those people who likes to talk with their hands — like me — you’re going to love this.

Using ZoomIt is very simple; launch the utility (a desktop shortcut is a good idea for this), and then toggle zooming mode using Ctrl-1. Once in ZoomIt mode, the mouse wheel is zoom-in and zoom-out, and moving the mouse is your pan.  Very intuitive.  Left click, and you can write on the presentation using the mouse.  Esc cancels everything, and you’re back to exactly where you left off before invoking ZoomIt.

All key sequences can be configured. I use Alt-~ to invoke ZoomIt. This works best for me, based on my particular keyboard and where my left hand naturally comes to rest. I find in presentation scenarios, there is usually enough stress to make even simple tasks difficult, so finding a combination of keys that is really intuitive is helpful.

In your next presentation, belt it out to the back row with ZoomIt. Your audience will thank you. Speaking of which, thank you very much for your reading, and let me know what you think.

Blank Property Pages in Visual Studio 2005

I spent the better part of half a day chasing this problem, so I figured I would make a brief post in the hope I can save another developer the frustration of chasing down a solution.

Problem

I was working with the Dataset Designer in Visual Studio 2005, and was about to make a very minor change to one of the DataTable objects.  After hitting F4, I was surprised, and a little dismayed, to find the property page blank.  I then discovered I couldn’t get properties for anything — not for a table, not for a column, nothing!  I first thought this was a result of a hand edit of the XSD (to reverse the sequence of two columns), and somehow, there was some corruption preventing Designer from reading to the XSD to get properties.  I then discovered the problem was more widespread than I first thought. For the life of me, I couldn’t get the properties for any object to show — even very simple, straightforward things, like buttons on a form.  I had visions of having to reinstall VS 2005 or some such butchery, but it turns out it was a simple and effective fix.

Solution

Some digging with Google yielded up the answer.  Briefly stated, it’s the devenv.exe utility, used with the /setup option, executed from the Visual Studio Command Prompt.  To access this,  click Start, then All Programs, then Microsoft Visual Studio 2005, then Visual Studio Tools, and finally click Visual Studio Command Prompt.  When the command prompt appears, type;

devenv /setup

It takes quite a few seconds to run…maybe as much as a minute.  Also, the utility runs without generating any sort of feedback.  When it completes, the command prompt simply re-appears.  But when Visual Studio 2005 fires up — voilà! — the property pages will have returned.  

Full credit where it is due; I found this answer on the ASP.Net forum, authored by Benson Yu.  As always, thank you very much for reading, and let me know what you think.

Jeff Bezos Talks to Charlie Rose about Kindle

Although it had to wait for a couple of days on the DVR, I finally got around to watching Jeff Bezos on the Charlie Rose show.  I have seen Mr. Bezos interviewed a couple of times before, but this time, his comments really caught my attention.  He talked at length about the recent launch of Kindle and despite my initial reservations about the idea, Bezos makes a fairly convincing argument for this device — one that he envisions improving on, and eventually replacing, the book.  It’s an ambitious target, to say the least.

I won’t try and re-spin Bezos’ arguments for Kindle — the best way to get up to speed is to simply watch the interview.  He talks precisely and succinctly about Kindle and its capabilities.  However, it’s when he talks about the device in the context of the publishing industry and the Amazon universe in general that it really gets interesting.  The device, as Bezos says, really does "out-book the book", in many respects.  So I’m reasonably convinced it will have an impact.

However, one potential drawback of Kindle is that its primary strength may also be its primary weakness.   With the advent of pervasive Google, your work is always at the mercy of the hyperlink.  Run into a problem with your latest code?  Google gets you more information that you could possibly consume in hours, or even days.  Before you know it, you’re so far down the click stream you can’t remember where you started.  Kindle provides this same opportunity/drawback.  With an ink-and-paper book, however, you really are forced into the moment.  Don’t know something about what it is your reading?  Tough, you’ll just have to look it up later, and continue with the page in front of you.

By no means, does this prevent Kindle from being a success.  For the majority of reading that I do these days, it would be great.  But if I really want to focus on the material at hand — at the exclusion of all other things — there are certain limitations to the printed book that I still value having.

I am a fan of the Charlie Rose show.  You’ll see people on it that you will never see on mainstream television.  Charlie also takes the time to become knowledgeable of his guests and their area of expertise, so he can ask well informed and intelligent questions.  It seems as though information technology is of particular interest to Charlie, as he seems able to ask just the questions to which I want to hear the answer. 

Even though I really am a fan,  I think it’s a fair comment to say that  Charlie occasionally talks too much at the expense of his guests.  Not so with this interview.  Charlie asks just the right questions, but more  importantly, gives Bezos the opportunity to answer the questions fully and completely. 

Incidentally, Jeff talks a little about Blue Origin, which is a project that I had never heard of, and certainly had no idea Bezos was involved in.   Get this, Jeff is getting into suborbital space flight.  I’m looking forward to reading more about this, and watching this latest venture in the future.  If you’re a little jaded about the world, watch the videos on the Blue Origin website and try and tell me you’re not just a little inspired — and hopeful — about the future.

What I got out of this interview is what I always hope to get out of an interview I see.  To hear the questions asked that I would have asked if I had been lucky enough to be the interviewer, and give the subject of the interview the opportunity the answer the question  properly.  But more important than that I like to be inspired by the subject and the material — and Charlie Rose and Jeff Bezos delivered that, in spades.