# Thursday, October 06, 2005
« Security: Links, and one significant pr... | Main | Using Fiddler to debug .NET Web Services... »

Looks like it's about time for another post!

This one is about the SQL Server system tables.  These are a fav of mine because I find them so useful in scripts. 

The caveats when dealing with them are you need to be mindful of SQL Server versions.  Everything that worked on SQL Server 7.0 will work on SQL Server 2000, but there are some minor tweaks in SQL Server 2000 that are not valid in SQL Server 7.0.  Now is not a good time to mention SQL Server <= v6.5 because the system tables had an overhaul for 7.0, and I haven't checked any of this code on Yukkon/SQL Server 2005 yet.

My fav thing to use the tables for is dealing with object existance in scripts.  In my books a good T-SQL script can be run over and over without damaging the database.  Put another way, if your SQL Script throws an error if it is run twice against the same database it's not a good T-SQL script.

Consider we are dealing with the following table:

CREATE TABLE testing_data (
    pkey INT IDENTITY (1,1) NOT NULL,
    created DATETIME DEFAULT getdate() NOT NULL,
    modified DATETIME NULL,
    deleted BIT DEFAULT 0 NOT NULL,
    testing_val_1 NVARCHAR(15) NOT NULL,
    testing_val_2 NVARCHAR(255)
)


For whatever reason we want to drop and recreate this table each run, you could put the following statement before it:

IF Exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[testing_data]')
    AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
    DROP TABLE testing_data
GO

This is the syntax you will see if you choose to include Drops in scripts you generate from the Enterprise Manager, but I don't use it much, mainly because I can never remember the OBJECTPROPERTY() syntax!

Typically I do the following:

IF Exists(SELECT [id] FROM sysobjects
    WHERE sysobjects.[name] = N'testing_data'
    AND sysobjects.[type] = N'U')
    DROP TABLE testing_data
GO

I feel that Microsoft are hinting us towards using OBJECTPROPERTY() for future version compatability, but I still favor this syntax because apart from being easy to remember it's easy to adapt for other kinds of objects, e.g:

IF Exists(SELECT [id] FROM sysobjects
        WHERE sysobjects.[name] = 'prGetTestingDataRows'
        AND sysobjects.[type] = 'P')
    DROP PROC prGetTestingDataRows
GO

So if the Type column in sysobjects is 'U' for user tables, and 'P' for procedures then there are no prizes for guessing what TR, D & V might mean.

For a more complex example, lets say you want to change the type of the fileds testing_val_1 to NVARCHAR(35) ONLY if it has not been changed before, you could wrap the ALTER TABLE stateement in the following BEGIN... END:

IF Exists(SELECT syscolumns.[name]
    FROM syscolumns
    LEFT JOIN sysobjects
        ON syscolumns.[id] = sysobjects.[id]
    LEFT JOIN systypes
        ON syscolumns.[xtype] = systypes.[xtype]
    WHERE syscolumns.[name] = 'testing_val_1'
    AND systypes.[name] = 'nvarchar'
    AND sysobjects.[name] = 'testing_data')
BEGIN
    ALTER TABLE -- ... Implementation ommited for clarity
END

So having only touched two or three sys tables we have a couple of good tools that are easy to use.  I'll cover more at a later date, in the mean time enjoy the extra metadata!

After blog mint [?]:

Here's an actual practical example from a script I have been working  on recently (user name changed).  This script makes a dozen or so procs, the svcapp account is a login used by a service that only has rights to exec these procs, and no rights granted to the base tables.  This automates granting access to the created procs, and it much quicker than doing it in the SQL EM:

PRINT 'PART 4 - Granting access to user account'
GO

DECLARE @sql NVARCHAR(512)
DECLARE @name NVARCHAR(128)
DECLARE @usernm NVARCHAR(128)
DECLARE cr CURSOR FOR
    SELECT [name] FROM sysobjects
    WHERE type='P'
    ORDER BY [name]

SET @usernm = 'svcapp'

OPEN cr
FETCH NEXT FROM cr INTO @name

WHILE @@fetch_status = 0
BEGIN
    SET @sql = 'grant exec on ' + @name + ' to ' + @usernm
    EXEC sp_executesql @sql
    PRINT 'Granting EXEC on ' + @name + ' to user: '
    FETCH NEXT FROM cr INTO @name
END

CLOSE cr
DEALLOCATE cr

PRINT 'Done.'
GO


Thursday, October 06, 2005 11:24:38 PM (AUS Eastern Standard Time, UTC+10:00)  #    Disclaimer  |  Comments [1]  |  Related posts:
Visual Studio 2008 Professional vs. Standard edition. Just what are the differences? Is it Features?
The var keyword (C# 3.0) - Nothing at all like VB6 Variant - It's not even a Type!
Bringing Grep back using PowerShell
iTunes messages not getting any better despite constant updates!
First DR scare at the new office
Sign your way to better quality with a x509 Certificate
Tracked by:
"movin' on up..." (movin' on up...) [Trackback]
"Do Me In The Button Order Form" (Do Me In The Button Order Form) [Trackback]
"yellow." (yellow.) [Trackback]
"do me in the button [1" button design and production]" (do me in the butto... [Trackback]
"yellow.thecampaign.net/photos.php" (yellow.thecampaign.net/photos.php) [Trackback]
"the campaign records (photos)" (the campaign records (photos)) [Trackback]
"yellow is a rock band based out of sydney, nova scotia. formed in" (yellow is a... [Trackback]
"paid to take surveys" (paid to take surveys) [Trackback]
"i was a spy (for about 6 years)" (i was a spy (for about 6 years)) [Trackback]
"Tom Fun & the Holy Microphone Machine" (Tom Fun & the Holy Microphone M... [Trackback]
"the following two tracks are from our first album, "the heat'll be" (t... [Trackback]
"one day late" (one day late) [Trackback]
"bands: i was a spy one day late great plains the ditchpigs" (bands: i was a spy... [Trackback]
"news" (news) [Trackback]
"shoes and boots search" (shoes and boots search) [Trackback]
"Rent Apartments" (Rent Apartments) [Trackback]
"the campaign records" (the campaign records) [Trackback]
"get work from home" (get work from home) [Trackback]
"the campaign records messageboard!" (the campaign records messageboard!) [Trackback]
"i was a spy - progressive punk rock / coffee-core" (i was a spy - progressive p... [Trackback]
"i was a spy (for about 6 years)" (i was a spy (for about 6 years)) [Trackback]
"news" (news) [Trackback]
"boston table tennis online" (boston table tennis online) [Trackback]
"yellow can be contacted by paper mail at the following address" (yellow can be ... [Trackback]
"content" (content) [Trackback]
"ebay used cars" (ebay used cars) [Trackback]
"Triumph the Insult Comic Dog Downloads" (Triumph the Insult Comic Dog Downloads... [Trackback]
"italian handbag" (italian handbag) [Trackback]
"junction%2c tx real estate" (junction%2c tx real estate) [Trackback]
"Delorean Replicas" (Delorean Replicas) [Trackback]
"Pin Striping Tape" (Pin Striping Tape) [Trackback]
"dual channel ram" (dual channel ram) [Trackback]
"accomplishments of Martin Luther King Jr." (accomplishments of Martin Luther Ki... [Trackback]
"Se47 Full Housing" (Se47 Full Housing) [Trackback]
"motivation scale" (motivation scale) [Trackback]
"Facts about Georgia" (Facts about Georgia) [Trackback]
"iron based adsorbents" (iron based adsorbents) [Trackback]
"rural houses in majorca" (rural houses in majorca) [Trackback]
"Rio de Janiero" (Rio de Janiero) [Trackback]
"antifurto auto" (antifurto auto) [Trackback]
"cumaru engineered hardwood" (cumaru engineered hardwood) [Trackback]
"j2ee servlet" (j2ee servlet) [Trackback]
"linux format" (linux format) [Trackback]
"Ulysses S Grant" (Ulysses S Grant) [Trackback]
"Problems with Pontiac Bonneville" (Problems with Pontiac Bonneville) [Trackback]
"sniffing dirty underwear and crotches" (sniffing dirty underwear and crotches) [Trackback]
"Florida boating accident attorney" (Florida boating accident attorney) [Trackback]
"motion control systems" (motion control systems) [Trackback]
"18 and i still wet the bed" (18 and i still wet the bed) [Trackback]
"samsonite tripods" (samsonite tripods) [Trackback]
"Flathead Reservation" (Flathead Reservation) [Trackback]
"bead jewelry" (bead jewelry) [Trackback]
"bipolar disease" (bipolar disease) [Trackback]
"Men%27s Pocket Watches" (Men%27s Pocket Watches) [Trackback]
"acrylic nail removal" (acrylic nail removal) [Trackback]
"WICKED WITCHES OF LEGEND AND LORE" (WICKED WITCHES OF LEGEND AND LORE) [Trackback]
"flood guard door" (flood guard door) [Trackback]
"NCHRP 350" (NCHRP 350) [Trackback]
"wireless pet containment system" (wireless pet containment system) [Trackback]
"clomid use to overcome low sperm count" (clomid use to overcome low sperm count... [Trackback]
"ball shear process validation" (ball shear process validation) [Trackback]
"Canada Post" (Canada Post) [Trackback]
"fosamax alternative" (fosamax alternative) [Trackback]
"stair manufacturers" (stair manufacturers) [Trackback]
"Hot Cheerleaders" (Hot Cheerleaders) [Trackback]
"lubus world passwords" (lubus world passwords) [Trackback]
"gucci gg cufflink" (gucci gg cufflink) [Trackback]
"what have the pyramids got to to with the sky" (what have the pyramids got to t... [Trackback]
"Clothing Optional Resorts" (Clothing Optional Resorts) [Trackback]
"pogo stick" (pogo stick) [Trackback]
"community bible study" (community bible study) [Trackback]
"cdlive" (cdlive) [Trackback]
"AMD Processors" (AMD Processors) [Trackback]
"Im Injection Instruction" (Im Injection Instruction) [Trackback]
"cartoon network" (cartoon network) [Trackback]
"tax return forms" (tax return forms) [Trackback]
"wakeboard boats" (wakeboard boats) [Trackback]
"Mad World" (Mad World) [Trackback]
"baseball betting newsletter" (baseball betting newsletter) [Trackback]
"portaporteseit" (portaporteseit) [Trackback]
"smoking chimp" (smoking chimp) [Trackback]
"hoover air purifier filter" (hoover air purifier filter) [Trackback]
"freschissimocelestemadre" (freschissimocelestemadre) [Trackback]
"massaggiorelax" (massaggiorelax) [Trackback]
"chimicaappunti" (chimicaappunti) [Trackback]
"serviziocatering" (serviziocatering) [Trackback]
"online casino roleta roulette ca" (online casino roleta roulette ca) [Trackback]
"School of rock by Jack Black" (School of rock by Jack Black) [Trackback]
"pallidofighettesesso" (pallidofighettesesso) [Trackback]
"cameradicommerciodiverona" (cameradicommerciodiverona) [Trackback]
"add" (add) [Trackback]
"volkswagenitalia" (volkswagenitalia) [Trackback]
"faircamerierapompino" (faircamerierapompino) [Trackback]
"business and commercial lawyer rating" (business and commercial lawyer rating) [Trackback]
"thanksgiving crap" (thanksgiving crap) [Trackback]
"tomtomgo700" (tomtomgo700) [Trackback]
"distribuzionilinux" (distribuzionilinux) [Trackback]
"cellulite laser treatment frederick" (cellulite laser treatment frederick) [Trackback]
"rovereto" (rovereto) [Trackback]
"bingo halls in colorado springs" (bingo halls in colorado springs) [Trackback]
"belletettine" (belletettine) [Trackback]
"bollettinopostale" (bollettinopostale) [Trackback]
"ss dagger pins" (ss dagger pins) [Trackback]
"sony dcrtrv33 mini dv camcorder" (sony dcrtrv33 mini dv camcorder) [Trackback]
"royal oak daily tribune" (royal oak daily tribune) [Trackback]
"propagating dwarf mondo" (propagating dwarf mondo) [Trackback]
"jurassic park operation genesis ps2 cheats" (jurassic park operation genesis ps... [Trackback]
"dwarf miscanthus nippon" (dwarf miscanthus nippon) [Trackback]
"camcorder canon dv mini opturaxi" (camcorder canon dv mini opturaxi) [Trackback]
"psat prep classes dekalb illinois" (psat prep classes dekalb illinois) [Trackback]
"koga ryu nin jutsu" (koga ryu nin jutsu) [Trackback]
"protable dvd players protable dvd players" (protable dvd players protable dvd p... [Trackback]
"tmj night guard" (tmj night guard) [Trackback]
"dvd fab decrypter" (dvd fab decrypter) [Trackback]
"daft punk robot rock" (daft punk robot rock) [Trackback]
"nigerian dwarf goats colorado" (nigerian dwarf goats colorado) [Trackback]
"hp psc 1315xi all in one" (hp psc 1315xi all in one) [Trackback]
"mithgar dwarves" (mithgar dwarves) [Trackback]
"copying dvds" (copying dvds) [Trackback]
"daisuke ishiwatari" (daisuke ishiwatari) [Trackback]
"dainese leather jacket" (dainese leather jacket) [Trackback]
"jan barboglio" (jan barboglio) [Trackback]
"morrowind: where is the living dwemer" (morrowind: where is the living dwemer) [Trackback]
"remix no jutsu" (remix no jutsu) [Trackback]
"gerbera daisy bridal bouquet" (gerbera daisy bridal bouquet) [Trackback]
"daiwa emcast surf rod" (daiwa emcast surf rod) [Trackback]
"marilyn dahlenburg halloran" (marilyn dahlenburg halloran) [Trackback]
"muhibb dyer" (muhibb dyer) [Trackback]
"nativie american dwellings tipi longhouse wigwam" (nativie american dwellings t... [Trackback]
"ultraman dvd" (ultraman dvd) [Trackback]
"twig dwarf anole" (twig dwarf anole) [Trackback]
"house of flying daggers vimou zhang" (house of flying daggers vimou zhang) [Trackback]
"dyanna lauren nurse gallery" (dyanna lauren nurse gallery) [Trackback]
"daily jigsaw puzzles to play online" (daily jigsaw puzzles to play online) [Trackback]
"macbeth's dagger" (macbeth's dagger) [Trackback]
"portable car dvd player" (portable car dvd player) [Trackback]
"hp psc 2510 print memory fax transfer computer" (hp psc 2510 print memory fax t... [Trackback]
"game cheats for ps2" (game cheats for ps2) [Trackback]
"darkfusiondesigns.com" (darkfusiondesigns.com) [Trackback]
"coasar.com" (coasar.com) [Trackback]
"chhabranetwork.com" (chhabranetwork.com) [Trackback]
"click4stars.com" (click4stars.com) [Trackback]
"prontostudios.com" (prontostudios.com) [Trackback]
"cobeoffice.com" (cobeoffice.com) [Trackback]
"commercialbankquotes.com" (commercialbankquotes.com) [Trackback]
"areasii.com" (areasii.com) [Trackback]
"smartzy.com" (smartzy.com) [Trackback]
"buy-web-site-traffic.com" (buy-web-site-traffic.com) [Trackback]
"smartzy.com" (smartzy.com) [Trackback]
"sukkary.com" (sukkary.com) [Trackback]
"coffeebeenery.com" (coffeebeenery.com) [Trackback]
"byronhinterlandaccommodation.com" (byronhinterlandaccommodation.com) [Trackback]
"arabtraffic.com" (arabtraffic.com) [Trackback]
"cobetravel.com" (cobetravel.com) [Trackback]
"epaysurf.com" (epaysurf.com) [Trackback]
"chhabracorporation.com" (chhabracorporation.com) [Trackback]
"wa7ah.net" (wa7ah.net) [Trackback]
"slightly-morbid.net" (slightly-morbid.net) [Trackback]
"bikinipage1.com" (bikinipage1.com) [Trackback]
"chhabrahomes.com" (chhabrahomes.com) [Trackback]
"areasii.com" (areasii.com) [Trackback]
"comeworldwide.com" (comeworldwide.com) [Trackback]
"countyyardsales.com" (countyyardsales.com) [Trackback]
"frontlinetravels.com" (frontlinetravels.com) [Trackback]
"putitinwriting.net" (putitinwriting.net) [Trackback]
"combatduck.com" (combatduck.com) [Trackback]
"chhabrapharmaceuticals.com" (chhabrapharmaceuticals.com) [Trackback]
"tabak-meier.com" (tabak-meier.com) [Trackback]
"commercialbankquotes.com" (commercialbankquotes.com) [Trackback]
"chhabrafamilyfoundation.com" (chhabrafamilyfoundation.com) [Trackback]
"auctionsection.com" (auctionsection.com) [Trackback]
"internet-marketingpro.com" (internet-marketingpro.com) [Trackback]
"hornypics.net" (hornypics.net) [Trackback]
"avalon-knights.com" (avalon-knights.com) [Trackback]
"internet-marketingpro.com" (internet-marketingpro.com) [Trackback]
"wysiwygkennels.com" (wysiwygkennels.com) [Trackback]
"spaceless.net" (spaceless.net) [Trackback]
"auctionsection.com" (auctionsection.com) [Trackback]
"wysiwygkennels.com" (wysiwygkennels.com) [Trackback]
"gregpayneoffenses.com" (gregpayneoffenses.com) [Trackback]
"wysiwygkennels.com" (wysiwygkennels.com) [Trackback]
"whartongcc.com" (whartongcc.com) [Trackback]
"writewithapro.com" (writewithapro.com) [Trackback]
"namicmarketing.com" (namicmarketing.com) [Trackback]
"gregpayneoffenses.com" (gregpayneoffenses.com) [Trackback]
"spaceless.net" (spaceless.net) [Trackback]
"auctionsection.com" (auctionsection.com) [Trackback]
"caramigo.com" (caramigo.com) [Trackback]
"avalon-knights.com" (avalon-knights.com) [Trackback]
"whartongcc.com" (whartongcc.com) [Trackback]
"caramigo.com" (caramigo.com) [Trackback]
"wysiwygkennels.com" (wysiwygkennels.com) [Trackback]
"internet-marketingpro.com" (internet-marketingpro.com) [Trackback]
"whartongcc.com" (whartongcc.com) [Trackback]
"writewithapro.com" (writewithapro.com) [Trackback]
"gregpayneoffenses.com" (gregpayneoffenses.com) [Trackback]
"internet-marketingpro.com" (internet-marketingpro.com) [Trackback]
"writewithapro.com" (writewithapro.com) [Trackback]
"fetishe6.com" (fetishe6.com) [Trackback]
"wysiwygkennels.com" (wysiwygkennels.com) [Trackback]
"leomoctezuma.com" (leomoctezuma.com) [Trackback]
"ladyboy6.com" (ladyboy6.com) [Trackback]
"caramigo.com" (caramigo.com) [Trackback]
"learn-here" (learn-here) [Trackback]
"moleygarden" (moleygarden) [Trackback]
"thefactoryweb" (thefactoryweb) [Trackback]
"prisonlinks" (prisonlinks) [Trackback]
"overmad" (overmad) [Trackback]
"web-spyglass" (web-spyglass) [Trackback]
"tyemi" (tyemi) [Trackback]
"rxsquad" (rxsquad) [Trackback]
"idebenonecreams" (idebenonecreams) [Trackback]
"gingerbredibles" (gingerbredibles) [Trackback]
"davezillaworld" (davezillaworld) [Trackback]
"prisonfamilychat" (prisonfamilychat) [Trackback]
"dimebagdarrell" (dimebagdarrell) [Trackback]
"jokersville" (jokersville) [Trackback]
"illinicorp" (illinicorp) [Trackback]
"lasmobile" (lasmobile) [Trackback]
"bidphone" (bidphone) [Trackback]
"knerds" (knerds) [Trackback]
"diminishaging" (diminishaging) [Trackback]
"thewomansdream" (thewomansdream) [Trackback]
"nomorerent4me" (nomorerent4me) [Trackback]
"stpetebeachcondorental" (stpetebeachcondorental) [Trackback]
"jily" (jily) [Trackback]
"trademarkwatches" (trademarkwatches) [Trackback]
"travelrelatedstuff" (travelrelatedstuff) [Trackback]
"listentogod" (listentogod) [Trackback]
"nivosus" (nivosus) [Trackback]
"stureplan" (stureplan) [Trackback]
"noacreative" (noacreative) [Trackback]
"archetypefilms" (archetypefilms) [Trackback]
"accounting-live" (accounting-live) [Trackback]
"byggnadsingenjor" (byggnadsingenjor) [Trackback]
"extreminvest" (extreminvest) [Trackback]
"blakealexisjohn" (blakealexisjohn) [Trackback]
"sawauctions" (sawauctions) [Trackback]
"hipaaparser" (hipaaparser) [Trackback]
"daniellungren.com" (daniellungren.com) [Trackback]
"weemuffin.com" (weemuffin.com) [Trackback]
"proebiz.net" (proebiz.net) [Trackback]
"looloous.com" (looloous.com) [Trackback]
"ihealthywealthywise.com" (ihealthywealthywise.com) [Trackback]
"torahbums.com" (torahbums.com) [Trackback]
"newheavenproductions.com" (newheavenproductions.com) [Trackback]
"travel-resource.net" (travel-resource.net) [Trackback]
"royaljellyhouse.com" (royaljellyhouse.com) [Trackback]
"provenance-hosting.com" (provenance-hosting.com) [Trackback]
"swords-sources.com" (swords-sources.com) [Trackback]
"browno.com" (browno.com) [Trackback]
"technologyeverywhere.com" (technologyeverywhere.com) [Trackback]
"knitting-sources.com" (knitting-sources.com) [Trackback]
"steveelarbee.com" (steveelarbee.com) [Trackback]
"garganza.com" (garganza.com) [Trackback]
"peachevents.com" (peachevents.com) [Trackback]
"webhostcash.com" (webhostcash.com) [Trackback]
"harumph.com" (harumph.com) [Trackback]
"elegalities.com" (elegalities.com) [Trackback]
"ihankook.com" (ihankook.com) [Trackback]
"cooloptics.com" (cooloptics.com) [Trackback]
"stevesworldonline.com" (stevesworldonline.com) [Trackback]
"spacial-online.com" (spacial-online.com) [Trackback]
"proebizsystems.com" (proebizsystems.com) [Trackback]
"feelgoodindustries.com" (feelgoodindustries.com) [Trackback]
"latinreporter.com" (latinreporter.com) [Trackback]
"strictlyimages.com" (strictlyimages.com) [Trackback]
"2001corporation.com" (2001corporation.com) [Trackback]
"feelgoodministries.net" (feelgoodministries.net) [Trackback]
"feelgoodministries.com" (feelgoodministries.com) [Trackback]
"adamsphereproductions.com" (adamsphereproductions.com) [Trackback]
"confederate-inc.com" (confederate-inc.com) [Trackback]
"proebizinfo.com" (proebizinfo.com) [Trackback]
"model-airplanes-sources.com" (model-airplanes-sources.com) [Trackback]
"joeysrecovery.com" (joeysrecovery.com) [Trackback]
"milattansonra.com" (milattansonra.com) [Trackback]
"roadmaxauto.com" (roadmaxauto.com) [Trackback]