Sql 服务器查询在 Management Studio 中有效,但在 C# 中无效 (ServiceStack.OrmLite)

Sql Server query works in management studio but not in C# (ServiceStack.OrmLite)

以下递归查询在 SSMS 中有效,但在 ServiceStack 中的 C# 查询中无效。它归结为查询(我认为)......或者我正在使用 OrmLite 的事实......在 SQL Server Management Studio 中查询工作得非常好......它列出了分层的记录(自引用)table。 RowNumber 很不错,因为我可以按 ID、名称等进行排序。

我得到的错误是

Incorrect syntax near the keyword 'WITH'. Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.

代码:

var sql = @"
WITH TREE (CategoryId, Active, Created, Modified, SortBy, [Name], [Description], Parent_CategoryId, Depth, Sort) AS
(
   SELECT 
      c.CategoryId, c.Active, c.Created, c.Modified, c.SortBy, 
      c.[Name], c.[Description], c.Parent_CategoryId, 
      0 AS Depth,
      CONVERT(VARCHAR(20), RIGHT('0000000000' + CAST((ROW_NUMBER() over (order by c.CategoryId)) AS VARCHAR), 10)) AS Sort 
   FROM 
      category c 
   WHERE 
      c.parent_categoryid IS NULL

   UNION ALL

   SELECT 
      c2.CategoryId, c2.Active, c2.Created, c2.Modified, c2.SortBy, 
      c2.[Name], c2.[Description], c2.Parent_CategoryId, 
      t.Depth + 1,
      CONVERT(VARCHAR(20),  t.Sort + RIGHT('0000000000' + CAST((ROW_NUMBER() over (order by c2.Name)) AS VARCHAR), 10)) AS Sort
   FROM 
      Category c2
   INNER JOIN 
      TREE as t ON t.CategoryId = c2.Parent_CategoryId
)
SELECT 
    CategoryId, Active, Created, Modified, SortBy, [Name], 
    [Description], Parent_CategoryId, Depth, Sort 
FROM TREE 
WHERE depth < 2";

var result = Db.Select<Category>(sql);

--- The following is the Category object ---
namespace EdgeLib
{
    [Route("/folder", "POST")]
    public class Category
    {
        [AutoIncrement]
        [Alias("CategoryId")]
        public long? Id { get; set; }

        public bool? Active { get; set; }

        [Compute] // serialize from database... but not to database
        public DateTime? Created { get; set; }
        [Compute] // serialize from database... but not to database
        public DateTime? Modified { get; set; }

        public double? SortBy { get; set; }

        [ForeignKey(typeof(Category))]
        public long? Parent_CategoryId { get; set; }

        [Index]
        public string Name { get; set; }

        public string Description { get; set; }

        // returned in the recursive query
        [Ignore]
        public int? Depth { get; set; } 
        [Ignore]
        public string Sort { get; set; } 

        public override string ToString()
        {
            return Name;
        }
    }
}

您应该在执行自定义查询时使用 OrmLite's Custom SQL API's,例如:

var result = Db.SqlList<Category>(sql);