0

我有两张桌子:

1) 博文:

 COLUMN_NAME    DATA_TYPE
Id                  int
Title             varchar
Description       varchar
ImageName         varchar
FileName          varchar
CreatedDate       datetime
Tags              varchar
ModifiedDate      datetime
RateNumber           int
CreatedBy            int
ShortDescription    varchar

2. 博客评分:

Id  EmployeeId  PostId  Rate
4     1           12    3
5     1           13    2
6     1           11    2

我写了一个存储过程来保存 BlogRating 的详细信息:

ALTER PROCEDURE [dbo].[BlogRatingSave]
     @EmployeeId    int
    ,@PostId        int
    ,@Rate          int
AS
BEGIN
    DELETE FROM [HRM_BlogRating]
        WHERE   [HRM_BlogRating].[EmployeeId] = @EmployeeId 
            AND [HRM_BlogRating].[PostId] = @PostId 

    INSERT INTO [HRM_BlogRating]
        ([EmployeeId]
        ,[PostId]
        ,[Rate]
        )
    VALUES
        (@EmployeeId    
        ,@PostId        
        ,@Rate
        )
END

我想要的是,如果不同的员工给出率,在保存 BlogRating 时,我需要将 table1 中的字段 RateNumber 自动增加 1。同时,如果下一次相同的员工率,RateNumber 不应该增加。请帮我解决这个问题。

4

2 回答 2

0

你为什么要删除然后插入。相反,您应该尝试插入,如果它失败(由于重复)然后进行更新。

在此过程中,您还可以调整评级的值,但我假设您需要传入进行更改的人员的 EmployeeId,因为这是您的规则的一部分。IE。

update BlogPost set RateNumber = RateNumber + 1 where EmployeeId = @EmployeeID and CreatedBy != @EmployeeID

所以一切都会变成:

ALTER PROCEDURE [dbo].[BlogRatingSave]
     @EmployeeId    int
    ,@PostId        int
    ,@Rate          int
AS
BEGIN
    BEGIN TRY
        INSERT INTO [HRM_BlogRating]
            ([EmployeeId]
            ,[PostId]
            ,[Rate]
            )
        VALUES
            (@EmployeeId    
            ,@PostId        
            ,@Rate
            )
    END TRY
    BEGIN CATCH
        UPDATE [HRM_BlogRating]
             SET Rate = @Rate
        WHERE EmployeeID = @EmployeeID and PostId = @PostId
    END CATCH

    UPDATE BlogPost set RateNumber = RateNumber + 1 where EmployeeId = @EmployeeID and CreatedBy != @EmployeeID
END
于 2012-07-09T07:22:02.433 回答
0

我可以试试这个作为解决方案吗?@迈克尔

ALTER PROCEDURE [dbo].[BlogRatingSave]
     @EmployeeId    int
    ,@PostId        int
    ,@Rate          int
AS
BEGIN
IF(EXISTS(SELECT 1 FROM [HRM_BlogRating] WHERE EmployeeId= @EmployeeId AND [PostId] = @PostId))
    BEGIN
        DELETE 
            FROM 
                [HRM_BlogRating]
        WHERE   
                [HRM_BlogRating].[EmployeeId]=@EmployeeId  
            AND 
                [HRM_BlogRating].[PostId] = @PostId 
    END
ELSE
    BEGIN
        UPDATE 
            HRM_BlogPost 
        SET 
            RateNumber=isnull(RateNumber,0)+1 
        WHERE 
            Id=@PostId
    END 

    INSERT INTO [HRM_BlogRating]
        ([EmployeeId]
        ,[PostId]
        ,[Rate]
        )
    VALUES
        (@EmployeeId    
        ,@PostId        
        ,@Rate
        )
END
于 2012-07-09T08:45:16.463 回答