关键字'end'附近的语法不正确。 SQL

时间:2016-07-19 09:23:00

标签: sql sql-server sql-server-2008

ALTER procedure [dbo].[proc_PostVisitCountInsert](
@postCount bigint,
@postID bigint)
as
 Begin
  if not exists(select * from PostVisitCount where postID=@postID)
   Begin
    Insert into PostVisitCount(postcount,postID) values(@postCount, @postID)
   end   
  else
    Begin
     --Query for Update PostVisitCount
       Declare @count bigint
       Set @count=(select postcount from PostVisitCount where postID=@postID)
       Update PostVisitCount set postcount=(@count+1), postID=@postID
    End 
 end --Error getting at this place

当我尝试执行查询时,我收到这些查询的错误。我不明白这个查询有什么问题,任何人都可以帮我弄清楚我做错了什么。

4 个答案:

答案 0 :(得分:1)

ELSE的Begin End不包含任何语句(它实际上已被注释掉)。这就是错误的原因。以下将起作用

ALTER procedure [dbo].[proc_PostVisitCountInsert](
@postCount bigint,
@postID bigint)
as
 Begin
  if not exists(select * from PostVisitCount where postID=@postID)
   Begin
    Insert into PostVisitCount(postcount,postID) values(@postCount, @postID)
   end   
  else
    Begin
     Query for Update PostVisitCount
    End 
 end --Error getting at this place

答案 1 :(得分:0)

@ user6503334:我不确定我的帖子是否会解决您的问题,但您可以更改"否则"部分如下,因为我觉得你的更新声明中有一些逻辑上缺失的东西。我在else部分做了几处修改。您应该添加where子句,否则将更新所有行。

  var allcourse = db.Enrollments
        .Where(e => e.UserID == User.Identity.GetUserId())
        .Select(x => new CourseViewModel { 

    CourseID = e.Course_page.CourseID,
    ...
    ...

    Course_section = e.Course_page.course_sections.OrderBy(i => i.Order).FirstOrDefault
    ...
    ...
    ...
        });

答案 2 :(得分:0)

由于评论中给出了一个有效的答案而不是每个人都阅读这些答案,因此脚本应如下所示:

ALTER procedure [dbo].[proc_PostVisitCountInsert](
    @postCount bigint,
    @postID bigint
)
as
Begin
    if not exists (select * 
        from PostVisitCount 
        where postId = @postId)
    Begin
        insert into PostVisitCount(postcount,postID) values(@postCount, @postID)
    end        
    else
    Begin
        --Query for Update PostVisitCount
        update PostVisitCount set postcount = postcount + 1 where postID = @postID
    End 
end

答案 3 :(得分:-1)

可能这应该有用。

ALTER procedure [dbo].[proc_PostVisitCountInsert](
@postCount bigint,
@postID bigint)
as
 Begin
  if not exists(select * from PostVisitCount where postID=@postID)

    Insert into PostVisitCount(postcount,postID) values(@postCount, @postID)
  else

     --Query for Update PostVisitCount

 end --Error getting at this place