Generate Columns for Update Statements
I'm not a fan of most CRUD generators. The formatting doesn't match my style, and I usually spend about as much time modifying the generated code as I would spend just writing it from scratch. But there's been times when I've considered using CRUD generators, mainly when I'm writing updates on wide tables. If you've never written an update for a table with many columns, it's not sexy. You're wasting valuable time on a tedious task that you could instead spend reading SQL Server 2008 Internals or chewing the cud with the SQL Twitterati.
Fortunately, Dave Carlile shared another tip with me that helps with this and has made it's way into my little bag of tricks.
Let's assume you having the following outline:
Update sales Set ['insert really long column list'] From Sales.vStoreWithDemographics As sales Join myTempTable As mtt On sales.someColumn = mtt.someColumn;
You could use the following code to generate a list of columns for you:
Select name + ' = sales.' + name + ',' From sys.columns Where object_id = object_id('Sales.vStoreWithDemographics') Order by column_id;
Just replace [Sales.vStoreWithDemographics] with a table of your choice, and replace "sales." with the appropriate alias.This will return a list of nicely formatted columns for you. Best of all, no potential for column typos! Just don't forget to remove the very last comma, otherwise you'll get a syntax error.
CustomerID = sales.CustomerID, Name = sales.Name, ContactType = sales.ContactType, (etc.)
I know, nothing earth shattering, but definitely one of those "huh, why didn't I think of that?" moments. So, thanks, Dave!
Source: http://sqlfool.com/2009/03/generate-columns-for-update-statements
Categories
- Business Intelligence
- Internals
- Miscellaneous
- PASS
- Performance & Tuning
- Presentations
- SQL 2008
- SQL Tips
- Syndication
- T-SQL Scripts
Subscribe to my blog!
| Like what you see? Subscribe! |
![]() |
Around the Web
Recent Tweets
- @gregsohl yeah, that would be a nice feature. Did you find any products that do support field-level dependencies?
- @MladenPrajdic @atlantis_uk Thanks, Mladen, I'll be sure to check that out. :)
- I'm really lovin' @RedGate's #SQL Dependency Tracker. I can see it saving me a *lot* of time once I figure out what the heck I'm doing :)
Archives
- November 2011
- October 2011
- September 2011
- July 2011
- June 2011
- May 2011
- April 2011
- January 2011
- December 2010
- November 2010
- October 2010
- September 2010
- July 2010
- June 2010
- May 2010
- April 2010
- February 2010
- January 2010
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008


