错误::“在动态sql中将nvarchar值'cereals'转换为数据类型int时转换失败”

ruyhziif  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(416)

我尝试在动态sql中按id“order by”我的表,尽管它可以与 Name 以及 Description (两种类型均为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 ---

该行给出以下错误
将nvarchar值“谷物”转换为数据类型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新手。

vyswwuz2

vyswwuz21#

可以将整个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 ---

相关问题