tags:

views:

36

answers:

5

I have the following tables structure:

Shipment (has IDDestination as foreign key) -> Destination (has IDCity as foreign key) -> City (has IDCountry as foreign key).

I want to give my stored procedure a Country ID and have it return all of the shipments. How would I do this with pure SQL syntax? I could do this trivially with an ORM, but I'm forcing myself to learn this.

+1  A: 

You can use INNER JOINs to link all your tables together.

CREATE GetShipments

@CountryID int

AS

SELECT *
FROM Shipments
INNER JOIN Destination ON Shipment.IDDestination = Destination.ID
INNER JOIN Cities ON Destination.IDCity = Cities.ID
WHERE Cities.IDCountry = @CountryID
LittleBobbyTables
Great user name.
Serg
Thanks! Also, Tahbaza is right, you would want to SELECT Shipments.*, otherwise you'll get all the Destination and City information as well, which you may or may not need.
LittleBobbyTables
I must admit, I am jealous of your username ever time I see it
OMG Ponies
@OMG Ponies - And to think, I was about to register with my real name (sadly, not Bobby) when I had the stroke of insight. While we're at it, I'm jealous of your reputation and your lightning-quick response time.
LittleBobbyTables
OMG Ponies
A: 
SELECT s.*
FROM City c INNER JOIN (
  Shipment s INNER JOIN Destination d ON s.IDDestination = d.ID)
  ON c.ID = d.IDCity
WHERE c.IDCountry = @IDCountry
Tahbaza
I'm not an expert, but won't this select a list of Cities?
Serg
@Sergio: What?! Shipment s means "use s as an alias for the SHIPMENT table" why would a list of cities be returned??? As a matter of fact the other responses WITHOUT a prefix for the * will return a lot more fields that you probably aren't interested in...
Tahbaza
That's unusual formatting for ANSI-92 join syntax
OMG Ponies
A: 

Like this maybe...

select * from Shipment as s
inner join Destination as d on s.IDDestination = d.IDDestination
inner join City as c on d.IDCountry = c.IDCountry
where c.IDCountry = @CountryID
w4ik
A: 
SELECT S.* 
FROM Shipment S
JOIN Destination D on S.IDDestination  = D.ID
JOIN City C on D.IDCity = C.ID
WHERE IDCountry = @IDCountry
Jaimal Chohan
+2  A: 

For a visual demonstration of various JOINs, see this link.

Assuming @idcountry is an integer data type, use:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE get_shipments_for_countryid 
   @idcountry INT
AS
BEGIN

   SELECT DISTINCT 
          s.*
     FROM SHIPMENT s
     JOIN DESTINATION d ON d.id = s.iddestination
     JOIN CITY c ON c.id = d.idcity 
    WHERE c.idcountry = @idcountry
END
GO

Change the parameter data type, if not an INT, to whatever is appropriate.

The DISTINCT is necessary if any of the tables are many-to-many, or one-to-many...

OMG Ponies
SELECT sys.* ? Somebody's been working with system tables a lot lately :)
LittleBobbyTables
@LittleBobbyTables: Stupid SSMS 2008 intellisense, did it even though I selected my `example` database...
OMG Ponies