为什么子查询在我的查询中不返回任何结果,但在自行运行时却正常返回?

时间:2019-04-11 20:29:03

标签: sql

SELECT Part_Code 
INTO #Part_Codes
FROM v_items vi
WHERE Item_Class IN('ZFIN','AWORT')
AND Engineering_Status = 'A'
ORDER BY Division_Code, Desc_1

;WITH BOM AS (
    SELECT Parent_Part, Component_Part, Component_Part as Starting_Part, i.*
    FROM v_prod_structure v
    INNER JOIN v_items i on i.Item_Nbr = v.Parent_Part
    WHERE Component_Part IN(SELECT Part_Code + '|01' FROM #Part_Codes)
    AND Item_Class IN('FERM')

UNION ALL

    SELECT v.Parent_Part, v.Component_Part, BOM.Starting_Part, i.*
    FROM v_prod_structure v
    INNER JOIN BOM on BOM.Parent_Part = v.Component_Part
    INNER JOIN v_items i on i.Item_Nbr = v.Parent_Part
    WHERE i.Item_Class IN('STOR')
)
--SELECT Component_Part FROM BOM WHERE Item_Class = 'STOR' AND BOM.Starting_Part = '19125' + '|01'

SELECT Part_Code, Desc_1,Item_Class, Division_Code,
--Dilution
CASE Item_Class
    WHEN  'ZFIN' THEN
    (SELECT Qty_per_Assy 
    FROM v_prod_structure
    INNER JOIN v_items i on i.Item_Nbr = v_prod_structure.Component_Part
    WHERE Parent_Part = vi.Part_Code + '|01'
    AND Item_Class = 'STOR')
    ELSE 
    (SELECT Max_Ord
    FROM IPL
    WHERE Part_Nbr LIKE('%' + Part_Code + '%')) 
    END as Dilution,
NULL as 'Next Week',
--Fermentation
NULL as Fermentation,
--Storage
CASE Item_Class
    WHEN 'AWORT' 
    THEN (SELECT BOM.Component_Part FROM BOM WHERE vi.Item_Class = 'STOR' AND BOM.Starting_Part = vi.Part_Code + '|01')
ELSE NULL END as Storage
FROM v_items vi
WHERE Item_Class IN('ZFIN','AWORT')
AND Engineering_Status = 'A'
ORDER BY Division_Code, Desc_1

现在这段代码中我需要返回数据的部分,但每行总是返回null:

CASE Item_Class
WHEN 'AWORT'
THEN (SELECT BOM.Component_Part FROM BOM WHERE vi.Item_Class = 'STOR' AND BOM.Starting_Part = vi.Part_Code + '|01')
ELSE NULL END as Storage

我已经测试过case语句本身,它可以正确地区分项目是否为AWORT。临时表#Part_Codes也具有所有正确的数据。尝试SELECT BOM.Component_Part FROM BOM WHERE vi.Item_Class = 'STOR' AND BOM.Starting_Part = '19125' + '|01'手动用完“主要”查询后,它会得到我正确寻找的结果。

2 个答案:

答案 0 :(得分:1)

此查询不能单独运行-您没有从任何带有'vi'别名的表中进行选择。您是否要过滤BOM表Item_Class?

SELECT BOM.Component_Part FROM BOM WHERE vi.Item_Class = 'STOR' AND BOM.Starting_Part = '19125' + '|01'

似乎您混淆了别名,因为您的案子是矛盾的: CASE Item_Class WHEN 'AWORT' -- this is looking at vi's Item_Class THEN (SELECT BOM.Component_Part FROM BOM WHERE vi.Item_Class = 'STOR'-vi的Item_Class不能同时等于AWORT和STOR

答案 1 :(得分:0)

阅读答复后,我发现我只是在子查询的where子句中查看错误的表。我将vi.Item_Class更改为BOM.Item_Class