Hi,
I'm trying to use CROSS APPLY
in SQL, but only want to use the results of the call if the returned row count is greater than 1.
I have the following SQL:
INSERT INTO @dest (val1, val2, val3)
SELECT t2.crossVal, t2.crossVal2, t1.tempVal
FROM @tempTable t1
CROSS APPLY dbo.TableValuedFunction(t1.IDColumn) t2
The CROSS APPLY
returns multiple rows in some cases, but in the vast majority returns one row (as all @tempTable
rows have a corresponding result from the function). I'm interesting in only inserting those that have multiple corresponding results from the CROSS APPLY
.
I'm trying to avoid inserting all then doing a delete afterwards. Really interested to see if there is any sort of aggregation action I can apply to that statement as it is.
Any ideas?
Edit: in response to SQLMenace's answer. I am getting the following results where the left column is tempVal, the middle column is crossVal, the right column is crossVal2:
a : 1 : z0
b : 1 : z0
a : 2 : z1
b : 2 : z1
c : 1 : z0
d : 1 : z0
I want to ditch the rows "c : 1 : z0" and "d : 1 : z0". Also, it may affect the groupings so I will mention this, my final query has two columns returned from the function and one from the temp table.
The end query is basically counting the parents of the tempTable row, where there is more than one parent (returned as a table from the function) I want to do the insert and record the order of the parent (again returned from the function). crossVal is the parent ID and crossVal2 is the order as an int.