Wednesday, October 21, 2009

Default New Query for SQL Server Management Studio

I found an article about how to change this on the web.  The file can be found at C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\SqlWorkbenchProjectItems\Sql\SQLFile.sql for SQL 2008.  It can be found at C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE\SqlWorkbenchProjectItems\Sql\SQLFile.sql for SQL 2005.  I thought I would give it a shot and see what became useful for me. This is now my default New Query document contents in both SSMS 2005 and SSMS 2008.

-- Set the transaction isolation level explictly
SET TRANSACTION ISOLATION LEVEL READ uncommitted

BEGIN TRAN

BEGIN TRY

-- Replace this with the actual work ;)

-- Here is an example breakpoint
RAISERROR (N'BREAKPOINT.',16,1);
END TRY

BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);

DECLARE @ErrorSeverity INT;

DECLARE @ErrorState INT;

SELECT Error_number() AS errornumber,
Error_severity() AS errorseverity,
Error_state() AS errorstate,
Error_procedure() AS errorprocedure,
Error_line() AS errorline,
Error_message() AS errormessage;

-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH;

IF @@TRANCOUNT > 0
COMMIT TRANSACTION;



Tuesday, October 20, 2009

RESEED all tables with Identity Columns in a Database

I had a problem today where a comparison tool had inserted lots of data into a database and it was then propagated to other environments. We started seeing errors and needed to ensure that all tables were fixed. This was the hack I came up with. Enjoy

DECLARE @SQL NVARCHAR(MAX)

DECLARE reseed CURSOR FAST_FORWARD FOR
SELECT N'DBCC CHECKIDENT (' + Quotename(Object_name(object_id)) + N',RESEED)'
FROM sys.columns
WHERE is_identity = 1
AND Objectproperty(object_id,'IsTable') = 1

OPEN reseed

FETCH NEXT FROM reseed
INTO @SQL

WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF (@@FETCH_STATUS <> -2)
BEGIN
EXEC dbo.Sp_executesql
@SQL
END

FETCH NEXT FROM reseed
INTO @SQL
END

CLOSE reseed
DEALLOCATE reseed