Thursday, December 6, 2012

Sql Server Functions

SQL Aggregate Functions
SQL aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:
AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum

SQL Scalar functions

SQL scalar functions return a single value, based on the input value.

Useful scalar functions:
UCASE() - Converts a field to upper case
LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LEN() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimals specified
NOW() - Returns the current system date and time
FORMAT() - Formats how a field is to be displayed

Executing Scalar Function:
select dbo.ScalarFunctionName(@param1..)

Table-Valued Functions
Table-Valued Functions have been around since SQL Server version 2005. Basically a Table-Valued Function is a function that returns a table, thus it can be used as a table in a query.

Executing Table-valued Function:
select * from dbo.TablevaluedfunctionName(@param1..)


CREATE FUNCTION [dbo].[testFunction](@Itemvalue int)      

returns @temptable TABLE (ID int IDENTITY(1,1),value int)      

 set @Itemvalue=@Itemvalue+20
  insert into @temptable(value) values(@Itemvalue)    

select * from testFunction(50)

Out put:

ID value
1 70

No comments:
Write comments
Recommended Posts × +