Wednesday, February 21, 2007

Two SQLServer SQL Tips

1) My transaction log file was gigantic (38GB). I fixed it by doing this:
sp_detach_db MyDB,
deleting my log file and then doing this:
exec sp_attach_db 'MyDB', '[pathToMDF]\MyDB.mdf'

2) When I'm writing a script that creates tables, I often want to drop the table if it already exists. Instead of writing out the if exists (select ...) drop table over and over again, I created a little stored procedure to do it:

CREATE PROCEDURE drop_table @tableName varchar(255) AS
if exists (select name from sysobjects where name=@tableName and type='U')
EXEC('DROP TABLE '+@tableName)
GO
Now I can drop a table like this: exec drop_table 'MyOldTable'. I created a similar procedure for dropping stored procedures.

Now that I think about it, I wonder whether T-SQL has the equivalent of Oracle's 'CREATE OR REPLACE'. That's basically what I've re-implemented here.

No comments: