title: SQL user defined function, with table variables as input & return value
body: <p>I have a user defined table-valued function that has an input type of a table variable, and the return type is another table variable.</p>
  
  <p>However, when I try to execute the function it throws the error "Must declare the scalar variable". It looks like the call to the function does not have knowledge of the table variable @myTable, even though it is declared on the previous line.</p>
  
  <p>I think I'm going crazy... can you spot what I am doing wrong?</p>
  
  <pre><code>-- Create the table type
  CREATE TYPE [dbo].[TableType] AS TABLE(
      [z] [varchar](50) NULL
  )
  GO
  
  
  -- Create the user defined function
  USE [databaseName]
  GO
  SET ANSI_NULLS ON
  GO
  SET QUOTED_IDENTIFIER ON
  GO
  ALTER FUNCTION [dbo].[boxPackingSort3](@TableName TableType READONLY)
  RETURNS @ReturnTable TABLE(
      [partno] [varchar](50) NULL,
      [Q] [int] NULL,
      [L] [int] NULL,
      [W] [int] NULL,
      [H] [int] NULL,
      [Id] [int] NULL
  )
  AS
  BEGIN
      INSERT INTO @ReturnTable SELECT 'xxx', '1' , '1', '1', '1', '1' 
      RETURN
  END
  
  
  -- Call the user defined function
  DECLARE @myTable TableType
  INSERT INTO @myTable(z) VALUES('aaa')
  select * from  dbo.[boxPackingSort3](@myTable)
  
  
  
  Msg 137, Level 16, State 1, Line 5
  Must declare the scalar variable "@myTable".
  </code></pre>