views:

350

answers:

3

Can someone tell me why I get error: Msg 207, Level 16, State 1, Procedure ExtractPDP4FromPDP, Line 21 Invalid column name 'ContainsEX'.

when executing the following stored procedure.

CREATE PROCEDURE ExtractPDP4FromPDP 
    -- Add the parameters for the stored procedure here
AS
BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
SELECT PDP.*, LEFT(PDPCode,7) AS PDP7, PDP.Obsolete, 
        PDP.InvestorPDP, PDP.OnlineReport, PDP.ClientSpecific, 
        ContainsEX = CASE 
 WHEN(CHARINDEX(Left(PDPCode,5),'EX')>0) THEN 'True'
 ELSE 'False'
END, PDP4 =
CASE 
 WHEN ContainsEX = 'True' THEN 'E' & SUBSTRING(pdpcode,5,3)
 ELSE SUBSTRING(pdpcode,6,3)
END
FROM PDP
WHERE (((PDP.Obsolete)='False') AND ((PDP.InvestorPDP)='True') AND 
    ((PDP.OnlineReport)='False') AND ((PDP.ClientSpecific)='False'));  
END
GO

Thank You in advance

+1  A: 

You cannot use a column in a statement immediately after defining it.

One alternative is to use stacked CTEs to build up your expressions or use nested queries:

WITH cte1 AS (
    SELECT x, x AS y
    FROM t
),cte2 AS (
    SELECT x, y, x + y AS z
    FROM cte1
)
SELECT x, y, z
FROM cte2
Cade Roux
+7  A: 

Sql Server does not allow you to refer to fields on the same level. You'd have to create a subquery, like:

select *,
    PDP4 = CASE 
        WHEN ContainsEX = 'True' THEN 'E' & SUBSTRING(pdpcode,5,3)
        ELSE SUBSTRING(pdpcode,6,3)
    END
from (
    select *, LEFT(PDPCode,7) AS PDP7, PDP.Obsolete, 
        PDP.InvestorPDP, PDP.OnlineReport, PDP.ClientSpecific, 
        ContainsEX = CASE 
            WHEN(CHARINDEX(Left(PDPCode,5),'EX')>0) THEN 'True'
            ELSE 'False'
        END
    from PDP
    WHERE (((PDP.Obsolete)='False') AND ((PDP.InvestorPDP)='True') AND 
   ((PDP.OnlineReport)='False') AND ((PDP.ClientSpecific)='False'))
) sub
Andomar
A: 

Your case statement is not correct. CASE WHEN 'value' = 'value' THEN 'do something like CONTAINEX = 'grandma' END