Error :: "Conversion failed when converting the nvarchar value 'cereals' to data type int" in Dynamic SQL

Error :: "Conversion failed when converting the nvarchar value 'cereals' to data type int" in Dynamic SQL

我正在尝试按动态 SQL 中的 Id“订购”我的 table,尽管它适用于 NameDescription(均为 Nvarchar 类型)已显示但未使用 Id(类型 INT), 这是我的动态 SQL 查询

';With data AS (Select P.Id,
    P.Name,
    P.Description,
    P.Price,
    12 AS ActiveUsers,
    B.Name as BillingPeriod,
        CASE '+@SortField+'
                WHEN P.Name THEN ROW_NUMBER() OVER (ORDER BY P.Name)
                WHEN Description THEN ROW_NUMBER() OVER (ORDER BY P.Description)
                WHEN P.Id THEN ROW_NUMBER() OVER (ORDER BY P.Id)   *****This Line Gives Error*****
            END rn '
     --- REST of The SP ---

该行给出以下错误

Conversion failed when converting the nvarchar value 'cereals' to data type int.

我打印SQL它显示...

CASE P.Id
                WHEN P.Name THEN ROW_NUMBER() OVER (ORDER BY P.Name)
                WHEN Description THEN ROW_NUMBER() OVER (ORDER BY P.Description)
                WHEN P.Id THEN ROW_NUMBER() OVER (ORDER BY P.Id)
                END rn From Products P  

请帮助我,我是 sql 的新手。

您可以将整个 CASE 表达式替换为...

';With data AS (Select P.Id,
    P.Name,
    P.Description,
    P.Price,
    12 AS ActiveUsers,
    B.Name as BillingPeriod,
    ROW_NUMBER() OVER (ORDER BY '+@SortField+')'
     --- REST of The SP ---