SQL服务器查询返回但功能没有

时间:2017-10-28 11:48:06

标签: java sql sql-server hibernate jpa

在我基于Java的网络项目中,我已经进行了一次recursive查询,该查询运行得非常好,并返回ids列表。

WITH treeResult(id) AS 
    (SELECT pt.id FROM myschema.art_artwork_tree AS pt WHERE pt.id in 
      (select node_id from myschema.art_brand_user_mapping where emp_id = $1)
     UNION ALL 
     SELECT pa.id FROM treeResult AS p, myschema.art_artwork_tree AS pa 
     WHERE pa.parent_node = p.id and pa.site_id = $2) SELECT id FROM treeResult AS n
    );

现在,我想在JPQL查询中使用它。所以,我已经function如下所示。

USE [darshandb]
GO

DROP FUNCTION [dbo].[testfunction]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

    CREATE FUNCTION [dbo].[testfunction] (@empId INT,@siteId INT)
     RETURNS TABLE
     WITH SCHEMABINDING
     AS
     RETURN
     (
      WITH treeResult(id) AS 
        (SELECT pt.id FROM myschema.art_artwork_tree AS pt WHERE pt.id in 
          (select node_id from myschema.art_brand_user_mapping where emp_id = $1)
         UNION ALL 
         SELECT pa.id FROM treeResult AS p, myschema.art_artwork_tree AS pa 
         WHERE pa.parent_node = p.id and pa.site_id = $2) SELECT id FROM treeResult AS n
    );
GO

当我尝试执行function时,它不会返回任何值。

SELECT * FROM [dbo].[testfunction] (4,3);

请帮助我,我做错了什么。

1 个答案:

答案 0 :(得分:1)

我认为您的问题是在您的函数查询中使用$1$2。只需在表值函数中使用原始参数名称。

因此,在用户定义的函数中用@empId替换$ 1,用@siteId替换$ 2.