SQL 服务器 Select 来自 If Exists 的多个字段

SQL SERVER Select multiple fields from If Exists

我必须做一个 SQL Server Statement,它必须 return 一个空行,当它为空时,其他数据。

我正在尝试从(如果存在)执行 Select 但在父级 table 上有错误。

我简化一下。但意思是,当条件为空时检索几个字段,当条件不为空时检索其他字段。

当我不在另一个 select 中关闭它时,它工作正常。...我需要将它作为 table 检索以与其他 clouse 进行内部连接。

我该如何解决?

这是我的代码..

select * from
 (
       if exists(select isnull(SECTOR_ID_DESTINO_BAD,-1) 
   from workflow_Compras_detalle w
   where w.id=2)
   begin  
       select null as Sector,null as sector_id_origen
   end
   else
   begin
    select top 1 isnull(ws.sector,'') sector,  wd.sector_id_origen
    from workflow_Compras_detalle wd 
    where orden < 10
       end 
 )Table

你应该尝试将数据插入临时 table 或 Table 变量,然后从 table 中获取数据,这里有一个 [=15= 的例子] 变量,如果你需要更持久的东西,你可以使用#Temp Table,我建议你看看这个:difference between var table and #Temp Table

    DECLARE @VAR_TABLE AS TABLE(
Sector varchar(25),
sector_id_origen int
)

if exists(select isnull(SECTOR_ID_DESTINO_BAD,-1) 
            from workflow_Compras_detalle w
            where w.id=2)
    begin       
                INSERT INTO @VAR_TABLE
                Select null as Sector,null as sector_id_origen 
    End
Else
    begin

        INSERT INTO @VAR_TABLE
        select top 1 isnull(ws.sector,'') sector,  wd.sector_id_origen
        from workflow_Compras_detalle wd 
        where orden <   10
End 

SELECT * FROM @VAR_TABLE