简体   繁体   English

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

[英]SQL - Syntax Error When Trying to Increment a Value

I'm using SQL Server in a C# project for a troubleshooting program and I have a table that contains ID,Question,QuestionId,Solution and Rank. 我在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. 我之前曾问过一个问题,它可以选择,所以我尝试修改它来更新。 I'm trying to increment the rank of the solution with the highest rank by 1. 我正在尝试将具有最高排名的解决方案的排名增加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;

I get the following error with this: 我收到以下错误:

Incorrect syntax near 'q' Incorrect syntax near the keyword 'AND' 'q'附近的语法不正确关键字'AND'附近的语法不正确

The table alias is in the wrong place. 表别名放在错误的位置。 In SQL Server, you want a FROM clause: 在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;

You can also write this as: 您也可以这样写:

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

This makes it obvious that you only want to update one row. 很明显,您只想更新一行。

Let me also add . 让我也补充一下。 . . learn to use query parameters. 学习使用查询参数。 Don't put questionId directly into the query string. 不要将questionId直接放入查询字符串中。 That is just a way to introduce syntax errors that are really hard to debug. 这只是引入很难调试的语法错误的一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM