Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 Database Design and Application Architecture
 Double Foreign key to the same table

Author  Topic 

GnR_Slash
Starting Member

14 Posts

Posted - 2010-02-25 : 10:48:09
Hi,

Is it possible to do this?



I need to create two links from tblProjetos to tblClientes, one for (CodigoCliente and LojaCliente) and another to (CodigoClienteFinal and LojaClienteFinal).

Sorry because the tables is in Portuguese, but:

Codigo means Code
Loja means Store

CodigoCliente means CustomerCode
LojaCliente means CustomerStore

CodigoClienteFinal means FinalCustomerCode
LojaClienteFinal means FinalCustomerStore

If this is not possible, so i need to update tblProjetos every time my user changes Codigo or Loja from tblClientes
Thanks!

Kristen
Test

22859 Posts

Posted - 2010-02-25 : 11:33:43
You can create the Foreign Key, but I don't think you will be able to cascade changes to Codigo / Loja to both locations in tblProjetos.

An alternative would be to store tblClientes.ID in tblProjetos (i.e. store the ID instead of the Codigo+Loja) - so called "surrogate-key" - and then you can change Codigo+Loja in tblClientes as often as you like - anything that wants to display it will link from tblProjetos using the ID.

You can create a VIEW to make it easier to get the related data from tblClientes


So instead of CodigoCliente + LojaCliente you have ClienteID, and instead of ClienteFinal + LojaClienteFinal you have ClienteFinalID.

For example:

CREATE VIEW V_Projetos
AS
SELECT ID AS V_ID,
C1.Codigo AS CodigoCliente,
C1.Loja AS LojaCliente,
C2.Codigo AS ClienteFinal,
C2.Loja AS LojaClienteFinal
FROM tblProjetos AS P
LEFT OUTER JOIN tblClientes AS C1
ON C1.ID = P.ClienteID
LEFT OUTER JOIN tblClientes AS C2
ON C2.ID = P.ClienteFinalID

and then when you use tblProjetos you must JOIN to the View too - the column names will be the same as you already have (so no change to WHERE or SELECT)

SELECT ID, Projecto, CodigoCliente, LojaCliente, CodigoClienteFinal, LojaClienteFinal, ...
FROM tblProjetos AS P
JOIN VProjetos AS V
ON V.V_ID = P.ID

Go to Top of Page

GnR_Slash
Starting Member

14 Posts

Posted - 2010-02-25 : 12:37:38
quote:
Originally posted by Kristen




Yes, you are right.
I will use ID field instead of two fields.
I was using tow fields (Codigo + Loja), because of the Projects was imported from another database that i can't access directly (just from Excel spreadsheat). But i will no longer use this spreadsheet.

Anyways, thank you so much for your reply, it was a good explanation and help me to see another way to do what i need.

tks!
Go to Top of Page
   

- Advertisement -