Just got another query that I'm pulling what remaining hair I have left out over here.
I have 4 tables ( Product
, Customers
, Orders
and Order Details
) I need to create a valued table function that passes Country Name to the function. I also need the function to join my Customers
table with my Orders
table. I ideally want to filter Countries by Order Date. So I'd like to able to Select from the function that tells me orders from a certain country within a certain date range.
So far I've tried the following with not much success:
USE sample;
GO
CREATE FUNCTION Orders_By_Country (@Country VARCHAR(50))
RETURNS TABLE
AS RETURN (SELECT Customers.Country, Customers.CompanyName
FROM Customers
WHERE Customers.Country = Orders.ShipCountry
AND Country = @Country);
I don't have a Country
column in my Orders
table so maybe that is why it's not working. Not sure how to join these two. Orders
and Customers
share CustomerID
as a relation but trying that gave me an error as well.
Any ideas? I have to go to bed now, but I'll check back first thing in the morning.
Thanks
If you want to use the Orders
table to make decisions or if you want to return one or multiple columns from that table in your TVF, you need to join to it!
CREATE FUNCTION Orders_By_Country (@Country VARCHAR(50))
RETURNS TABLE
AS RETURN
(SELECT Customers.Country, Customers.CompanyName
FROM Customers
INNER JOIN Orders ON Orders.CustomerId = Customers.CustomerId
WHERE
Customers.Country = Orders.ShipCountry
AND Country = @Country);
or then you might not need it at all - seeing that you have a Country
column on the Customers
table:
CREATE FUNCTION Orders_By_Country (@Country VARCHAR(50))
RETURNS TABLE
AS RETURN
(SELECT Customers.Country, Customers.CompanyName
FROM Customers
WHERE
Customers.Country = @Country);
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.