2017-08-31 61 views
0

我試圖更新存儲在SQL Server的博客中的評論和/或評級2012年正確的SQL語法和值

我需要檢查,如果該評論是一個空字符串,如果通過該代碼塊。

我需要檢查評級是否爲0.0,如果是的話繞過該代碼塊。註釋和評級使用標記[Comment][RatingValue]注入到SQL語句中。

上面的正確語法是什麼?以下是我已經試過:

IF [Comment] <> "" 
    UPDATE EasyDNNNewsComments 
    SET Comment = '[Comment]' 
    WHERE CommentID = [CommentID] 
ELSE IF [NewRating] <> 0.0 
    SELECT 
     EasyDNNNewsComments.Comment, EasyDNNNewsComments.DateAdded, 
     EasyDNNNewsComments.UserID, EasyDNNNewsComments.CommentID, 
     Users.UserName 
    FROM 
     EasyDNNNewsComments 
    INNER JOIN 
     Users ON EasyDNNNewsComments.UserID = Users.UserID 
    WHERE 
     (ArticleID = [ArticleID]) 
    ORDER BY 
     EasyDNNNewsComments.CommentID DESC 

UPDATE ArticleRating 
SET RatingValue = [NewRating] 
WHERE ArticleID = [ArticleID] AND UserID = [UserID] 

UPDATE EasyDNNNews 
SET RatingValue = (SELECT Sum(RatingValue) FROM ArticleRating WHERE ArticleID = [ArticleID])/(SELECT Count(*) FROM ArticleRating WHERE ArticleID = [ArticleID]) 

SELECT RatingValue 
FROM EasyDNNNews 
WHERE ArticleID = [ArticleID] 
+1

IF [評論] <>「」應該是單引號,除非你'設置QUOTED_IDENTIFIER OFF' – scsimon

+2

我不知道你想做的事,但是這個代碼並沒有太大的SENCE。什麼是「[評論]」?這應該是一個變量? (同樣適用於''CommentID]','[NewRating]'ect'。 –

回答

0

IF [Comment] <> ""應該是單引號,除非你有SET QUOTED_IDENTIFIER OFF

對於UPDATE EasyDNNNewsComments SET Comment = '[Comment]'我假設你想將它設定爲列值,而不是字符串文字這樣你會想刪除左右的引號[Comment]

0

我不希望使用標記「注入」代碼(除非在您的情況下絕對必要),但創建一個過程並傳遞參數。 請遵循一個原始示例(可能會出現一些錯誤,因爲我沒有使用表格進行編寫,也沒有進行任何測試,但它應該給出一個想法)。

當然,您應該添加檢查錯誤,檢查參數和其他事情,使代碼更強大,更可靠。

CREATE PROCEDURE DO_IT 
    @pComment VARCHAR(500) 
    , @pComment_id INT 
    , @pNewRating NUMBER(10,2) 
    , @pArticleID INT 
    , @pUserID INT) 
AS 
BEGIN 
    SET NOCOUNT ON; 
    IF @pComment <> '' 
     UPDATE EasyDNNNewsComments 
     SET Comment = @pComment 
     WHERE CommentID = @pComment_id 
    ELSE IF @pNewRating <> 0.0 
     BEGIN 
      SELECT EasyDNNNewsComments.Comment 
       , EasyDNNNewsComments.DateAdded 
       , EasyDNNNewsComments.UserID 
       , EasyDNNNewsComments.CommentID 
       , Users.UserName 
      FROM EasyDNNNewsComments 
      INNER JOIN Users ON EasyDNNNewsComments.UserID = Users.UserID 
      WHERE ArticleID = @pArticleID 
      ORDER BY EasyDNNNewsComments.CommentID DESC 

      UPDATE ArticleRating SET RatingValue = @pNewRating 
      WHERE ArticleID = @pArticleID AND UserID = @pUserID; 

      UPDATE EasyDNNNews SET RatingValue = 
           (SELECT Sum(RatingValue)/Count(*) 
           FROM ArticleRating 
           WHERE ArticleID = @pArticleID) ; 
     END 

     SELECT RatingValue 
     FROM EasyDNNNews 
     WHERE ArticleID = @pArticleID; 

END