tags:

views:

89

answers:

4

Hi,

i have a stored procedure that has to retrieve data from multiple tables

something like

SELECT [AppointmentId]
  ,[ContactId]
  ,[Date]
  ,[BookedBy]
  ,[Details]
  ,[Status]
  ,[Time]
  ,[Type]
  ,[JobId]
  ,[AppointmentFor]
  ,(Select PersonFirstName from Person where Person_Id = [AppointmentFor]) As UserFirstName
  ,(Select PersonLastName from Person where Person_Id = [AppointmentFor]) As UserLastName

  ,(Select PersonFirstName from Person where Person_Id = [ContactId]) As ContactFirstName      
  ,(Select PersonLastName from Person where Person_Id = [ContactId]) As ContactLastName           

 FROM [dbo].[Appointments]

my question is there is any other more efficient way to do this? Or is this the right approach?

I am working on a Sql server 2008 Thanks

A: 
CREATE PROCEDURE up_getData 
select personId,
       name,
       surname,
       street address,
       Postcode,
FROM Persons p
JOIN Address a on a.PersonId = p.personId
Andrey
A: 

Yes you should be using joins:

SELECT a.[AppointmentId]
  ,a.[ContactId]
  ,a.[Date]
  ,a.[BookedBy]
  ,a.[Details]
  ,a.[Status]
  ,a.[Time]
  ,a.[Type]
  ,a.[JobId]
  ,a.[AppointmentFor]
  ,p.PersonFirstName
  ,p.PersonLastName
  ,p2.PersonFirstName
  ,p2.PersonLastName 
FROM Appointments a
    JOIN Person p ON a.AppointmentFor = p.Person_Id
    JOIN Person p2 ON a.ContactId = p2.Person_Id
AdaTheDev
+5  A: 

If i understand correctly you will need to use two joins, so that you can match on [AppointmentFor] and [ContactId].

I have also aliased the table, which is a good habit to get into when joined across mutiple tables.

SELECT a.[AppointmentId] 
  ,a.[ContactId] 
  ,a.[Date] 
  ,a.[BookedBy] 
  ,a.[Details] 
  ,a.[Status] 
  ,a.[Time] 
  ,a.[Type] 
  ,a.[JobId] 
  ,a.[AppointmentFor] 
  ,p1.PersonFirstName As UserFirstName 
  ,p1.PersonLastName As UserLastName 
  ,p2.PersonFirstName As ContactFirstName       
  ,p2.PersonLastName  As ContactLastName            

 FROM [dbo].[Appointments] a

    INNER JOIN Person p1 ON p1.Person_Id = a.[AppointmentFor]

    INNER JOIN Person p2 ON p2.Person_Id = a.[ContactId]
kevchadders
+1, the `selected` answer yet no up vote, I don't like when that happens to me!
KM
thanks for the vote KM
kevchadders
you may want to read this article on Understanding SQL Joins:www.devshed.com/c/a/MySQL/Understanding-SQL-Joins/
Leslie
+3  A: 
SELECT [AppointmentId]
  ,[ContactId]
  ,[Date]
  ,[BookedBy]
  ,[Details]
  ,[Status]
  ,[Time]
  ,[Type]
  ,[JobId]
  ,[AppointmentFor]
  ,b.PersonFirstName UserFirstName
  ,b.PersonLasName UserLastName
  ,c.PersonFirstName ContactFirstName
  ,c.PersonLastName ContactLastName           
 FROM [dbo].[Appointments] a 
JOIN Person b on a.ApointmentFor = b.Person_Id
JOIN Person c on a.ContactId = c.ContactId
RJ1516