【问题标题】:SQL Server, Error 102, when using CURSOR, creating a dynamic tableSQL Server,错误 102,使用 CURSOR 时,创建动态表
【发布时间】:2013-02-13 10:43:56
【问题描述】:

在使用 CURSOR 创建临时表时出现以下错误:

(1 row(s) affected)
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '?'.
Msg 208, Level 16, State 0, Line 33
Invalid object name '##TEMP_Branch'.

没有 CURSOR 一切正常。 完整代码如下:

declare  @TableSchema table
(
    Id  Int Identity(1,1),
    Name    nVarchar(50),
    DataType    nVarchar(50)
)

declare @reportid uniqueidentifier
set @reportid = '597d37c0-563b-42f0-99be-a15000dc7a65'
declare @ttl nvarchar(100)
declare cur CURSOR LOCAL for
    SELECT    title
    FROM            ReportItems
    where reportid = @reportid
    and del = 0 
    ORder by so
open cur
    fetch next from cur into @ttl
    while @@FETCH_STATUS = 0 BEGIN
        INsert @TableSchema Values(@ttl,'nVarchar(max) NULL')
    fetch next from cur into @ttl
    end
close cur
deallocate cur

Declare @Statement  Varchar(1000)
Select @Statement  = 'Create Table [##TEMP_Branch](FieldID Varchar(50)'
Select @Statement = COALESCE(@Statement +',','') + Name + ' ' + DataType from @TableSchema
Select @Statement = @Statement + ')'
EXEC(@Statement)


Select * from ##TEMP_Branch
drop table ##TEMP_Branch

非常感谢任何帮助。

【问题讨论】:

  • 可能是动态查询出了点问题。你能不能先PRINT它而不是执行它,看看发生了什么?

标签: tsql dynamic cursor temp


【解决方案1】:

使用表变量

    Declare @TEMP_Branch TABLE
    (
       FieldID varchar(50)
    )

它像普通表一样工作,没有关系,不必删除,对于较大的数据处理,制作一个永久表来临时存储数据并删除或截断它之后

【讨论】:

    【解决方案2】:

    您可能在 ReportItems 表中有一个标题,其中包含空格或其他错误字符(问号)。

    第一个错误看起来像是来自EXEC(@Statement),因为表定义无效。

    Msg 102, Level 15, State 1, Line 1
    Incorrect syntax near '?'.
    

    第二个错误可能是 Select * from ##TEMP_Branch 正在针对不存在的临时表执行:

    Msg 208, Level 16, State 0, Line 33
    Invalid object name '##TEMP_Branch'.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 2013-05-13
      • 2011-04-26
      相关资源
      最近更新 更多