SQL Order by 子句在操作期间赋值时受影响

SQL Order by clause affected when assigned value during operation

我正在使用 SQL 服务器并且有一个 Users table 包含这些列:

Sr. (int), civil_id (varchar), fname etc 

我想要实现的是在我的用户 table 中有序插入 civil_id 比如说 100,101 等

为此,我尝试使用前 1 获取最后一行的 civil_idvarchar 类型),并为我的下一个用户插入排序并递增 1。

ALTER PROCEDURE [dbo].[check123]                               
AS 
     SET NOCOUNT ON 
     BEGIN

     DECLARE @civic int='';
    
     SELECT TOP 1 @civic = CONVERT(INT, civil_id) 
     FROM Users  
     ORDER BY Sr DESC;

     // just an example here  
     UPDATE Users
     SET civil_id = @civic + 1 
     WHERE Sr = 299
     //old civil_id was 10000 but after update it is 11  
END

但问题是当我在为

赋值时订购
@civic = CONVERT(INT, civil_id) FROM Users

我没有得到我想要的 civil_id,事实上它根本没有排序,而是给出 0 或其他一些输出。

我的 civil_id 列是 varchar 而不是 int 所以我转换了但我认为它仍在考虑 ASCII 值

有什么建议吗?

注意:我无法将 civil_id 的列类型更改为 int,因为太多的存储过程已经将其视为 varchar 类型。

总的来说,你的查询对我来说似乎是正确的,尽管有一些混淆。让我们提出一些您可以执行的改进-

ALTER PROCEDURE [dbo].[check123]                               
AS 
 SET NOCOUNT ON 
 BEGIN

 -- DECLARE @civic int='';
 -- Do not need to assign a blank string which is VARCHAR by default to a 
 -- Integer type variable. You can simply Declare the variable as below-
 DECLARE @civic INT

 SELECT TOP 1 @civic = CONVERT(INT, civil_id) + 1
 -- Directly generate the desired value by adding +1 as shown above
 -- Now your  declared variable @civic contains the final value you wants.
 FROM Users  
 ORDER BY Sr DESC;

 // just an example here  
 UPDATE Users
 SET civil_id = @civic
 WHERE Sr = 299
 //old civil_id was 10000 but after update it is 11  
 -- Not sure what you are checking here by sr = 299
END

对于上面的查询(基本上是你的查询),我总是得到预期的结果,你可以在这里通过使用不同的输入更改值来检查它 DEMO HERE

现在,随着@civic 中的值按预期生成,问题是通过检查“sr= 299”提出您基本上更新哪一行,然后选择哪一行来检查相应更新的值。如果您正在更新正确的 row/s,值应该是正确的,并且 @civic 值生成没有问题。