use [EnVisage]
/*
Run this script on SQL Server 2008 or later. There may be flaws if running on earlier versions of SQL Server.
*/
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_DeleteProject]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_DeleteProject]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE [dbo].[sp_DeleteProject] (@id uniqueidentifier) AS
	BEGIN
	
		BEGIN TRANSACTION

		select Id into #scenarioId2Delete from Scenario where Scenario.ParentId = @id
		delete from dbo.TeamAllocation where ScenarioId in (select id from #scenarioId2Delete)
		delete from dbo.Team2Scenario where ScenarioId in (select id from #scenarioId2Delete)
		delete from History where EntityId in (select id from #scenarioId2Delete)
		delete from Note where ParentId in (select id from #scenarioId2Delete)
		delete from Rate where ParentId in (select id from #scenarioId2Delete)
		delete from ScenarioDetail where ScenarioDetail.ParentID in (select id from #scenarioId2Delete)
		delete from Scenario_Snapshot where ParentID in (select id from #scenarioId2Delete)
		delete from Scenario_Wide where ScenarioId in (select id from #scenarioId2Delete)
		delete from ScenarioAccess where ScenarioAccess.ParentId in (select id from #scenarioId2Delete)
		delete from Scenario where id in (select id from #scenarioId2Delete)
		delete from Team2Project where ProjectId =@Id
		delete from Contact2Project where ShowId =@Id
		delete from ProjectAccess where ProjectId =@Id
		delete from Project where id = @id
		
		COMMIT TRANSACTION 

 	END
GO
