I am not able to figure out why a tvf does not work within a USP.
My TVF looks something like this & it is defined
SELECT
[id]
, [field1]
, [field2]
FROM [mydb].[dbo].[tvf_dataset_search]()
And the definition of the TVF is something like this.
SELECT
[id]
, [field1]
, [field2]
FROM [mydb].[dbo].[sometable]
The USP to update a dataset looks like this
EXEC [mydb].[dbo].[usp_dataset_update] @id, @field1, @field2
And is defined something like this:
UPDATE [mydb].[dbo].[sometable]
SET field1 = @field1
, field2 = @field2
WHERE id = @id
...
Here is the problem. When I add this to the USP, it works.
SELECT * FROM [mydb].[dbo].[sometable]
WHERE ID = SCOPE_IDENTITY()
But when I add this, it doesn't work the first time, but does work each additional time.
SELECT
[id]
, [field1]
, [field2]
FROM [mydb].[dbo].[tvf_dataset_search]()
WHERE ID = SCOPE_IDENTITY()
At the moment I have two copies of the TVF query (which is much more complicated than the snippet above). So long as the raw SQL is in the USP, it will work. But the moment I nest the TVF into the USP it stops working.
I have checked the filters & the ID is returned. In fact, the same TVF when called outside of the USP always works.
I've tried adding option (recompile)
. I've also tried adding the SCOPE_IDENTITY
to a temporary table to assure it exists before the query is called. The data is there, but the TVF does not return it.
Any thoughts?
EDIT - To clarify, when I say have to copies, I mean that after the update is made, I have to have all of the raw SQL for the select statement again (below) instead of calling the TVF. Also it's worth clarifying that this is a simplified example. There are multiple tables with many columns & the headers are renamed in specific ways.
UPDATE [mydb].[dbo].[sometable]
SET field1 = @field1
, field2 = @field2
WHERE id = @id
;
SELECT
[id]
, [field1]
, [field2]
FROM [mydb].[dbo].[tvf_dataset_search]()
WHERE ID = SCOPE_IDENTITY()