반응형


김종열

MS SQL Server MVP



 

udf_lag를 나름 만들고 나니 욕심이 나는 쿼리가 하나 있네요. 
누적합을 구하는 건데요.. 아주 lag와 비슷합니다.  코드는 참고하세요.. 

 


using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections.Generic;


public partial class UserDefinedFunctions
{
    public readonly static Dictionary<string, List<object>> _dicMemory = new Dictionary<string, List<object>>();

    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDouble Udf_Agg_Sum(object objValue, int key, string guid)
    {
        Double retValue = 0;

        if (_dicMemory.ContainsKey(guid) == false)
        {
            _dicMemory.Add(guid, new List<object>());
        }

        List<object> tempList = _dicMemory[guid];
        tempList.Add(objValue);


        int valueCount = tempList.Count;

        for (int i = 0; i < tempList.Count; i++)
        {
            retValue = retValue + Double.Parse(Convert.ToString(tempList[i]));
          
        }
       
        if (key == -1)
        {
            _dicMemory.Remove(guid);
        }

        return retValue;
       
    }
};

 

 


여튼 실행의 예시는 다음과 같습니다.


if OBJECT_ID('tempdb..#t') is not null
 drop table #t
go

create table #t ( a int)
go

insert into #t 
 select number from master.dbo.spt_values
 where TYPE= 'p'
go

declare @guid varchar(50) = newid()
 , @endbit int = 0 
 

select
*
, dbo.Udf_Agg_Sum(a,CASE ROW_NUMBER() OVER (ORDER BY a)WHEN 1 THEN 1
                                              WHEN @endbit THEN -1
                                              ELSE 0 END , @guid)
from
 #t



첨부 : Udf_Agg_Sum.cs
        udf_Agg_Sum.sql

반응형

'연구개발 > CLR' 카테고리의 다른 글

CLR - 병렬로 쿼리를 처리하기  (0) 2011.08.27
CLR - Windows Event Log  (0) 2011.08.27
CLR-이전행가기 udf_lag  (0) 2011.08.27
WMI 객체를 쿼리로 읽어오기  (0) 2010.08.10
파일리스트 불러오기  (0) 2009.06.22

+ Recent posts