我正在尝试更新存储在SQL Server 2012中的博客帖子的评论和/或评分。
我需要检查注释是否为空字符串,如果是,则传递该代码块。
我需要检查评级是否为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]
答案 0 :(得分:0)
IF [Comment] <> ""
,否则 SET QUOTED_IDENTIFIER OFF
应为单引号
对于UPDATE EasyDNNNewsComments SET Comment = '[Comment]'
我假设您要将其设置为列值,而不是字符串文字,因此您希望删除[Comment]
周围的引号
答案 1 :(得分:0)
我宁愿不注意&#34;注射&#34;使用标记进入代码(除非在您的情况下严格必要),但创建过程并传递参数。 按照一个原始的例子(它有可能存在一些错误,因为我在没有表格的情况下编写它而没有进行任何测试,但它应该给你一个想法。)
当然,你应该添加错误检查,检查参数和其他东西,以使代码更强大,更可靠。
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