Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Function Category Explanation: Rowset Functions

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

Functions

The Transact-SQL programming language provides three types of functions: Rowset functions Can be used like table references in an SQL statement. For more information about a list of these functions, see Rowset Functions. Aggregate functions Operate on a collection of values but return a single, summarizing value. For more information about a list of these functions, see Aggregate Functions. Scalar functions Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid. This table categorizes the scalar functions. Function category Explanation Configuration Functions Returns information about the current configuration. Cursor Functions Returns information about cursors. Performs an operation on a date and time input value and returns either a string, numeric, Date and Time Functions or date and time value. Performs a calculation based on input values provided as parameters to the function, and Mathematical Functions returns a numeric value. Metadata Functions Returns information about the database and database objects. Security Functions Returns information about users and roles. Performs an operation on a string (char or varchar) input value and returns a string or String Functions numeric value. Performs operations and returns information about values, objects, and settings in System Functions Microsoft SQL Server. System Statistical Returns statistical information about the system. Functions Performs an operation on a text or image input values or column, and returns information Text and Image Functions about the value.
Function Determinism

SQL Server 2000 built-in functions are either deterministic or nondeterministic. Functions are deterministic when they always return the same result any time they are called with a specific set of input values. Functions are nondeterministic when they could return different results each time they are called, even with the same specific set of input values. The determinism of functions dictate whether they can be used in indexed computed columns and indexed views. Index scans must always produce consistent results. Thus, only deterministic functions can be used to define computed columns and views that are to be indexed. Configuration, cursor, meta data, security, and system statistical functions are nondeterministic. In addition, the following built-in functions are also always nondeterministic: @@ERROR FORMATMESSAGE NEWID @@IDENTITY GETANSINULL PERMISSIONS @@ROWCOUNT GETDATE SESSION_USER @@TRANCOUNT HOST_ID STATS_DATE APP_NAME HOST_NAME SYSTEM_USER CURRENT_TIMESTAMP IDENT_INCR TEXTPTR CURRENT_USER IDENT_SEED TEXTVALID DATENAME IDENTITY USER_NAME
Function Collation

Functions that take a character string input and return a character string output use the collation of the input string for the output. Functions that take non-character inputs and return a character string use the default collation of the current database for the output.

Functions that take multiple character string inputs and return a character string use the rules of collation precedence to set the collation of the output string. For more information, see Collation Precedence.

FOR Clause
FOR clause is used to specify either the BROWSE or the XML option (BROWSE and XML are unrelated options).
Syntax

[ FOR { BROWSE | XML { RAW | AUTO | EXPLICIT } [ , XMLDATA ] [ , ELEMENTS ] [ , BINARY BASE64 ] } ]
Arguments

BROWSE Specifies that updates be allowed while viewing the data in a DB-Library browse mode cursor. A table can be browsed in an application if the table includes a time-stamped column (defined with the timestamp data type), the table has a unique index, and the FOR BROWSE option is at the end of the SELECT statement(s) sent to SQL Server. For more information, see Browse Mode. Note It is not possible to use the <lock_hint> HOLDLOCK in a SELECT statement that includes the FOR BROWSE option. The FOR BROWSE option cannot appear in SELECT statements joined by the UNION operator. XML Specifies that the results of a query are to be returned as an XML document. One of these XML modes must be specified: RAW, AUTO, EXPLICIT. For more information about XML data and SQL Server, see Retrieving XML Documents Using FOR XML. RAW Takes the query result and transforms each row in the result set into an XML element with a generic identifier <row /> as the element tag. For more information, see Using RAW Mode. AUTO Returns query results in a simple, nested XML tree. Each table in the FROM clause, for which at least one column is listed in the SELECT clause, is represented as an XML element. The columns listed in the SELECT clause are mapped to the appropriate element attributes. For more information, see Using AUTO Mode. EXPLICIT Specifies that the shape of the resulting XML tree is defined explicitly. Using this mode, queries must be written in a particular way so that additional information about the desired nesting is specified explicitly. For more information, see Using EXPLICIT Mode. XMLDATA Returns the schema, but does not add the root element to the result. If XMLDATA is specified, it is appended to the document. ELEMENTS Specifies that the columns are returned as subelements. Otherwise, they are mapped to XML attributes. BINARY BASE64 Specifies that the query returns the binary data in binary base64-encoded format. In retrieving binary data using RAW and EXPLICIT mode, this option must be specified. This is the default in AUTO mode.

WHILE
Sets a condition for the repeated execution of an SQL statement or statement block. The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.

Syntax

WHILE Boolean_expression { sql_statement | statement_block } [ BREAK ] { sql_statement | statement_block } [ CONTINUE ]


Arguments

Boolean_expression Is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses. {sql_statement | statement_block} Is any Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block, use the control-of-flow keywords BEGIN and END. BREAK Causes an exit from the innermost WHILE loop. Any statements appearing after the END keyword, marking the end of the loop, are executed. CONTINUE Causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.
Remarks

If two or more WHILE loops are nested, the inner BREAK exits to the next outermost loop. First, all the statements after the end of the inner loop run, and then the next outermost loop restarts.
Examples
A. Use BREAK and CONTINUE with nested IF...ELSE and WHILE

In this example, if the average price is less than $30, the WHILE loop doubles the prices and then selects the maximum price. If the maximum price is less than or equal to $50, the WHILE loop restarts and doubles the prices again. This loop continues doubling the prices until the maximum price is greater than $50, and then exits the WHILE loop and prints a message.
USE pubs GO WHILE (SELECT AVG(price) FROM titles) < $30 BEGIN UPDATE titles SET price = price * 2 SELECT MAX(price) FROM titles IF (SELECT MAX(price) FROM titles) > $50 BREAK ELSE CONTINUE END PRINT 'Too much for the market to bear'
B. Using WHILE within a procedure with cursors

The following WHILE construct is a section of a procedure named count_all_rows. For this example, this WHILE construct tests the return value of @@FETCH_STATUS, a function used with cursors. Because @@FETCH_STATUS may return -2, -1, or 0, all three cases must be tested. If a row is deleted from the cursor results since the time this stored procedure was executed, that row is skipped. A successful fetch (0) causes the SELECT within the BEGIN...END loop to execute.
USE pubs DECLARE tnames_cursor CURSOR FOR SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES OPEN tnames_cursor DECLARE @tablename sysname --SET @tablename = 'authors' FETCH NEXT FROM tnames_cursor INTO @tablename WHILE (@@FETCH_STATUS <> -1) BEGIN

IF (@@FETCH_STATUS <> -2) BEGIN SELECT @tablename = RTRIM(@tablename) EXEC ('SELECT ''' + @tablename + ''' = count(*) FROM ' + @tablename ) PRINT ' ' END FETCH NEXT FROM tnames_cursor INTO @tablename END CLOSE tnames_cursor DEALLOCATE tnames_cursor

CHARINDEX
Returns the starting position of the specified expression in a character string.
Syntax

CHARINDEX ( expression1 , expression2 [ , start_location ] )


Arguments

expression1 Is an expression containing the sequence of characters to be found. expression1 is an expression of the short character data type category. expression2 Is an expression, usually a column searched for the specified sequence. expression2 is of the character string data type category. start_location Is the character position to start searching for expression1 in expression2. If start_location is not given, is a negative number, or is zero, the search starts at the beginning of expression2.
Return Types

int
Remarks

If either expression1 or expression2 is of a Unicode data type (nvarchar or nchar) and the other is not, the other is converted to a Unicode data type. If either expression1 or expression2 is NULL, CHARINDEX returns NULL when the database compatibility level is 70 or later. If the database compatibility level is 65 or earlier, CHARINDEX returns NULL only when both expression1 and expression2 are NULL. If expression1 is not found within expression2, CHARINDEX returns 0.
Examples

The first code example returns the position at which the sequence "wonderful" begins in the notes column of the titles table. The second example uses the optional start_location parameter to begin looking for wonderful in the fifth character of the notes column. The third example shows the result set when expression1 is not found within expression2.
USE pubs GO SELECT CHARINDEX('wonderful', notes) FROM titles WHERE title_id = 'TC3218' GO -- Use the optional start_location parameter to start searching -- for wonderful starting with the fifth character in the notes -- column. USE pubs GO SELECT CHARINDEX('wonderful', notes, 5) FROM titles WHERE title_id = 'TC3218' GO

Here is the result set for the first and second queries:

----------46 (1 row(s) affected) USE pubs GO SELECT CHARINDEX('wondrous', notes) FROM titles WHERE title_id='TC3218' GO

Here is the result set.


----------0

(1 row(s) affected)

ALL
Compares a scalar value with a single-column set of values.
Syntax

scalar_expression { = | <> | != | > | >= | !> | < | <= | !< } ALL ( subquery )
Arguments

scalar_expression Is any valid Microsoft SQL Server expression. { = | <> | != | > | >= | !> | < | <= | !< } Is a comparison operator. subquery Is a subquery that returns a result set of one column. The data type of the returned column must be the same data type as the data type of scalar_expression. Is a restricted SELECT statement (the ORDER BY clause, the COMPUTE clause, and the INTO keyword are not allowed).
Return Types

Boolean
Result Value

Returns TRUE when the comparison specified is TRUE for all pairs (scalar_expression, x) where x is a value in the single-column set; otherwise returns FALSE.

CASE
Evaluates a list of conditions and returns one of multiple possible result expressions. CASE has two formats: The simple CASE function compares an expression to a set of simple expressions to determine the result. The searched CASE function evaluates a set of Boolean expressions to determine the result. Both formats support an optional ELSE argument.
Syntax

Simple CASE function: CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END

Searched CASE function: CASE WHEN Boolean_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END
Arguments

input_expression Is the expression evaluated when using the simple CASE format. input_expression is any valid Microsoft SQL Server expression. WHEN when_expression Is a simple expression to which input_expression is compared when using the simple CASE format. when_expression is any valid SQL Server expression. The data types of input_expression and each when_expression must be the same or must be an implicit conversion. n Is a placeholder indicating that multiple WHEN when_expression THEN result_expression clauses, or multiple WHEN Boolean_expression THEN result_expression clauses can be used. THEN result_expression Is the expression returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid SQL Server expression. ELSE else_result_expression Is the expression returned if no comparison operation evaluates to TRUE. If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. else_result_expression is any valid SQL Server expression. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion. WHEN Boolean_expression Is the Boolean expression evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression.
Result Types

Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. For more information, see Data Type Precedence.
Result Values
Simple CASE function:

Evaluates input_expression, and then, in the order specified, evaluates input_expression = when_expression for each WHEN clause. Returns the result_expression of the first (input_expression = when_expression) that evaluates to TRUE. If no input_expression = when_expression evaluates to TRUE, SQL Server returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified. Evaluates, in the order specified, Boolean_expression for each WHEN clause. Returns result_expression of the first Boolean_expression that evaluates to TRUE. If no Boolean_expression evaluates to TRUE, SQL Server returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

Searched CASE function:

Examples
A. Use a SELECT statement with a simple CASE function

Within a SELECT statement, a simple CASE function allows only an equality check; no other comparisons are made. This example uses the CASE function to alter the display of book categories to make them more understandable.
USE pubs GO SELECT Category = CASE type WHEN 'popular_comp' THEN 'Popular Computing' WHEN 'mod_cook' THEN 'Modern Cooking' WHEN 'business' THEN 'Business' WHEN 'psychology' THEN 'Psychology' WHEN 'trad_cook' THEN 'Traditional Cooking' ELSE 'Not yet categorized' END, CAST(title AS varchar(25)) AS 'Shortened Title', price AS Price FROM titles WHERE price IS NOT NULL ORDER BY type, price COMPUTE AVG(price) BY type GO

Here is the result set:

Category ------------------Business Business Business Business

Shortened Title ------------------------You Can Combat Computer S Cooking with Computers: S The Busy Executive's Data Straight Talk About Compu

Price -------------------------2.99 11.95 19.99 19.99 avg ========================== 13.73

B. Use a SELECT statement with simple and searched CASE function

Within a SELECT statement, the searched CASE function allows values to be replaced in the result set based on comparison values. This example displays the price (a money column) as a text comment based on the price range for a book.
USE pubs GO SELECT 'Price Category' = CASE WHEN price IS NULL THEN 'Not yet priced' WHEN price < 10 THEN 'Very Reasonable Title' WHEN price >= 10 and price < 20 THEN 'Coffee Table Title' ELSE 'Expensive book!' END, CAST(title AS varchar(20)) AS 'Shortened Title' FROM titles ORDER BY price GO

Here is the result set:

Price Category --------------------Not yet priced Not yet priced Very Reasonable Title Very Reasonable Title Very Reasonable Title Very Reasonable Title Coffee Table Title

Shortened Title -------------------Net Etiquette The Psychology of Co The Gourmet Microwav You Can Combat Compu Life Without Fear Emotional Security: Is Anger the Enemy?

C. Use CASE with SUBSTRING and SELECT

This example uses CASE and THEN to produce a list of authors, the book identification numbers, and the book types each author has written.
USE pubs SELECT SUBSTRING((RTRIM(a.au_fname) + ' '+ RTRIM(a.au_lname) + ' '), 1, 25) AS Name, a.au_id, ta.title_id, Type = CASE WHEN SUBSTRING(ta.title_id, 1, 2) = 'BU' THEN 'Business' WHEN SUBSTRING(ta.title_id, 1, 2) = 'MC' THEN 'Modern Cooking' WHEN SUBSTRING(ta.title_id, 1, 2) = 'PC' THEN 'Popular Computing' WHEN SUBSTRING(ta.title_id, 1, 2) = 'PS' THEN 'Psychology' WHEN SUBSTRING(ta.title_id, 1, 2) = 'TC' THEN 'Traditional Cooking' END FROM titleauthor ta JOIN authors a ON ta.au_id = a.au_id

Here is the result set:


Name ------------------------Johnson White Marjorie Green Marjorie Green au_id ----------172-32-1176 213-46-8915 213-46-8915 title_id -------PS3333 BU1032 BU2075 Type ------------------Psychology Business Business

Using SUBSTRING
The SUBSTRING function returns a portion of either a character or binary string, or a text string, and takes three parameters: A character or binary string, a column name, or a string-valued expression that includes a column name. The position at which the substring should begin.

The length (in number of characters, or in number of bytes for binary) of the string to be returned. This example displays the first initial and last name of each employee, for example, A Fuller:
USE Northwind SELECT SUBSTRING(FirstName, 1, 1), LastName FROM Employees SELECT x = SUBSTRING('abcdef', 2, 3) x ---------bcd (1 row(s) affected

This example displays the second, third, and fourth characters of the string constant abcdef:

You might also like