消息203,级别16,状态2,不是有效的标识符

4 sql t-sql sql-server error-handling sql-server-2008

我收到以下错误:

消息203,级别16,状态2,过程getQuestion,第18行
名称'select top(1)*from tlb_Question inner join tlb_options on tlb_options.qID = tlb_Question.id and tlb_Question.qNumber = 1 and tlb_Question.id not in(0 ,1)'不是有效的标识符

从以下存储过程:

ALTER proc getQuestion
    @qNo bigint,
    @total bigint,
    @next nvarchar(max)
as
begin 
    declare @hisa bigint
    set @hisa=@total/3

    if(@qNo<=@total/3)
    begin
    declare @query nvarchar(max)
    set @query=('select top(1) * from tlb_Question 
        inner join tlb_options on tlb_options.qID=tlb_Question.id and tlb_Question.qNumber=1 and tlb_Question.id not in ('+cast(@next as varchar)+')')
    print @query
    execute @query
    end
end
Run Code Online (Sandbox Code Playgroud)

Tec*_*hDo 17

请尝试这个,更改执行@query执行(@query):

ALTER proc getQuestion
    @qNo bigint,
    @total bigint,
    @next nvarchar(max)
as

begin 
    declare @hisa bigint
    set @hisa=@total/3

    if(@qNo<=@total/3)
    begin
      declare @query nvarchar(max)
      set @query=('select top(1) * from tlb_Question 
      inner join tlb_options on tlb_options.qID=tlb_Question.id and tlb_Question.qNumber=1 and tlb_Question.id not in ('+cast(@next as varchar)+')')
      --print @query
      execute (@query)
    end
end
Run Code Online (Sandbox Code Playgroud)

  • 为什么我们需要写 ``exec(@query)`` 为什么 ``exec @query`` 不起作用 (2认同)