没有为第1列指定cte3的列

时间:2014-08-05 12:45:03

标签: tsql

我收到此错误消息

declare @i as int 
declare @CategoryList varchar(1000);
set @i=294;
with 
cte1 as (
    select * from Project where Id=@i
),
cte2 as (
    select dbo.CableProperty.* 
      from CableProperty 
     inner join cte1 on dbo.CableProperty.ProjectId = cte1.Id
), 
cte3 as (
    select @CategoryList = coalesce(@CategoryList + ', ', '') + FromBay 
      from cable 
     inner join cte2 on dbo.cable.CablePropertyId = cte2.Id
    select @CategoryList
)
select * from cte3

上面的代码是我想要做的非常简单。但这个概念是这样的。 为什么我得到那个错误? 谢谢

2 个答案:

答案 0 :(得分:1)

我认为CTE中不可能有两个独立的SELECT语句(存在于CTE3中)。并且您将只从CTE3 [AliasName]获得一列,因此我想我们不必指定SELECT @CategoryList。

DECLARE @i AS INT
DECLARE @CategoryList VARCHAR(1000);
SET @i = 294;

;WITH CTE AS (
    SELECT * FROM Project WHERE ID = @i 
)
,CTE2 AS (
    SELECT * FROM CableProperty INNER JOIN CTE1 ON ProjectID = CTE1.ID
)
,CTE3 AS (
    SELECT COALESCE(@CategoryList + ', ','') + FromBay [AliasName] FROM Cable
    INNER JOIN CTE2 ON CablePropertyID = CTE2.ID    
)
SELECT * FROM CTE3

试试这个。希望它有所帮助。

答案 1 :(得分:0)

declare @i as int 
declare @CategoryList varchar(1000);
set @i=294;

select @CategoryList = coalesce(@CategoryList + ', ', '') + FromBay 
  from cable 
  join CableProperty 
    on cable.CablePropertyId = CableProperty.Id
  join Project 
    on CableProperty.ProjectId = Project.Id
   and Project.Id = @i
select @CategoryList

什么表有FromBay?