Useful T-Sql Snippets for my Reference
Get the list of all Primary Keys and associated foreign keys:
select a.name,c.name as pk_table ,b.name fk_table
from sys.foreign_keys a
inner join sys.sysobjects b on b.id = a.parent_object_id
inner join sys.sysobjects c on c.id = a.referenced_object_id
Richard Campbell's session on Error Handling using Sql Server 2005's Try Catch:
RETRY:
BEGIN TRY
BEGIN TRANSACTION
UPDATE tblContact SET LastName = 'SP_LastName_1' WHERE ContactID = 1
UPDATE tblContact SET LastName = 'SP_LastName_2' WHERE ContactID = 2
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SET @Err = @@ERROR
IF @Err = 1205
ROLLBACK TRANSACTION
INSERT INTO ErrorLog (ErrID, ErrMsg) VALUES (@Err, 'Deadlock recovery attempt.')
WAITFOR DELAY '00:00:10'
GOTO RETRY
IF @Err = 2627
SET @ErrMsg = 'PK Violation.'
IF @ErrMsg IS NULL
SET @ErrMsg = 'Other Error.'
INSERT INTO ErrorLog (ErrID, ErrMsg) VALUES (@Err, @ErrMsg)
END CATCH
If you carefully notice, Catch exception above handles the logic based on the type of error captured.
select a.name,c.name as pk_table ,b.name fk_table
from sys.foreign_keys a
inner join sys.sysobjects b on b.id = a.parent_object_id
inner join sys.sysobjects c on c.id = a.referenced_object_id
Richard Campbell's session on Error Handling using Sql Server 2005's Try Catch:
RETRY:
BEGIN TRY
BEGIN TRANSACTION
UPDATE tblContact SET LastName = 'SP_LastName_1' WHERE ContactID = 1
UPDATE tblContact SET LastName = 'SP_LastName_2' WHERE ContactID = 2
COMMIT TRANSACTION
END TRY
BEGIN CATCH
SET @Err = @@ERROR
IF @Err = 1205
ROLLBACK TRANSACTION
INSERT INTO ErrorLog (ErrID, ErrMsg) VALUES (@Err, 'Deadlock recovery attempt.')
WAITFOR DELAY '00:00:10'
GOTO RETRY
IF @Err = 2627
SET @ErrMsg = 'PK Violation.'
IF @ErrMsg IS NULL
SET @ErrMsg = 'Other Error.'
INSERT INTO ErrorLog (ErrID, ErrMsg) VALUES (@Err, @ErrMsg)
END CATCH
If you carefully notice, Catch exception above handles the logic based on the type of error captured.
Comments