title: SQL stored procedure - table as parameter
body: <p>I have a database with different tables (all the same structure) where I'd like to run a stored procedure having a parameter that defines which table to query.</p>
  
  <p>I can't seem to figure it out:</p>
  
  <pre><code>CREATE SCHEMA test;
  GO
  </code></pre>
  
  <p>First I created a schema</p>
  
  <pre><code>CREATE TYPE DataType as TABLE (
      [datetime] [datetime] NULL,
      [testVar] [bigint] NULL)
     GO
  </code></pre>
  
  <p>Then I created the table type</p>
  
  <pre><code>USE [TestDataFiles]
  GO
  
  SET ANSI_NULLS ON
  GO
  
  SET QUOTED_IDENTIFIER ON
  GO
  
  
  CREATE PROCEDURE [test].[testing]
  (
      -- Add the parameters for the stored procedure here
      @datetime datetime,
      @t DataType READONLY
  
  )
  AS
  BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON
  
  
  select top(10) * 
  from @t
  where [datetime] &gt; @datetime                
  
  END
  GO
  </code></pre>
  
  <p>Then I created the stored procedure.</p>
  
  <pre><code>Exec test.testing @t = 'table.1', @datetime = '2017-01-01'
  </code></pre>
  
  <p>However when I call it I get the following error:</p>
  
  <blockquote>
    <p>Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0]
    Operand type clash: varchar is incompatible with DataType</p>
  </blockquote>
  
  <p>Same happens with:</p>
  
  <pre><code>Exec test.testing @t = [table.1], @datetime = '2017-01-01'
  </code></pre>
  
  <p>I have seen an example where in the procedure between the <code>begin</code> and <code>select</code> you put something like:</p>
  
  <pre><code>INSERT INTO table.1
  ( datetime, testVar)
  </code></pre>
  
  <p>But table.1 (or table.2 etc as I have a list of tables) has data and I don't want to change it.</p>
  
  <p>Unless I'm meant to create a dummy table like I did the TYPE?</p>
  
  <p>The examples I've found online havent been useful. </p>