{"id":3716,"date":"2013-01-04T18:55:51","date_gmt":"2013-01-04T18:55:51","guid":{"rendered":"http:\/\/craftydba.com\/?p=3716"},"modified":"2013-01-05T21:25:07","modified_gmt":"2013-01-05T21:25:07","slug":"scalar-valued-functions","status":"publish","type":"post","link":"https:\/\/craftydba.com\/?p=3716","title":{"rendered":"Scalar Valued Functions"},"content":{"rendered":"<p><a href=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/yellow-binary-data.jpg\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/yellow-binary-data-150x150.jpg\" alt=\"\" title=\"yellow-binary-data\" width=\"150\" height=\"150\" class=\"alignleft size-thumbnail wp-image-3720\" srcset=\"https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/yellow-binary-data-150x150.jpg 150w, https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/yellow-binary-data.jpg 170w\" sizes=\"auto, (max-width: 150px) 100vw, 150px\" \/><\/a><br \/>\nToday, I want to start talking about database objects that are associated with stored (compiled) code.  A user-defined function is any Transactional SQL (<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/bb510741.aspx\">TSQL<\/a>) or Common Language Runtime (<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/8bs2ecf4(v=vs.71).aspx\">CLR<\/a>) routine that accepts parameters, performs an action, and returns the result of that action as a value. <\/p>\n<p>The return value can either be a scalar (single) value datatype or a composite (multiple) values table. I am going to concentrate on Scalar Value Functions today.<\/p>\n<p>Like most Data Definition Language (<a href=\"http:\/\/en.wikipedia.org\/wiki\/Data_definition_language\">DDL<\/a>) constructs, a user define function has three operations associated with it:  <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms186755.aspx\">CREATE FUNCTION<\/a>, <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms186967.aspx\">ALTER FUNCTION<\/a> and <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms190290.aspx\">DROP FUNCTION<\/a> <\/p>\n<p>I will be using the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/aa992075.aspx\">Adventure Works <\/a>2012 sample database supplied by Microsoft during this talk.  The SQL snippet below, drops the function if it exists, creates a new stub function, and alters the function to be identical to the original.<\/p>\n<pre><span style=\"color: #008000;\">-- Use the correct database\r\nUSE [AdventureWorks2012]\r\nGO\r\n\r\n-- Delete existing scalar valued function\r\nIF  EXISTS (\r\n    SELECT * FROM sys.objects\r\n    WHERE object_id = OBJECT_ID(N'[dbo].[ufnGetStock]') AND [type] in (N'FN')\r\n\t)\r\nDROP FUNCTION [dbo].[ufnGetStock]\r\nGO\r\n\r\n\r\n-- Create stub scalar valued function\r\nCREATE FUNCTION [dbo].[ufnGetStock] (@ProductID [int])\r\nRETURNS [int] \r\nAS \r\nBEGIN\r\n    RETURN 1;\r\nEND\r\nGO\r\n\r\n-- Alter sclar valued function\r\nALTER FUNCTION [dbo].[ufnGetStock] (@ProductID [int])\r\nRETURNS [int] \r\nAS \r\nBEGIN\r\n    -- Declare local variable\r\n    DECLARE @ret int;\r\n    \r\n    -- Only look at inventory in the misc storage\r\n    SELECT @ret = SUM(p.[Quantity]) \r\n    FROM [Production].[ProductInventory] p \r\n    WHERE \r\n        p.[ProductID] = @ProductID \r\n        AND p.[LocationID] = '6'; \r\n    \r\n\t-- Return the result\r\n    IF (@ret IS NULL) SET @ret = 0;\r\n    RETURN @ret;\r\n\r\nEND\r\nGO\r\n\r\n<\/span><\/pre>\n<p>While functions can be very complex, this simple one returns the current stock level given a [ProductId].  What good is a function, if it is not used in a query?  The code snippet below returns the stock level of all seats sold by Adventure Works.<\/p>\n<pre><span style=\"color: #008000;\">-- Example use of the function\r\nSELECT \r\n    ProductId, \r\n    [name] as ProductName,\r\n    [dbo].[ufnGetStock](ProductId) as StockLevel\r\nFROM \r\n    [Production].[Product]\r\nWHERE\r\n    [name] like '%seat%';\r\n\r\n<\/span><\/pre>\n<p>In short, Scalar Value Functions are good at taking zero or more values as an input parameters, perform any desired database actions, and returning a single value, output parameter, as a result.  Next time, I will be talking about Table Valued Functions (<a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/ms191165(v=sql.105).aspx\">TVF<\/a>).<\/p>\n<p><a href='https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/scalar-value-function.csv.txt'>Scalar Valued Function Output<\/a><\/p>\n<p><a href='https:\/\/craftydba.com\/wp-content\/uploads\/2013\/01\/scalar-value-function.sql_.txt'>Scalar Valued Function Example<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Today, I want to start talking about database objects that are associated with stored (compiled) code. A user-defined function is any Transactional SQL (TSQL) or Common Language Runtime (CLR) routine that accepts parameters, performs an action, and returns the result of that action as a value. The return value can either be a scalar (single) value datatype or a composite (multiple) values table. I am going to concentrate on Scalar Value Functions today. Like most Data Definition Language (DDL) constructs, a user define function has three operations associated with it:&hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[698,565,31,564,12,15,699,28,29],"class_list":["post-3716","post","type-post","status-publish","format-standard","hentry","category-db-dev","tag-alter-function","tag-create-funtion","tag-database-developer","tag-drop-function","tag-free-code","tag-john-f-miner-iii","tag-scalar-value-function","tag-sql-server","tag-tsql"],"_links":{"self":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3716","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3716"}],"version-history":[{"count":0,"href":"https:\/\/craftydba.com\/index.php?rest_route=\/wp\/v2\/posts\/3716\/revisions"}],"wp:attachment":[{"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3716"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3716"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/craftydba.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}