sql 2005 case 语句 - 列名无效
Posted
技术标签:
【中文标题】sql 2005 case 语句 - 列名无效【英文标题】:sql 2005 case statement - Invalid Column Name 【发布时间】:2009-06-23 15:12:45 【问题描述】:谁能告诉我为什么会出错: 消息 207,级别 16,状态 1,过程 ExtractPDP4FromPDP,第 21 行 列名“ContainsEX”无效。
执行以下存储过程时。
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
提前谢谢你
【问题讨论】:
【参考方案1】:Sql Server 不允许您引用同一级别的字段。您必须创建一个子查询,例如:
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
【讨论】:
【参考方案2】:您不能在定义后立即在语句中使用列。
另一种方法是使用堆叠 CTE 来构建表达式或使用嵌套查询:
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
【讨论】:
【参考方案3】:您的案例陈述不正确。案例当“价值”=“价值”那么 '做类似 CONTAINEX = 'grandma' END
【讨论】:
以上是关于sql 2005 case 语句 - 列名无效的主要内容,如果未能解决你的问题,请参考以下文章
sql2005中的case when语句怎么用啊?请写出一个常见的例子