WHERE子句不接受刚定义的列

时间:2016-01-06 10:46:25

标签: sql sql-server sql-server-2008

本规范不起作用:

SELECT 
( 
    SELECT [T_Licence].[isInstalled]    
    FROM [T_Licence]    
    WHERE [T_Licence].[System]  = [T_System].[ID]   
    AND [T_Licence].[Software] = 750
) AS [IsInstalled] ,*
FROM [T_System]
WHERE [IsInstalled] = 1

我必须这样做,但这会使整个代码变得如此复杂。我真的不想要那个:

SELECT 
( 
    SELECT [T_Licence].[isInstalled]    
    FROM [wf_subj_all].[T_Licence]  
    WHERE [T_Licence].[System]  = [T_System].[ID]   
    AND [T_Licence].[Software] = 750
) AS [IsInstalled] ,*
FROM [wf_subj_it].[T_System]
WHERE 
(
    SELECT 
    ( 
        SELECT [T_Licence].[isInstalled]    
        FROM [wf_subj_all].[T_Licence]  
        WHERE [T_Licence].[System]  = [T_System].[ID]   
        AND [T_Licence].[Software] = 750
    )
) = 1

有没有办法像第一个代码段中所示那样做? 因此代码保持某种程度的可重复性。

非常感谢

3 个答案:

答案 0 :(得分:2)

试试这个 -

SELECT *
FROM wf_subj_it.T_System s
CROSS APPLY (
    SELECT /*TOP(1)*/ t.isInstalled   
    FROM wf_subj_all.T_Licence t
    WHERE t.[System]  = s.ID   
    AND t.Software = 750
) t
WHERE t.isInstalled = 1

答案 1 :(得分:2)

使用外部选择包装查询,它应该可以工作。

SELECT *
FROM
(
  SELECT 
  ( 
    SELECT [T_Licence].[isInstalled]    
    FROM [T_Licence]    
    WHERE [T_Licence].[System]  = [T_System].[ID]   
    AND [T_Licence].[Software] = 750
  ) AS [IsInstalled], *
  FROM [T_System]
) As tbl1
WHERE [IsInstalled] = 1

答案 2 :(得分:0)

我为答案做出的假设:

  • 您正在尝试选择安装了id = 750的软件的系统(表T_System)
  • 表T_License包含已安装的信息
  • T_System和T_License之间存在1:n关系:T_License可以包含每个Sytem值0个,1个或更多个记录...
  • 但组合系统和软件是唯一的

我认为这会起作用

SELECT l.[isInstalled], s.*
FROM   [wf_subj_it].[T_System] AS s
       INNER JOIN [wf_subj_it].[T_License] AS l
       ON  l.[System] = s.[ID]
       AND l.[Software] = 750
       AND l.isInstalled = 1