简体   繁体   中英

SQL join 1 table and 2 table-valued function returned tables

I have a database with a table, which I will call Table1. The database also has 2 table-valued functions. The first function returns a table which I will call Table2 and the second function returns a table which I will call Tabel3. There is also a 4th table, which I will call Table4, which I want to insert records into.

Table1 has the following fields:

Fileno
Description
GeneralCode

The first function takes in 2 parameters (Table1.Fileno, Table1.Description) and returns Table2, which has the following fields:

FileNum
Desc1
Desc2
Desc3

The second function takes in 2 parameters (Table1.Fileno, Table1.GeneralCode) and returns Table3, which has the following fields:

FileNum
Code1
Code2

The forth table, Table4, has the following fields:

CaseNum
Desc1
Desc2
Desc3
Code1
Code2    

I wrote the following query which works:

DELETE FROM Table4
INSERT INTO Table4(CaseNum, Desc1, Desc2, Desc3)
SELECT Fileno, Desc1, Desc2, Desc3
FROM Table1 
CROSS APPLY function1(FileNo, Description)

This query runs, calls the function (which returns a table), and inserts data into Table4.

Now, I need to modify the query to call a second function, which will return another table, and insert that data into Table4. I have the following code:

DELETE FROM Table4
INSERT INTO Table4(CaseNum, Desc1, Desc2, Desc3, Code1, Code2)
SELECT m.Fileno, d.Desc1, d.Desc2, d.Desc3, c.Code1, c.Code2
FROM Table1 m
INNER JOIN function1(m.Fileno, m.Description) d ON d.FileNum = m.Fileno
LEFT OUTER JOIN function2(m.Fileno, m.GeneralCode) c ON c.FileNum = m.Fileno;

But this code does not work. Intellisense highlights the fields that I am passing to the functions so obviously I can't reference these fields in this manner but I'm not sure how to resolve that.

Any help is greatly appreciated. Thanks!

Your query should probably look something like the following.

You can apply multiple table expressions or TVFs, you're showing an outer-join in your sample query so use outer apply where you might (presumably) not get a row returned, and then handle the NULLs, if necessary.

select m.Fileno, 
    f1.Desc1, f1.Desc2, f1.Desc3, 
    IsNull(f2.Code1,''), IsNull(f2.Code2,'')
from Table1 m
cross apply function1(m.FileNo, m.Description)f1
outer apply function2(m.FileNo, m.GeneralCode)f2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM