I've got a table-valued type as a parameter to a stored procedure, with anything up to thousands of rows in it. I perform several operations on this stored procedure (currently a MERGE and an INSERT), but before those I want to filter the contents of the parameter on a predicate:
@data TableValuedType READONLY
MERGE INTO Table2
USING (
SELECT ... FROM @data
UNION
SELECT ... FROM @data
UNION
...)
ON ...
WHEN NOT MATCHED THEN ....
INSERT INTO Table3
SELECT ... FROM @data
Is the most efficient way to do this to declare another variable of the table type, insert into that, then use that variable to merge and insert from:
DECLARE @sanitisedData TableValuedType
INSERT INTO @sanitisedData
SELECT ... FROM @data
WHERE <predicate>
or to use the predicate every time I select something from @data:
MERGE INTO Table2
USING (
SELECT ... FROM @data WHERE <predicate>
UNION
SELECT ... FROM @data WHERE <predicate>
UNION
...)
ON ...
WHEN NOT MATCHED THEN ....
INSERT INTO Table3
SELECT ... FROM @data WHERE <predicate>
or something else?