【问题标题】:Declare a table variable without column definitions?声明一个没有列定义的表变量?
【发布时间】:2011-05-07 23:03:05
【问题描述】:

在 SQL Server 中,有没有一种方法可以在不知道表定义的情况下声明表变量?

示例:

DECLARE @Results TABLE
INSERT INTO @Results EXEC MyProc @param1 = @myValue

DECLARE @Results TABLE
SELECT INTO @Results EXEC MyProc @param1 = @myValue

DECLARE @Results TABLE
EXEC MyProc @param1 = @myValue INTO @Results

DECLARE @Results TABLE
EXEC INTO @Results MyProc @param1 = @myValue

DECLARE @Results TABLE
SELECT * FROM EXEC MyProc @param1 = @myValue INTO @Results

DECLARE @Results TABLE
SELECT * INTO @Results FROM EXEC MyProc @param1 = @myValue

DECLARE @Results TABLE
SELECT * INTO @Results EXEC MyProc @param1 = @myValue

(你明白了)

【问题讨论】:

    标签: stored-procedures sql-server-2000


    【解决方案1】:

    不可能。来自“在线书籍”的引用:

    ==============

    语法 注意使用DECLARE @local_variable 来声明table 类型的变量。

    table_type_definition ::= 
      TABLE ( { column_definition | table_constraint } [ ,...n ] ) 
    

    ==============

    “(”,至少一个列定义和“)”在语法上是必需的。

    PS:AFAIK 根本不可能从“exec”结果插入任何新表。仅限于具有预定义结构的表。

    【讨论】:

      【解决方案2】:

      您无法使用表 VARIABLES 执行此操作,但您可以使用 TEMP 表执行此操作。

      -- Drop the table, if it exists
      IF OBJECT_ID(N'tempdb.dbo.#tmpMyTable',N'U') IS NOT NULL
      DROP TABLE #tmpMyTable
      
      
      SELECT
        ColumnA,
        ColumnB
      
      INTO #tmpMyTable
      
      FROM MyTable
      
      -- Then clean up after yourself
      DROP TABLE #tmpMyTable
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-31
        • 2011-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多