I am using SQL Server 2005. I have this stored procedure below but it doesn't work. It is for an archiving process I am currently implementing. The RiskArchive table has fields ArchiveID (primary key), RiskID, Criticality, MitigationActionID and ArchiveMonth (datetime data type). What I am trying to do is take the RiskID from the Risk table, the Criticality (a number showing how severe the risk is) for that risk and also any mitigations (MitigationActionID from the table Mitigation) for that risk. There can be many mitigations for each risk. In the Mitigation table, there is a RiskID field so that you can see which risk it belongs to.
First of all, I had this working at one stage. It was working before I put in the lines "if Risk.MitigationPlan = 'See action'", the "else" and the 3 lines of code after the else. But what I realised is that some risks might not have a mitigation when the stored procedure is run, so I implemented the if..else block that you see. The error that I get is:
Msg 4104, Level 16, State 1, Procedure usp_RiskArchive, Line 13
The multi-part identifier "Risk.MitigationPlan" could not be bound.
This error is on the if line, just before the insert into. Basically, when a mitigation has been entered for a risk, the MitigationPlan field for that risk is changed from None to See detail so that the user can see there are mitigations on that risk. So what I tried to do is when the MitigationPlan field for a risk is equal to See action, then insert the RiskID, Criticality and the MitigationActionID for that risk into the table RiskArchive, otherwise only insert the RiskID and Criticality (with the MitigationActionID field being left blank (null)). Note that this is what I want as I want a record of if there wasn't mitigations before, but are now, I can see when there wasn't any (by ArchiveMonth). The ArchiveMonth has a default value of getdate(). Here is the stored procedure:
Expand|Select|Wrap|Line Numbers
- USE [RiskAnalysis]
- GO
- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
- alter PROCEDURE [dbo].[usp_RiskArchive]
- AS
- SET NOCOUNT ON
- IF NOT EXISTS
- (SELECT RiskArchive.RiskID, RiskArchive.Criticality
- FROM RiskArchive, Risk
- WHERE RiskArchive.RiskID = Risk.RiskID AND RiskArchive.Criticality = Risk.Criticality)
- if Risk.MitigationPlan = 'See action'
- INSERT INTO RiskArchive (RiskID, Criticality, MitigationActionID)
- SELECT Risk.RiskID, case when Risk.Criticality <> '' then Risk.Criticality else '' end, Mitigation.MitigationActionID
- FROM Risk, Mitigation
- WHERE Mitigation.RiskID = Risk.RiskID
- else
- INSERT INTO RiskArchive (RiskID, Criticality)
- SELECT Risk.RiskID, case when Risk.Criticality <> '' then Risk.Criticality else '' end
- FROM Risk, Mitigation
- set nocount off
Andrew