SQL 存储过程 - table 作为参数

SQL stored procedure - table as parameter

我有一个具有不同 table 的数据库(全部相同的结构),我想在其中 运行 一个存储过程,该存储过程的参数定义要查询的 table .

我好像想不通:

CREATE SCHEMA test;
GO

首先我创建了一个模式

CREATE TYPE DataType as TABLE (
    [datetime] [datetime] NULL,
    [testVar] [bigint] NULL)
   GO

然后我创建了 table 类型

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] > @datetime                

END
GO

然后我创建了存储过程。

Exec test.testing @t = 'table.1', @datetime = '2017-01-01'

但是当我调用它时出现以下错误:

Msg 206, Level 16, State 2, Procedure test, Line 0 [Batch Start Line 0] Operand type clash: varchar is incompatible with DataType

同样发生在:

Exec test.testing @t = [table.1], @datetime = '2017-01-01'

我看过一个例子,在 beginselect 之间的过程中,你放了类似的东西:

INSERT INTO table.1
( datetime, testVar)

但是 table.1(或 table.2 等,因为我有 table 的列表)有数据,我不想更改它。

除非我打算像创建 TYPE 那样创建一个虚拟对象 table?

我在网上找到的例子没有用。

您必须传递 DataType 类型的参数。因此,创建该类型的变量并将其传递给存储过程,如

declare @table1 DataType
INSERT INTO @table1(datetime, testVar) values (..., ...)
Exec test.testing @datetime = '2017-01-01', @t = @table1

为此,您需要使用动态 SQL

基本过程是建立一个字符串来保存您要执行的语句,然后执行它

declare @SQL nvarchar(1000)
declare @t as nvarchar (1000)
set @t = 'MyTable'
set @Sql = 'Select * from ' + @t
exec sp_executesql @sql