SQL Server Use Exists with a Column of Query Result?

jjjwad0x  于 2023-02-18  发布在  其他
关注(0)|答案(2)|浏览(157)

I have 2 tables.
One is bom_master:
| CHILD | PARENT |
| ------------ | ------------ |
| 1-111 | 66-6666 |
| 2-222 | 77-7777 |
| 2-222 | 88-8888 |
| 3-333 | 99-9999 |

Another one is library:

FileNameLocation
66-6666_A.stepS:\ABC
77-7777_C~K1.stepS:\DEF

And I want to find out if the child's parents have related files in the library.
Expected Result:

CHILDPARENTFileName
1-11166-666666-6666_A.step
2-22277-777777-7777_C~K1.step

Tried below lines but return no results. Any comments? Thank you.

WITH temp_parent_PN(parentPN)
AS
(
    SELECT 
    [PARENT]
    FROM [bom_master]
    where [bom_master].[CHILD] in ('1-111','2-222')
)
SELECT s.[filename]
FROM [library] s
WHERE EXISTS 
(
    SELECT 
    *
    FROM temp_parent_PN b
    where s.[filename] LIKE '%'+b.[parentPN]+'%'
)
wgxvkvu9

wgxvkvu91#

If you have just one level of dependencies use the join solution proposed by dimis164.

If you have deeper levels you could use recursive queries allowed by WITH clause ( ref. WITH common_table_expression (Transact-SQL) ).

This is a sample with one more level of relation in bom_master (you could then join the result of the recursive query with library as you need).

DECLARE @bom_master TABLE (Child NVARCHAR(MAX), Parent NVARCHAR(MAX));

INSERT INTO @bom_master VALUES
    ('1-111', '66-666'),
    ('2-222', '77-777'),
    ('3-333', '88-888'),
    ('4-444', '99-999'),
    ('A-AAA', '1-111');

WITH 
    leaf AS ( -- Get the leaf elements (elements without a child)
        SELECT Child FROM @bom_master b1
        WHERE NOT EXISTS (SELECT * FROM @bom_master b2 WHERE b2.Parent = b1.Child) ),
    rec(Child, Parent, Level) AS (
        SELECT b.Child, b.Parent, Level = 1 
        FROM @bom_master b
        JOIN leaf l ON l.Child = b.Child
        UNION ALL
        SELECT rec.Child, b.Parent, Level = rec.Level + 1
        FROM rec
        JOIN @bom_master b
        ON b.Child = rec.Parent )
SELECT * FROM rec
wpcxdonn

wpcxdonn2#

I think you don't have to use exists. The problem is that you need to substring to match the join. Have a look at this:

SELECT b.CHILD, b.PARENT, l.[FileName] 
FROM [bom_master] b 
INNER JOIN [library] l ON b.PARENT  = SUBSTRING(l.FileName,1,7)

相关问题