views:

26

answers:

2

I want to use a table valued function and call it from within multiple stored procedures rather than repeat the same query across all the stored procedures, but for compatibility with a legacy VB6/UltraGrid app I need to preserve the foreign key references from the original tables.

Within the table valued function I can specify a PRIMARY KEY, but is there a way to specify a 'FOREIGN KEY'? I tried to modify the return table like this, but I get a syntax error:

ALTER TABLE @ReturnTable  
WITH CHECK ADD  CONSTRAINT [FK_ReturnTable_OtherTable]
FOREIGN KEY([OtherTableID])
REFERENCES [dbo].[OtherTable] ([OtherTableID])
+2  A: 

no you can't. the function returns a "virtual" table that exists only at run time and there is no way to FK to such a imaginary/transient set of rows. Without knowing your schema and exactly what you are trying to accomplish, my best guess it to try to use a trigger to enforce this.

KM
Thanks, I suspected as much but I'm by no means an expert. At the moment I'm joining back to the original table in the stored procedures to pull the FK columns out, but that sort of defeats the purpose.
robertc
I would recommend just using the regular tables and joins in each stored procedure. Using this function may confuse the optimizer and result in bad execution plans and slow performing queries. The goal with sql is to have fast index using queries. many people fall into the trap of trying to make the SQL code "slick" by attempting remove duplication and other typical application code inefficiencies. This can result in very ineffective SQL performance. I've seen very subtle SQL code changes that result in massive performance degradation.
KM
+1  A: 

Will your legacy grid see the FK relationships through a view? Or is the query unable to be stored as a view?

JamWheel
I think that's worth a go, I'll see if it works.
robertc