sql – 获取查询的行号

前端之家收集整理的这篇文章主要介绍了sql – 获取查询的行号前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个将返回一行的查询.有什么办法可以在表格排序时找到我要查询的行的行索引吗?

我已经尝试过rowid但是当我期待排第7行时得到#582.

例如:

CategoryID  Name            
    I9GDS720K4  CatA
    LPQTOR25XR  CatB
    EOQ215FT5_  CatC
    K2OCS31WTM  CatD
    JV5FIYY4XC  CatE
--> C_L7761O2U  CatF <-- I want this row (#5)
    OU3XC6T19K  CatG
    L9YKCYAYMG  CatH
    XKWMQ7HREG  CatI

我尝试过rowid意外的结果:

SELECT rowid FROM Categories WHERE CategoryID = 'C_L7761O2U ORDER BY Name

编辑:我也尝试过J Cooper的建议(如下),但行数不正确.

using (var cmd = conn.CreateCommand()) {
        cmd.CommandText = string.Format(@"SELECT (SELECT COUNT(*) FROM Recipes AS t2             WHERE t2.RecipeID <= t1.RecipeID) AS row_Num 
                FROM Recipes AS t1 
                WHERE RecipeID = 'FB3XSAXRWD'
                ORDER BY Name";
        cmd.Parameters.AddWithValue("@recipeId",id);
        idx = Convert.ToInt32(cmd.ExecuteScalar());

解决方法

这是一种在sqlite中获取行号的方法
SELECT CategoryID,Name,(SELECT COUNT(*)
        FROM mytable AS t2
        WHERE t2.Name <= t1.Name) AS row_Num
FROM mytable AS t1
ORDER BY Name,CategoryID;
原文链接:https://www.f2er.com/mssql/76405.html

猜你在找的MsSQL相关文章