Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Returning all linked values in a self-linked table

Status
Not open for further replies.

glyph1

Programmer
Jun 15, 2007
26
0
0
Database: MSDE SQL Server 2000

Table Contract

ContractID PK*
ContractNumber
Status
NextContractID FK*

I am looking to select [ContractNumber] based on an input parameter and return all (non-null) of the linked [ContractNumber]s based on the [NextContractID] / [ContractID] relationship. I am trying to establish this in a single sql query.

I could not figure out a way to do this, any help would be greatly appreciated!
 
Try...

Code:
Select A.ContractNumber, B.ContractNumber As NextContractNumber
From   Contract As A
       Inner Join Contract As B
         On A.NextContractId = B.ContractId

It's hard to tell if this is what you're looking for. If it is, and you would like me to explain it, just let me know.


-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Just following up to my original post, I created a stored procedure using a while loop to achieve this.

Code:
CREATE Procedure get_contracts
	@ContractID int
AS 
BEGIN

DECLARE @NextID int
DECLARE @ContractTable TABLE -- Temporary Table
	(ContractID INT, NextContractID INT, ContractNumber varchar(20))

SET @NextID = @ContractID -- For first interation only

	-- Begin Insert Previous Into TempTable
	INSERT @ContractTable 

	SELECT ContractID, NextContractID, ContractNumber
	FROM Contract
	WHERE NextContractID = @ContractID
	-- End Insert Previous

	-- Begin Insert Next Into TempTable
	WHILE (@NextID IS NOT NULL) 
	BEGIN
		INSERT @ContractTable

		SELECT ContractID, NextContractID, ContractNumber
		FROM Contract
		WHERE ContractID = @NextID AND ContractID != @ContractID -- Omit parameter value

		SET @NextID = (Select NextContractID FROM Contract Where ContractID = @NextID)
	END;
	-- End Insert Next

END;

SELECT * From @ContractTable
 
if you were working with 2005, Recursive Common Table Expressions would give you what you want easily. Will you be upgrading soon? if so look at them.

Regards

Frederico Fonseca
SysSoft Integrated Ltd

FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top