Assigning TABLE typed variables in T-SQL

109 views Asked by At

I've defined a user defined Table type - call it TrackRefsTable

Having declared two variables DECLARE @FOO1 AS TrackRefsTable DECLARE @FOO2 AS TrackRefsTable

Is there any way to set one to t'other? The obvious

SET @FOO2 = @FOO1

doesn't work as this assignment method only appears to work for Scalar variables and therefore you get the error Must declare the scalar variable "@FOO1"

I would hope to be able to avoid having to do INSERT statements to move data from one to the other as this can be an expensive operation.

DECLARE @FOO1 AS TrackRefsTable
DECLARE @FOO2 AS TrackRefsTable

-- INSERT INTO @FOO1 here

SET @FOO2 = @FOO1
1

There are 1 answers

0
AudioBubble On

So my issue was that the SP in which I implemented this would retrieve relatively unstructured data and then try to apply Sorting and Filtering on it. In order to squeeze maximum performance out of this we had to do things like sometimes populating a Table Variable @FOO1, but then sometimes apply Sorting or Filtering on it with results going into @FOO2 before joining it to an actual Data table to retrieve further column data. If performance wasn't such a big deal, I would have taken the simpler option to simply create a variable @FOOFinal into which all the data would be placed before implementing a single JOIN to get the remaining data. But INSERT INTO @FOOFinal SELECT * FROM @FOO1 (for example) costs precious milliseconds so that wasn't acceptable.

Ultimately, the solution was to simply create a separate SP in which we do the JOIN from such a Table Variable to the other data. Because the Table variable was defined as a Table Variable Type we could (thanks to the fact that we no longer support anything older than SQL Server 2008) use a Table Type as a parameter in the SP. So the solution then is to simply call that SP with either @FOO1 or @FOO2 as the parameter being passed in, and that obviates the need to assign one to the other.