Sunday, January 22, 2012

Table-Valued Function in SQL Server

---- Create a test table and insert some data 
IF OBJECT_ID('ProductionHistory')>0   
       DROP TABLE ProductionHistory;  

 CREATE TABLE [dbo].[ProductionHistory]
 (         
       [WellID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, 
       [WellName] [varchar](50) NULL,               
       [Date] datetime NULL,         
       [Oil] decimal(18,6) NULL,               
       [Gas] decimal(18,6) NULL,               
       [Water] decimal(18,6) NULL               
 )  

 DECLARE @counter int
 SET @counter = 1            

 WHILE (@counter <=1000)
 BEGIN                           

       INSERT INTO [ProductionHistory](Wellname, [date], [oil], [gas], [water])                     
       VALUES ('Mustang Ranch #1', DATEADD(day, @counter, '2009-01-01'), 50 + (80-50)*RAND(), 10 + (30-10)*RAND(), 1 + (10-1)*RAND())                  

       INSERT INTO [ProductionHistory](Wellname, [date], [oil], [gas], [water])                     
       VALUES ('Mary May #1', DATEADD(day, @counter, '2009-01-01'), 80 + (120-80)*RAND(), 1 + (10-1)*RAND(), 20 + (30-20)*RAND())                  



       SET @counter = @counter + 1
 END  
 GO
---- Create a table valued function to sum values to date
Create FUNCTION dbo.udf_GetCumulativeProduction
 (
       @WellName varchar(50),
       @Date datetime
 )
 RETURNS @CumulativeProductionTable TABLE
 (
       CumulativeOil Decimal(18,6),
       CumulativeGas Decimal(18,6),
       CumulativeWater Decimal(18,6)
 )  

 BEGIN
      
       INSERT INTO @CumulativeProductionTable(CumulativeOil, CumulativeGas, CumulativeWater)
       SELECT
             SUM(Oil), SUM(Gas), Sum(Water)
       FROM
             ProductionHistory
       WHERE WellName = @WellName 
         AND Date <= @Date     
       RETURN
 END
 GO

---- Call the function for each row 
SELECT *
FROM ProductionHistory ph
 CROSS APPLY dbo.udf_GetCumulativeProduction(ph.wellName, ph.date)  



Wanted to have a simple example of a table-valued function. For this example I created some daily production data for a couple of wells. I use the table valued function to calculate the cumulative production to date for each well.

No comments:

Post a Comment