This document provides a cheat sheet on SQL functions and commands for the Sybase System 11 database. It summarizes date, string, mathematical and other functions. It also lists commands for retrieving, modifying, inserting and deleting data, as well as useful stored procedures for obtaining database metadata and information.
This document provides a cheat sheet on SQL functions and commands for the Sybase System 11 database. It summarizes date, string, mathematical and other functions. It also lists commands for retrieving, modifying, inserting and deleting data, as well as useful stored procedures for obtaining database metadata and information.
Retrieve rows of data from table. select [all |distinct] select_list [into table_name] [from {table_name | view_name} [alias] [where search_conditions] [group by [all] aggregate_free_expression] [having search_conditions] [order by {col |col_no} [{ asc | desc}] [compute row_aggregate(column_name) [,…] [by column_name [,…]]] Add rows to a table. insert [into] {table_name | view_name} [(column_list)] {values (constant_expression [,…]) | select_statement } Modify rows in a table. update {table_name | view_name} set col_name1 = {expression | NULL | (select_statement)} [, col_name2 = {expression | NULL | (select_statement)}] [from {table_name | view_name} [,…]] [where search_conditions] Remove rows from a table. delete [from] table_name [from {table_name | view_name} [,…]] [where search_conditions] Drop a table. drop table table_name SQL Server Functions - Date Functions getdate() Returns the current system date and time. datename(datepart, date_expr) Returns a specific part of date_expr value as a string. datepart(datepart, date_expr) Returns a specific part of date_expr value as an integer. datediff(datepart, date_expr1, date_expr2) Returns date_expr2 – date_expr1 as measured by specific number of dateparts to date_expr. dateadd(datepart, number, date_expr) Returns the date produced by adding specified number of dateparts to date_expr. SQL Server Functions - String Functions Length and Parsing char_length(char_expr) Returns integer number of characters in char_expr, ignoring trailing spaces. substring(expression, start, length) Returns part of a string. right(char_expr, int_expr) Returns int_expr characters from right of char_expr. upper(char_expr) Converts char_expr to uppercase. lower(char_expr) Converts char_expr to lowercase. space(int_expr) Generates string of int_expr spaces. replicate(char_expr, int_expr) Repeats char_expr, int_expr times. stuff(char_expr1, start, length, char_expr2) Replaces length characters from expr1 at start with expr2. reverse(char_expr) Reverses text in char_expr. ltrim(char_expr) Removes leading spaces. rtrim(char_expr) Removes trailing spaces. Conversions ascii(char_expr) ASCII value of first character in char_expr. char(int_expr) ASCII code-to-character conversion. str(float_expr [, length [,decimal]]) Numeric-to-character conversion. soundex(char_expr) Returns soundex value of char_expr. difference(char_expr1, char_expr2) Returns difference between soundex values of expressions. charindex(char_expr, expression) Returns the starting position of the specified char_expr, else 0. patindex(“%pattern%”, expression) Returns the starting position of the specified pattern, else 0. SQL Server Functions - Mathematical Functions abs(numeric_expr) Absolute value of specified value. ceiling(numeric_expr) Smallest integer greater than or equal to the specified value. exp(float_expr) Exponential value of the specified value. floor(numeric_expr) Largest integer less that or equal to the specified value. pi() Returns the constant value of 3.1415926… power(numeric_expr, power) Returns the value of numeric_expr to the power of power. rand([int_expr]) Returns a random float number between 0 and 1, optionally using int_expr as a seed. round(numeric_expr, int_expr) Rounds off a numeric expression to the precision specified in int_expr. sign(int_expr) Returns the positive (+1), zero (0), or negative (-1). sqrt(float_expr) Returns the square root of the specified value. SQL Server Functions - Row Aggregate Functions sum([all | distinct] expression) The total of the (distinct) non-null values in the numeric column. avg([all | distinct] expression) The average of the (distinct) non-null values in the numeric column. count([all | distinct] expression) The number of (distinct) non-null values in the column. count(*) The number of select rows. max(expression) The highest value in the expression. min(expression) The lowest value in the expression. isnull(expr1, expr2) Replaces expr1, if null, with expr2. SQL Server Functions – Access and Security Information host_id() Current host process ID number of client process. host_name() Current host computer name of the client process. suser_id([“login_name”]) User’s SQL Server ID number. suser_name([server_user_id]) User’s SQL Server login name. user_id([“name_in_db”]) User’s ID number in database. user_name([user_id]) User’s name in the database. user User’s name in the database. show_role() Current active roles for user. valid_user(login_id) Returns 1 if specified login_id is a valid user or alias in at least one database. SQL Server Functions – Database and Object Information db_id([“db_name”]) Database ID number. db_name([db_id]) Database name. object_id(“objname”) Database object ID number. object_name(obj_id [, db_id]) Database object name. col_name(obj_id, col_id) Column name of column. col_length(“objname”, “colname”) Length of column. index_col(“objname”, index_id, key #) Indexed column name. valid_name(char_expr) Returns 0 if char_expr is not a valid identifier. curunreservedpgs(db_id, lstart, unreservedpgs) Used in query against sysusages; returns number of free pages on device fragment. data_pgs(object_id, {doampg | ioampg}) Number of data pages used by table (doampg) or index (ioampg). reserved_pgs(object_id, {doampg | ioampg}) Number of reserved pages for a table(doampg) or index (ioampg). rowcnt(doampg) Number of rows in a table. used_pgs(object_id, doampg, ioampg) Total number of pages used by a table and its clustered index. SQL Server Functions – Data Functions datalength(expression) Returns length of expression in bytes. tsequal(timestamp1, timestamp2) Compares timestamp values; returns error if timestamp vales do not match. convert(datatype, expression,[format]) Converts expression to datatype. Format specifies the display format for datetime values when converted to character string. Useful System Stored Procedures Display information about an object. sp_help{type_name | procedure_name| table_name | view_name | rule_name | default_name} List all referenced objects. sp_depends {trigger_name | procedure_name} List all triggers and stored procedures. sp_depends {table_name | view_name} View current locks. sp_lock [spid] View current process. sp_who [login_name | spid] List databases. sp_helpdb [db_name] Display keys. sp_helpkey table_name Transact SQL Programming Constructs - Generate Messages Print a text string. Print {“character_string” | @variable | @@global_variable} [, arglist] Raise an error message. Raiserror error_number {character_string | @varibale} [, arglist]
Compiled by Scott M Ferguson on 05/23/02
Sybase System 11 SQL Cheat Sheet
Transact SQL Programming Constructs – Flow Control
Insert a multiple line comment. /* Comment */ Single line comment. -- Exit a batch. return Exit a stored procedure. return [return_status] Declare a local variable. Declare @variable_name datatype [, …] Set a local variable. Select @variable_name = expression [, …] [from … [where …]] Evaluate a condition. if boolean_expression {statement | statement block} [else {statement | statement block}] Check for existence of rows. if [not] exists (select_statement) {statement | statement block} [else {statement | statement block}] Create a statement block with if or while. begin SQL_Statements end Execute repeatedly. While boolean_condition {statement | statement_block} Restart while loop. continue Exit while loop. break Declare a label execute from. goto label A labeled spot label: Wait for an event. waitfor {delay “time” | time “time” | errorexit | processexit | mirrorexit} Modify the environment. Set condition {on | off | value} Transact SQL Programming Constructs - Stored Procedures Create a procedure create proc procedure_name [; number] [(@parm_name datatype = default_value [output] [,…])] [with recompile] as SQL_Statements [return [integer_status_value]] Execute a procedure [exec[ute]] [@status =] procedure_name [; number] [[@parm_name =] expression [output][,…]] Transact SQL Programming Constructs - Cursors Define the query for a cursor. declare cursor_name cursor for Select select_list from {table_name | view_name} [holdlock | noholdlock] [shared] [,…] [for {read only | update [ of column_name_list]}] Execute query and set row pointer to 1st row. open cursor_name Set the number of rows for a fetch. set cursor rows num_rows for cursor_name Retrieve a row or rows. Fetch cursor_name [ into variable_list] Stop a cursor processing and release locks. close cursor_name Release cursor name and resources. deallocate cursor cursor_name Data Types, Formats, and Date Parts Date Parts Date Part Abbreviation Value Range Year yy 1753-9999 Quarter qq 1-4 Month mm 1-12 Day Of Year dy 1-366 Day dd 1-31 Week wk 1-54 Week Day dw 1-7 (1 = Sunday) Hour hh 0-23 Minute mi 0-59 Second ss 0-59 Millisecond ms 0-999
Date Conversion Formats Value Format of Date in Converted String
0 or 100 mon dd yyyy hh:mi AM 1 or 101 mm/dd/yy 2 or 102 yy.mm.dd 3 or 103 dd/mm/yy 4 or 104 dd.mm.yy 5 or 105 dd-mm-yy 6 or 106 dd mon yy 7 or 107 mon dd, yy 8 or 108 hh:mm:ss 9 or 109 mon dd, yyyy hh:mi:ss:ms AM 10 or 110 mm-dd-yy 11 or 111 yy/mm/dd 12 or 112 yymmdd
Data Types Data Type Range of Values Size in Bytes Example
char[(n)] 1 <= n <= 255 n (default is 1) ‘Scott’ varchar[(n)] 1 <= n <= 255 data length ‘123 Elm St.’ text BLOB Up to 2147483647 bytes 16 + multiple of 2k ‘Scott’ binary(n) 1 <= n <= 255 n 0xa1b3 varbinary(n) 1 <= n <= 255 n + 1 0xf1 image BLOB up to 2147483647 bytes 16 + multiple of 2k 0xf1. . . datetime 01/01/1753 to 12/31/9999 8 ‘Jul 4, 1972 14:47:00.000’ smalldatetime 01/01/1990 to 06/06/2079 4 ‘Jul 4, 1998 15:30:00’ bit 0 or 1 1 1 int(integer) + or – 2147483647 4 123456 smallint + or – 32767 2 2134 tinyint 0 to 255 1 30 float[(precision)] machine dependent 4 or 8 123.1234567 numeric(p,s) + or – 10 to the 38th power 2 through 17 12345.123 p is precision (total digits) s is scale (decimal digits) decimal(p,s) same as numeric money + or - $922,337,203,685,447.5807 8 $150,235.56 smallmoney + or _ $214,748.3647 4 $25,078.23 KEY {} Indicates that you must choose at least one of the enclosed options. [] The value / keyword is optional. () Parentheses are part of the command. | Indicates that you can select only one of the options shown. , Indicates that you can select as many of the options shown, separated by commas. expression An expression that returns a single value; may be restricted to one of the following types: char_expression, constant_expression, float_expression, integer_expression, numeric_expression, binary_expression. … Indicates the previous option can be repeated.