Question

Is it possible to return or output a @tableVariable in SQL Server?
For example for the following stored procedure, how do I return the @TSV table variable?

ALTER PROCEDURE MyStoredProdecure
    @Parameter1 INT,
    @Parameter2 INT
AS
   BEGIN

   DECLARE @TSV TABLE
   (
      Transition_Set_Variable_ID INT,
      Passed BIT
   )

   INSERT INTO @TSV
   { some data }

END
Was it helpful?

Solution

You cannot do it directly. Table variables are valid for READONLY input.

If you have no other data being returned from the stored procedure, you can select from the @TSV at the end and have the caller capture the output, e.g.

ALTER PROCEDURE MyStoredProdecure
    @Parameter1 INT,
    @Parameter2 INT
AS
   BEGIN

   DECLARE @TSV TABLE
   (
      Transition_Set_Variable_ID INT,
      Passed BIT
   )

   INSERT INTO @TSV
   { some data }

   SELECT * FROM @TSV
END

Caller

DECLARE @outerTSV TABLE
(
   Transition_Set_Variable_ID INT,
   Passed BIT
);
insert into @outerTSV
exec MyStoredProdecure 1, 2;

Alternatively, if the SP is really as simple as you showed, turn it into a table valued function instead.

OTHER TIPS

No, but you can write a table valued function that returns a table.

create function MyTVF
    @Parameter1 INT,
    @Parameter2 INT
returns @tsv table
   (
      Transition_Set_Variable_ID INT,
      Passed BIT
   )

AS
   BEGIN
   INSERT INTO @TSV
   { some data }
   return 
END

Table Valued Parameters can only be used for input only, not output.

Depending on what your end goal is, here are some options:

  1. change the sproc to a table-valued function to return a TABLE, that can then be used inline in another statement

  2. simply SELECT the data from the @TSV table var at the end of your sproc

  3. return an XML OUTPUT parameter (get a grubby feeling suggesting this, but just to highlight one way to return multiple rows actually using an OUTPUT parameter)

If you go for a Table Valued Function, ideally create an inline one if it is simple as it looks in your case:

e.g.

CREATE FUNCTION dbo.Func() 
RETURNS TABLE 
AS
RETURN
(
    SELECT Something
    FROM Somewhere
    WHERE x = 1
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top