Skip to content

Instantly share code, notes, and snippets.

@csdear
Last active August 29, 2015 14:11
Show Gist options
  • Save csdear/1217f68622cc7b9805bc to your computer and use it in GitHub Desktop.
Save csdear/1217f68622cc7b9805bc to your computer and use it in GitHub Desktop.
Transaction - COMMIT & ROLL BACK A safe guard against mistakes, best practice is to alway wrap changes that are going to affect the table in these transactional code snippets.
--1. BEGIN transaction, write your query and execute.
SELECT *
FROM [stuart_sandbox].[dbo].[Categories]
BEGIN transaction
UPDATE [stuart_sandbox].[dbo].[Categories]
SET Description ='Sushi'
WHERE CategoryID = '8'
--2. Check the results of your query
SELECT *
FROM [stuart_sandbox].[dbo].[Categories]
--3. Decision : If not expected results- ROLLBACK transaction.
--IF expected results - COMMIT transaction.
--COMMIT transaction
--ROLLBACK transaction
--******* Example 2 RW update replace, CASTS to overcome nTEXT and rollbacks to ensure safty...******************************
/****** Script for SelectTopNRows command from SSMS ******/
BEGIN transaction
UPDATE [BatNextGen].[dbo].[incentives_common]
SET consumer_legal = CAST(replace(CAST(consumer_legal as Nvarchar(MAX)), '1/5/15', '3/31/2015')
AS NText)
WHERE incentive_id = 1580
--check
SELECT *
FROM [BatNextGen].[dbo].[incentives_common]
WHERE description LIKE '%college%'
--decision
--COMMIT transaction
--ROLLBACK transaction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment