Tuesday, September 29, 2009

SnagIt is the Bomb!

I wholeheartedly endorse the screen capture program, SnagIt from TechSmith. They offer a free screen capture program called Jing, but SnagIt has so many features that it is worth the cost.

AutoGenerate IF EXISTS, DROP TABLE SQL

I created some SQL that can generate IF EXISTS, DROP TABLE SQL code for all existing tables in a database. Handy, if you need to create SQL for all or even most of the tables in your database without having to write the code yourself. SQL Server Management Studio can generate the code for each table individually, but I'm not aware that it can multiple tables at a time.
I set the Results to Text option because it keeps the text formatting for my SQL.

-- Generate an IF EXISTS, DROP TABLE SQL code for every table that currently exists in a database
-- For optimal text formatting, Set RESULTS TO TEXT to copy code.
-- 09.29.2009 http://tlinget.blogspot.com/

DECLARE @database varchar(128)
DECLARE @sql varchar(4000)

SET @database = 'yourdatabasename' -- User select which database to generate IF EXISTS, DROP TABLE SQL.

SET @sql = 'SELECT ''IF EXISTS(SELECT [name] FROM [' + @database + ']..sysobjects
    WHERE [name] = N'''''' + name + '''''' AND xtype=''''U'''')
    BEGIN DROP TABLE '' + name + '' END''
    FROM [' + @database + ']..sysobjects WHERE xtype=''U'''

PRINT '@sql: ' + @sql -- just some debugging to show the SQL generated

EXEC (@sql)