<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://sqlservernation.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>How Tos : scalar valued function, table valued function</title><link>http://sqlservernation.com/blogs/howtos/archive/tags/scalar+valued+function/table+valued+function/default.aspx</link><description>Tags: scalar valued function, table valued function</description><dc:language>en</dc:language><generator>CommunityServer 2008.5 SP2 (Build: 40407.4157)</generator><item><title>User Defined Functions</title><link>http://sqlservernation.com/blogs/howtos/archive/2009/03/07/user-defined-functions.aspx</link><pubDate>Sat, 07 Mar 2009 17:50:00 GMT</pubDate><guid isPermaLink="false">a3dbd76b-19b9-441f-b40a-d79e8f433d35:83</guid><dc:creator>BrandonGalderisi</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://sqlservernation.com/blogs/howtos/rsscomments.aspx?PostID=83</wfw:commentRss><comments>http://sqlservernation.com/blogs/howtos/archive/2009/03/07/user-defined-functions.aspx#comments</comments><description>&lt;p&gt;User defined functions have many uses in SQL Server.&amp;nbsp; Functions are useful to help clean up complex string manipulation logic in other areas of code and many other things.&amp;nbsp; But convenience is not free.&amp;nbsp; There is overhead in using functions and we will go over that later in the article.&lt;/p&gt;
&lt;p&gt;There are two types of User Defined Functions in SQL Server, Scalar Valued and Table Valued Functions.&amp;nbsp; Scalar Valued functions are used to return a single value whereas Table Valued functions return a table.&amp;nbsp; The table can be one or more columns and one or more rows.&amp;nbsp; While the structure for creating each type of function is nearly identical, how you use them is different.&lt;/p&gt;
&lt;p&gt;First let&amp;#39;s create a basic Scalar Valued function to show the proper way to construct your function.&amp;nbsp; For Scalar Valued Functions, you start with the keywords &amp;quot;create function&amp;quot;.&amp;nbsp; The next thing is the name of the function.&amp;nbsp; While it is not necessary to provide the schema name when naming the function, you will need to provide the schema name when using the function.&amp;nbsp; The next thing you provide is the keyword &amp;quot;returns&amp;quot; followed by the data type to be returned.&amp;nbsp; Returns says &amp;quot;This is the type of value that the function will return.&amp;nbsp; The next thing is the keyword &amp;quot;as&amp;quot;.&amp;nbsp; Like in stored procedures, it separates the definition of the function from the code of the function.&amp;nbsp; The next thing to know is that the code in a function MUST be contained within a BEGIN/END block.&amp;nbsp; And the last thing to know is that the last thing that a function must do is RETURN the value.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This basic function uses the dateadd and datediff functions to strip the time portion of the @DateTime parameter to have it return the DATE at midnight.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;create function dbo.fn_GetDateOnly(@DateTime datetime)&lt;br /&gt;returns datetime&lt;br /&gt;as&lt;br /&gt;begin&lt;br /&gt;return dateadd(d, datediff(d, 0, @DateTime), 0)&lt;br /&gt;end&lt;br /&gt;go&lt;br /&gt;&lt;/code&gt;&lt;code&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now how do we use scalar valued functions?&amp;nbsp; You use the function by selecting it.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;select dbo.fn_GetDateOnly(getdate())&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The result will be the the date which you run it with the time of midnight.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://sqlservernation.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_GetDateOnly.png"&gt;&lt;img src="http://sqlservernation.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_GetDateOnly.png" border="0" alt="" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You can also use it to format a datetime column as you select it from your table.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;&lt;/code&gt;&lt;code&gt;select dbo.fn_GetDateOnly(SomeDateField) as SomeDate&lt;br /&gt;from SomeTable&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Next we will create a simple Table Valued Function.&amp;nbsp; This function accepts a datetime parameter and then inserts the date of, before and after into the table for the function.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;create function dbo.fn_DatesTable(@BaseDate datetime)&lt;br /&gt;returns @Dates table (theDate datetime)&lt;br /&gt;as&lt;br /&gt;begin&lt;br /&gt;insert into @Dates (Thedate)&lt;br /&gt;values(Dateadd(d, datediff(d, 0, @BaseDate)-1, 0))&lt;br /&gt;insert into @Dates (Thedate)&lt;br /&gt;values(Dateadd(d, datediff(d, 0, @BaseDate), 0))&lt;br /&gt;insert into @Dates (Thedate)&lt;br /&gt;values(Dateadd(d, datediff(d, 0, @BaseDate)+1, 0))&lt;br /&gt;return&lt;br /&gt;end&lt;br /&gt;GO&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The below SQL shows you the difference in calling a Table Valued function as opposed to Scalar Valued functions.&amp;nbsp; You don&amp;#39;t select it, you select from it.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;select * from dbo.fn_datestable(&amp;#39;2009-03-07 12:00 pm&amp;#39;)&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The results will be:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://sqlservernation.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_GetDateOnly.png"&gt;&lt;/a&gt;&lt;a href="http://sqlservernation.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_DatesTable.PNG"&gt;&lt;img src="http://sqlservernation.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_DatesTable.PNG" border="0" alt="" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Another, less commonly used syntax for creating a table valued function is below.&amp;nbsp; This syntax is useful when you are using a user defined function in place of a view because you need to specify parameters.&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;create function dbo.fn_dosomething()&lt;br /&gt;returns  TABLE&lt;br /&gt;as&lt;br /&gt;&lt;br /&gt;return &lt;br /&gt;(         select cast(1 as int) as Id, cast(N&amp;#39;Hello&amp;#39; as nvarchar(50)) as theValue&lt;br /&gt;union all select 2,&amp;#39;Good Bye&amp;#39;&lt;br /&gt;)&lt;br /&gt;GO&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now comes the bad news.&amp;nbsp; While functions are useful tools, they are not for every scenario.&amp;nbsp; There is some overhead to using functions.&amp;nbsp; The below Test script will loop 100,000 times and assign the function&lt;/p&gt;
&lt;pre style="border:1px dashed #999999;padding:5px;overflow:auto;font-family:Andale Mono,Lucida Console,Monaco,fixed,monospace;color:#000000;background-color:#eeeeee;font-size:12px;line-height:14px;width:100%;"&gt;&lt;code&gt;declare &lt;br /&gt;      @SampleDate   datetime&lt;br /&gt;     ,@dt           datetime&lt;br /&gt;     ,@dt2          datetime&lt;br /&gt;     ,@i            int&lt;br /&gt;declare @res table&lt;br /&gt;     (Method        varchar(20)&lt;br /&gt;     ,Time_In_Ms    int&lt;br /&gt;     )&lt;br /&gt;set @SampleDate = getdate()&lt;br /&gt;set @dt = getdate()&lt;br /&gt;set @i=1&lt;br /&gt;while @i&amp;lt;100000&lt;br /&gt;begin&lt;br /&gt;     set @dt2=dbo.fn_GetDateOnly(@sampleDate+@i)&lt;br /&gt;set @i=@i+1&lt;br /&gt;end&lt;br /&gt;insert into @Res(Method,time_In_Ms)&lt;br /&gt;values(&amp;#39;Function&amp;#39;, datediff(ms, @dt, getdate()))&lt;br /&gt;&lt;br /&gt;set @dt = getdate()&lt;br /&gt;set @i=1&lt;br /&gt;while @i&amp;lt;100000&lt;br /&gt;begin&lt;br /&gt;     set @dt2=dateadd(d, datediff(d, 0, @SampleDate+@i), 0)&lt;br /&gt;set @i=@i+1&lt;br /&gt;end&lt;br /&gt;insert into @Res(Method,time_In_Ms)&lt;br /&gt;values(&amp;#39;SQL&amp;#39;, datediff(ms, @dt, getdate()))&lt;br /&gt;select * from @Res&lt;br /&gt;&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;As you can see by this output, executing the same statement through a function is slower than using an inline SQL.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://sqlservernation.com/cfs-file.ashx/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_VS_5F00_inline.PNG"&gt;&lt;img src="http://sqlservernation.com/resized-image.ashx/__size/550x0/__key/CommunityServer.Blogs.Components.WeblogFiles/howtos.User+Defined+Functions/res_5F00_fn_5F00_VS_5F00_inline.PNG" border="0" alt="" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Now that you know the basics of functions, you are ready to get into some tougher examples.&amp;nbsp; Look for more postings specific on scalar and table valued functions.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://sqlservernation.com/aggbug.aspx?PostID=83" width="1" height="1"&gt;</description><category domain="http://sqlservernation.com/blogs/howtos/archive/tags/Beginner+SQL/default.aspx">Beginner SQL</category><category domain="http://sqlservernation.com/blogs/howtos/archive/tags/table+valued+function/default.aspx">table valued function</category><category domain="http://sqlservernation.com/blogs/howtos/archive/tags/scalar+valued+function/default.aspx">scalar valued function</category><category domain="http://sqlservernation.com/blogs/howtos/archive/tags/User+Defined+Functions/default.aspx">User Defined Functions</category></item></channel></rss>