简体   繁体   中英

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'

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:
使用MS SQL Server客户端创建功能

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

This is a bit broad, do you want to return a table? a value?.. There are many different things that a function can do, a sample syntax would be:

CREATE FUNCTION Schema.FunctionName
(
@InputValue InputValueDataType --Parameters here
)
RETURNS ReturnDataType -- The data type you want to return it
AS
BEGIN
    -- Do some things with @InputValue
END

The Microsoft Doc is HERE it explains the different ways to do it

Then you can just do SELECT * FROM schema.FunctionName (@InputValue) to return it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM