Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a function and use it in a SQL-Query

I was tring to create a function and use it in my little Query. I did not do this before and I do not really know to do it.

Is it simply the same like any other languages? like

create function testFunction()...
begin
..
..
end

and then for example :

Select testFunction() 

and it should work ?

CREATE FUNCTION dbo.ISOweek (@DATE datetime)  
RETURNS int  
WITH EXECUTE AS CALLER  
AS  
BEGIN  
     DECLARE @ISOweek int
     SET @ISOweek= DATEPART(wk,@DATE)+1  
          -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104')
--Special cases: Jan 1-3 may belong to the previous year  
     IF (@ISOweek=0)   
          SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1   
               AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1
--Special case: Dec 29-31 may belong to the next year  
     IF ((DATEPART(mm,@DATE)=12) AND   
          ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))  
          SET @ISOweek=1
     RETURN(@ISOweek)
END;  
GO  
SET DATEFIRST 1
SELECT dbo.ISOweek(CONVERT(DATETIME,'12/26/2004',101)) AS 'ISO Week'
like image 629
memo_star Avatar asked Sep 14 '25 23:09

memo_star


1 Answers

Yes, SQL functions are easy to create. But you have to understand the 3 different types of functions in SQL:
1) Scalar functions:
-- return a single value.
2) Table based functions:
-- returns a Table.
3) Aggregate function:
returns a single value (but the function looped through a window set).

creating a function in MS SQL Server 2012 by using template:
Creating Function with the MS SQL Server Client

There some great reference resources for starting creating SQL functions: an example of User Defined Scalar Function (from dotnettricks):

        --Create function to get emp full name 
        Create function fnGetEmpFullName
        (
          @FirstName varchar(50),
          @LastName varchar(50)
        )
        returns varchar(101)
        AS
        BEGIN 
          return (Select @FirstName + ' '+ @LastName);
        END


Microsoft reference, explanation and examples in this link
informit article on User Defined Functions in this link2
and finally from SQL Team website, an introduction to User Defined Functions

like image 124
Arthur Zennig Avatar answered Sep 17 '25 13:09

Arthur Zennig