【问题标题】:Issue when adding NULLS LAST添加 NULLS LAST 时的问题
【发布时间】:2020-02-21 15:17:44
【问题描述】:

在以下查询中添加“NULLS LAST”时,出现以下异常:

原因:com.microsoft.sqlserver.jdbc.SQLServerException:没有为参数号11设置值。

  1. 如果我删除 NULLS LAST 一切正常

  2. 如果我删除 CASE WHEN 代码并仅按一个特定列排序,它适用于 NULLS LAST,但我需要 CASE WHEN 上的所有列。

    @Query("SELECT c FROM ClassSpecificationTableEntity c"
            + " LEFT JOIN c.owner  o "
            + " LEFT JOIN c.domain d "
            + "WHERE ISNULL(c.classStructure.classification.description, '')    LIKE :SEARCH "
            + "   OR ISNULL(c.classStructure.description, '')                       LIKE :SEARCH "
            + " OR ISNULL(d.description, '')                                            LIKE :SEARCH "
            + " OR ISNULL(o.description, '')                                            LIKE :SEARCH "
            + " OR ISNULL(c.measurementUnit, '')                                    LIKE :SEARCH "
            + " OR ISNULL(c.defaultValue, '')                                       LIKE :SEARCH "
            + " OR ISNULL(c.dataType, '')                                               LIKE :SEARCH "
            + " OR ISNULL(c.tooltip, '')                                                LIKE :SEARCH "
            + " ORDER BY "
            + "  CASE :ORDERBY" + 
            "    WHEN 0 THEN c.classStructure.classification.description " +
            "    WHEN 1 THEN c.assetAttribId " + 
            "    WHEN 2 THEN c.dataType " + 
            "    WHEN 3 THEN c.measurementUnit " + 
            "    WHEN 4 THEN c.domain.description " + 
            "    WHEN 5 THEN c.owner.description " + 
            "    WHEN 6 THEN c.defaultValue " + 
            "    WHEN 7 THEN c.tooltip " + 
            "    END DESC NULLS LAST" 
            )
    Page<ClassSpecificationTableEntity> findByLikeSearchDESC(@Param(value="SEARCH") final String searchCrit, final Pageable pageable, @Param(value="ORDERBY") final String orderBy);

【问题讨论】:

  • 你的ON 子句在哪里?

标签: java sql-server spring-boot jpql


【解决方案1】:

没有NULLS LAST语法是T-SQL。

如果您想最后订购NULL 值,常用方法是使用CASE 表达式或IIF

--CASE Expression
CASE WHEN {expression} IS NULL THEN 1 ELSE 0 END
--IIF funciton (which is actually a shorthand CASE expression)
IIF({Expression} IS NULL, 1, 0)

如果您有一个复杂的表达式,您希望将 NULL 值排序在最后,然后是表达式,并且该表达式没有出现在 SELECT 中(因此不能被其别名引用),那么您可以将表达式移动到FROM,以避免多次输入表达式:

FROM ...
     JOIN ...
     LEFT JOIN ...
     ...
     CROSS APPLY (VALUES({Expression}))V(Alias)
WHERE ...
ORDER BY IIF(V.Alias IS NULL,1,0),
         V.Alias

【讨论】:

  • 感谢您的回答,但问题是:记住您所说的,我如何在 JPQL 中重写我的查询,以便生成正确的 T-SQL?
猜你喜欢
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 2011-04-10
  • 2013-04-24
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
相关资源
最近更新 更多