SQL创建视图并在Function中使用它

时间:2013-09-09 06:12:46

标签: sql sql-server sql-server-2005

我有以下功能,我需要取出SELECT部分并创建一个单独的视图。

CREATE FUNCTION dbo.dbf_get_penalty_points
(      @pn_seq_party_id          NUMERIC(18),
       @pv_penalty_points_code   CHAR(1) = 'Y') -- Use 'N' for total points, otherwise will return Current Penalty Points

RETURNS NUMERIC(18,0)
AS
BEGIN
   DECLARE @n_penalty_points       NUMERIC(18),
           @d_latest_points_date   DATETIME

   SELECT @d_latest_points_date = dbo.dbf_trunc_date(DateAdd(mm, - Abs(Convert(NUMERIC(18,0),dbo.dbf_get_sys_param('CMS2', 'PP_MONTHS'))), GetDate()))

   SELECT @n_penalty_points = IsNull(Sum(penalty_points_amount),0)
     FROM dbo.ar_penalty_point WITH(NOLOCK) 
    WHERE seq_party_id = @pn_seq_party_id
      AND 1 = CASE
                 WHEN @pv_penalty_points_code = 'N' THEN 1
                 WHEN @pv_penalty_points_code = 'Y' AND added_date >= @d_latest_points_date AND reset_date IS NULL THEN 1
                 ELSE 0
              END

   RETURN @n_penalty_points
END

GO

SET QUOTED_IDENTIFIER OFF
GO

GRANT EXECUTE ON dbo.dbf_get_penalty_points TO standard
GO

我试过这个,

 SELECT SUM(CASE WHEN added_date >=dbo.dbf_trunc_date(DateAdd(mm, - Abs(Convert(NUMERIC(18,0),dbo.dbf_get_sys_param('CMS2', 'PP_MONTHS'))), GetDate()))
                    AND reset_date IS NULL THEN 1 
                    ELSE 0) current_points,
           IsNull(Sum(penalty_points_amount),0) total_points,
           seq_party_id
     FROM dbo.ar_penalty_point WITH(NOLOCK) 
          GROUP BY seq_party_id

现在我需要摆脱

dbo.dbf_trunc_date(DateAdd(mm, - Abs(Convert(NUMERIC(18,0),dbo.dbf_get_sys_param('CMS2', 'PP_MONTHS'))), GetDate()))

来自查询的SELECT部分。我很震惊有没有更好的方式来写我的观点?

修改
目标是创建一个返回total_points和current_points的视图。为了更好地理解,请参阅以下CREATE部分

CREATE FUNCTION dbo.dbf_get_penalty_points
(      @pn_seq_party_id          NUMERIC(18),
       @pv_penalty_points_code   CHAR(1) = 'Y') -- Use 'N' for total points, otherwise will return Current Penalty Points

请参阅 - 使用'N'表示总积分,否则将在评论中返回当前惩罚点数

1 个答案:

答案 0 :(得分:0)

这就是我想出来的

SELECT SUM(CASE WHEN (t.added_date >= t.target_date
                AND t.reset_date IS NULL) THEN 1 
                ELSE 0 END) current_points,
       IsNull(Sum(t.penalty_points_amount),0) total_points,
       t.seq_party_id
 FROM (
   SELECT dbo.dbf_trunc_date(DateAdd(mm, - Abs(Convert(NUMERIC(18,0),dbo.dbf_get_sys_param('CMS2', 'PP_MONTHS'))), GetDate())) as target_date,
        u.reset_date, u.penalty_points_amount,u.seq_party_id,u.added_date  FROM
dbo.ar_penalty_point as u ) as t GROUP BY  t.seq_party_id