SQL - 尝试增加值时出现语法错误

时间:2017-04-12 11:31:28

标签: c# sql sql-server

我在C#项目中使用SQL Server进行故障排除程序,我有一个包含ID,Question,QuestionId,Solution和Rank的表。 I previously asked a question and it worked for selecting, so I tried modifying that for an Update instead.我试图将排名最高的解决方案的排名提高1.

sql = "UPDATE dbo.Questions SET Rank = Rank + 1 q WHERE Rank=(SELECT MAX(Rank) FROM dbo.Questions i where i.QuestionId = q.QuestionId) AND q.QuestionId = " + questionId;

我得到以下错误:

  

' q'附近的语法不正确     关键字' AND'

附近的语法不正确

1 个答案:

答案 0 :(得分:3)

表别名位于错误的位置。在SQL Server中,您需要FROM子句:

UPDATE q
    SET Rank = Rank + 1
    FROM dbo.Questions q
    WHERE Rank = (SELECT MAX(Rank)
                  FROM dbo.Questions i 
                  WHERE i.QuestionId = q.QuestionId
                 ) AND
         q.QuestionId = " + questionId;

您也可以将其写为:

UPDATE q
    SET Rank = Rank + 1
    FROM (SELECT TOP (1) q.*
          FROM dbo.Questions q
          WHERE q.QuestionId = " + questionId
          ORDER BY rank DESC
         );

这显然您只想更新一行。

我还要补充一下。 。 。学会使用查询参数。不要将questionId直接放入查询字符串中。这只是一种引入非常难以调试的语法错误的方法。