Sei sulla pagina 1di 98

MARK KUSMA NOVEMBER 10, 2004 DEVELOP APPLICATIONS WITH ASE EXPRESS EDITION FOR LINUX

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

AGENDA Contd. Function Categories Date, Math, String, Aggregate Programming Batches, Comments Programming with variables Programming with Control-of-flow Statements November 8, 2004

INTRODUCTION TO T-SQL Transact-SQL was created by Sybase for use with ASE Includes all ANSI SQL elements ANSI 89 & 92 Compliant Used for database and server management tasks T-SQL Extensions (to the ANSI Standards) Stored Procedures (System and User) Functions (System/Arithmetic/String/Datetime) Triggers Rule and Default Objects Global and Local Variables Flow Control Statements (if else, while) November 8, 2004

INTRODUCTION TO T-SQL T-SQL is a Superset of ANSI SQL fipsflagger Set on to be warned set fipsflagger on isql -F Statement still executes Federal Information Processing Standard T-SQL ANSI SQL November 8, 2004

INTRODUCTION TO T-SQL - sprocs System Stored Procedures are stored procedures defined by Sybase and delivered as part of ASE sp_help provides information about all the objects in a given database sp_who provides information about the users of ASE sp_helpdb provides information about defined databases All system stored procedures start with sp_ November 8, 2004

INTRODUCTION TO T-SQL - isql isql A command-line program Available for Windows and Unix platforms Many option flags available. See Utility Guide for info. SQL Batches A set of SQL statements that are submitted and executed as a group. Terminated by the keyword go select * from sysdatabases select name from sysobjects where type = U go November 8, 2004

INTRODUCTION TO T-SQL - isql Database Context A session is always in one of the databases Which database is the current database? select db_name( select db_name() is a Transact-SQL Extension Change to a different database use tempdb Make a mistake in a SQL statement? Use reset to reset the buffer and return a 1> prompt Use vi on Unix, edit on Windows -E option can be used to override default editor To issue a command to the OS, use !! !!date November 8, 2004

INTRODUCTION TO T-SQL - isql November 8, 2004

INTRODUCTION TO T-SQL - jisql jisql A Java-based GUI program Available for Windows and Unix platforms SQL Batches A set of SQL statements that are submitted and executed as a group. Terminated by the keyword go , or clicking Go button Database Context Can be confusing due to dropdown showing database name Recommend using the dropdown to change current database, except for scripts November 8, 2004

INTRODUCTION TO T-SQL - jisql November 8, 2004

INTRODUCTION TO T-SQL - jisql Notice the dropdown vs. actual db Previous batch Next Batch history November 8, 2004

INTRODUCTION TO T-SQL - jisql Menu bar Explore the options Create connection to same server, or another Save to file (input, output, history), Read batch from file Print results Other stuff November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

CREATING TABLES Naming tables Currently, most objects, including tables, are limited to names of 30 characters or less This is changing in 15.0 (Galaxy release) First character must be alphabetic or underscore (_) Remaining chars can be alpha, numeric, of any of these symbols: $, #, @, _, (pound), or (yen) The name cannot be a T-SQL keyword November 8, 2004

CREATING TABLES Column Datatypes fall into categories Exact numeric tinyint (T-SQL Extension), smallint, int, numeric(p,s), decimal(p,s) Approximate numeric float, double, real rounding may occur Money money, smallmoney four decimal places Date and Time date*, time*, datetime, smalldatetime Character (n)char**, (n)varchar**, text, unichar, univarchar Binary bit, binary, varbinary, image User-defined types based on a system type Notes * - New in ASE 12.5.2 ** Use n version for national strings (multibyte characters) November 8, 2004

CREATING TABLES User-defined types T-SQL Extension Can be used to ensure consistency of multiple columns that store the same set of values sp_addtype <name>,<datatype>[,column_property] sp_addtype typ_ch_zip_code, char(5) create table addresses ( billing_zip_code typ_ch_zip_code not null, shipping_zip_code typ_ch_zip_code not null, ) November 8, 2004

CREATING TABLES Columns can have one of three properties NULL Represents an unknown value For numerics, NULL does not equal 0 For chars, NULL does not equal (blank) It is not less than, greater than, or equal to any other value Two NULL values are not considered to be equal to one another NOT NULL ASE will require a value for this column during inserts This is the ASE default, which differs from the ANSI standard IDENTITY Assigns a system-generated value to uniquely identify the row May not be sequential across all rows (there may be gaps) Excellent resource for this at: www.sypron.nl/idgaps.html November 8, 2004

CREATING TABLES Server page size A page is the basic unit of ASE storage A page may be 2K (default), 4K, 8K, or 16K in size This is a server-wide setting A table consists of a series of pages Why use a larger page size? Except for text and image, a row must fit completely on a single page. If the row is large, you need a larger page size. Storing large Java objects Why not to use a larger page size? Increased memory requirement Wasted disk space for small tables November 8, 2004

CREATING TABLES Defining column defaults Specifies a value for a specific column if no value is supplied during the insert operation Examples create table abc ( account numeric(8,0) identity not null, name char(30) not null, city char(30) default Boston not null, state char(2) default MA not null, create_date datetime default getdate() not null, userid char(30) default suser_name() not null) go November 8, 2004

CREATING TABLES Example (continued) insert into abc(name) values( XYZ Corp ) go select * from abc go account name city state create_date userid ----------- ------------------------------ -------------------------- -------------------------- -----------------------1 XYZ Corp Boston MA Oct 27 2004 10:34PM sa November 8, 2004

CREATING TABLES An alternative way to create a table If you already have a table and would like to create another with the same column definitions, use select into select * into my_copy from source_table To capture a subset of the columns, replace * with names select col1, col2 into my_copy from source_table These also copy the data to the new table To skip the data copy, use an empty where clause select * into my_copy from source_table where 1=0 Default rules are not copied to the new table Indexes are not created on the new table The database option select into/bulkcopy/pllsort must be on in this database to use select into November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

QUERYING DATA IN TABLES The basic select statements select * from table1 select col1, col2 from table1 Renaming column headings (two ways) select col1 as Account Number from acct_table (SQL-89) select Account Number = col1 from acct_table (T-SQL Ext) Account Number 123428 383838 November 8, 2004

QUERYING DATA IN TABLES Ordering result sets with order by clause ASE does not require columns in the order by clause to be in the select list select col1, col2 from table1 order by col3 In ANSI standards, the columns in the order by must be in the select list select col1, col2, col3 from table1 order by col3 Order by defaults to Ascending (ASC) order, can use DESC for Descending Can also specify column number in result set Useful for un-named columns select price * 0.10, name from products order by 1, name Orders by 10% of the price first, name second November 8, 2004

QUERYING DATA IN TABLES Wildcards in the where clause % Replaces one or more characters where city like B% _ Replaces a single character where state like M_ [ ] Represents a single character in the set where zip like 1870[0-9] Includes all 1870x zip codes where name like [D-H]% Find all rows where name starts with the letter D, E, F, G, or H [^] Represents a single character where zip like 1870[^13579] Eliminates odd numbered zip codes starting with 1870x November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

AGGREGATE FUNCTIONS The compute clause A T-SQL Extension that provides a single value at the end of the result set You want to know salaries and total salary expense select emp_name,salary from emps compute sum(salary) go emp_name salary ------------------------------ ---------------------Joe Employee 40,000.00 Susan Workshard 60,000.00 Stan Theman 45,000.00 Compute Result: ---------------------145,000.00 (4 rows affected) November 8, 2004

AGGREGATE FUNCTIONS With the exception of count(*), NULL values are skipped Use the isnull function to specify a value for NULL insert emps values('Short Timer',NULL) go select avg(salary) from emps go 48,333.33 select avg(isnull(salary,0)) from emps go 36,250.00 November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

THE case STATEMENT The case expression is a T-SQL Extension that can be used anywhere an expression can be used In practice, it is typically used in select and update stmts Allows for conditional return of a value update employees set salary case job_code when A01 then salary * 1.05 when E01 then salary * 1.10 else salary * 1.03 end go If no else statement and no match, then returns NULL November 8, 2004

THE case STATEMENT The case expression can also be used with conditions update employees set salary = case when job_code = 'A01' and salary < 30000 then salary * 1.05 when job_code = 'A01' and salary >= 30000 then salary * 1.04 else salary end go Provides a variable percent raise to those in job_code A01 only, based on current salary The else clause retains the current salary for other job_codes. Without it, they would be NULL (if nulls allowed). November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

TEMPORARY TABLES A temporary table is a table that is eventually dropped by the server, even if no drop table statement is executed Two types of temporary tables Shareable Session-specific All temp tables are stored in either the system tempdb or a user-created tempdb November 8, 2004

TEMPORARY TABLES Uses for a temporary table By a user Hold the results of queries that are too complex for a single query Hold the intermediate work of a stored procedure By the system Hold the intermediate results of a query that requires ordering or elimination of non-distinct values (work tables) Hold the intermediate results of a query that has an aggregate or computed column November 8, 2004

TEMPORARY TABLES Shareable Temporary Tables Created explicitly in a tempdb database Example use tempdb go create table temp_table . Example create table tempdb..temp_table . Accessible to any user Table exists until one of the following Table is explicitly dropped with drop table Server is rebooted November 8, 2004

TEMPORARY TABLES Session-specific Temporary Tables Created by prefixing the table name with create table #temp_table . Accessible only by the session that created it Exists in the assigned tempdb until one of the following Table is explicitly dropped via drop table The session ends (user is disconnected from the server) The stored procedure that created it finishes Table names should be 13 characters or less November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

SYSTEM TABLES A system table is a table created and maintained by the server that stores information about the server or one of its databases Examples of system tables sysobjects One row for each table, view, rule, default, procedure, etc in the database sysmessages One row for each message used by the server System tables start with the letters sys Some system tables exist in every database The master database contains some extra system tables November 8, 2004

SYSTEM TABLES Query system tables just like any other tables select name from sysobjects where type = V Lists the name of all Views in the current database CAUTION: Making direct modifications to system tables can result in poor performance, loss of data, or severe corruption of the entire system In order to make changes to system tables, you need to tell the server this is OK sp_configure allow updates to system tables , Be sure to disable this when changes are done November 8, 2004

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

FUNCTIONS A function is an operation that manipulates data in a specific way Terminology Argument Value or expression passed to the function Result Value returned by the function Argument Function Result Kusma KUSMA upper() November 8, 2004

FUNCTIONS Functions can be used in select lists select upper(type) from titles select db_name( where clauses select title from titles where lower(title) like Wherever an expression is allowed November 8, 2004

%the%

AGENDA Introduction to Transact-SQL (T-SQL) Extensions & System Procedures isql, jisql, Batches & System Stored Procedures Creating Tables Querying Data in Tables Aggregate Functions The case Statement Temporary Tables System Tables Functions Datatype Conversions November 8, 2004

DATATYPE CONVERSIONS Under many circumstances, ASE can compare two values of different datatypes Implicit conversion A conversion that ASE does automatically select title from titles where pubdate < Oct 29 2004 Explicit conversion A conversion using the convert function Unsupported conversion A conversion that cannot be done directly in ASE select title from titles where pubdate < total_sales Msg 206, Level 16, State 2: Line 1: Operand type clash: INT is incompatible with DATETIME November 8, 2004

DATATYPE CONVERSIONS Conversion summary int real money datetime char, varchar int n/a implicit implicit unsupported explicit real implicit n/a implicit unsupported explicit money implicit implicit n/a unsupported explicit datetime unsupported unsupported unsupported n/a implicit char, varchar explicit explicit explicit implicit n/a November 8, 2004

DATATYPE CONVERSIONS Explicit conversion The convert function changes values from one datatype to another convert(datatype, expression [,style] Convert a money value to char(10) select price from titles where convert(char(10),price) like Convert the default date format to another style select convert(char,getdate() Oct 29 2004 10:58PM select convert(char,getdate(),109) Oct 29 2004 10:58:49:113PM The list of convert styles can be found in the T-SQL User s Guide November 8, 2004

%.99

AGENDA Contd. Function Categories Date, Math, String, Aggregate Programming Batches, Comments Programming with variables Programming with Control-of-flow Statements November 8, 2004

FUNCTION CATEGORIES - DATE Date functions are T-SQL Extensions that manipulate datetime/date/time data getdate() Returns the current date and time datename() Returns the character form of the specified part of the supplied date datepart() Returns the numeric form of the specified part of the supplied date dateadd() Used to add or subtract some amount of time from a supplied date datediff() Used to determine the difference between two dates in a specific unit (days, weeks, hours, minutes, etc) November 8, 2004

FUNCTION CATEGORIES - DATE select getdate() Oct 31 2004 10:21PM select datename(mm,getdate()) October select datepart(mm,getdate()) 10 select dateadd(dd,-5,getdate()) Oct 26 2004 10:21PM select datediff(dd,'Jan 1 2004',getdate()) 304 November 8, 2004

FUNCTION CATEGORIES - MATH Mathematical functions are T-SQL Extensions that manipulate numeric data ceiling() Returns the next largest integer floor() Returns the next lowest integer rand() Returns a random number round() Returns a value rounded to x decimal places pi() Returns the value of pi See the T-SQL User s Guide for a complete list November 8, 2004

FUNCTION CATEGORIES - MATH select ceiling(123.4) 124 select floor(123.4) 123 select rand(34) 0.762558 .. sample value select round(123.4567,2) 123.4600 select pi() 3.141593 November 8, 2004

FUNCTION CATEGORIES - STRING String functions are T-SQL Extensions that manipulate character data substring() Returns a section of the specified string charindex() Returns the position of the character(s) in the string right() Returns the right-most x characters upper() Returns the string in uppercase ltrim() Removes the left-side spaces See the T-SQL User s Guide for a complete list November 8, 2004

FUNCTION CATEGORIES - STRING select substring('abcdefg',3,2) cd select charindex('cd','abcdefg') 3 select right('abcdefg',4) defg select upper('abcdefg') ABCDEFG select ltrim(' abcdefg') abcdefg November 8, 2004

FUNCTION CATEGORIES - STRING The + concatenation operator Similar in functionality to the string function Concatenates two or more strings together Example with literal values select Mr. + Mark Kusma Example with column values from a table select lname + , + fname as name from authors Note that || is the ANSI standard concatenation operator and is supported in ASE select Mr. || Mark Kusma November 8, 2004

FUNCTION CATEGORIES - AGGREGATE Aggregates are ANSI standard functions that perform mathematical operations on some or all values in a given column count, max, min, avg, sum Except for count(*), aggregates ignore NULL values count(column-name) is a T-SQL Extension We touched on aggregate functions earlier November 8, 2004

AGENDA Contd. Function Categories Date, Math, String, Aggregate Programming Batches, Comments Programming with variables Programming with Control-of-flow Statements November 8, 2004

PROGRAMMING Code can basically be executed in three locations Client App Server ASE Server Advantages of client-side programming Can easily serve users with vastly different needs Can distribute processor load to local environments Advantages of server-side programming Can ensure uniform application of business rules Can update code easier November 8, 2004

PROGRAMMING - BATCHES Batches Recall that a batch is a set of SQL executed together Restrictions on batches Certain statements must be in their own batch create default, create rule, create procedure, create trigger, declare cursor use <db> must be the last, or only, statement in a batch You cannot drop and recreate an object in the same batch You cannot bind a rule or default to a column and insert values into that column in the same batch If a stored procedure is not the first statement in the batch, it must be preceded with exec or execute November 8, 2004

PROGRAMMING - COMMENTS A comment is ignored by ASE during execution Comments are used to document information about the code Two ways to mark comments -- and end-of-line select name, age, -- this part is a comment Cannot wrap lines with a single comment /* and * select name, age, /* this part is a comment * Can be used for single- or multi-line comments This is a T-SQL Extension November 8, 2004

AGENDA Contd. Function Categories Date, Math, String, Aggregate Programming Batches, Comments Programming with variables Programming with Control-of-flow Statements November 8, 2004

PROGRAMMING WITH VARIABLES A Local Variable is a named location in memory defined by a user Typical uses for a local variable Facilitate repeated use of constant values Perform conditional branching in T-SQL code Return custom messages to the client that contain variable information Pass information to and from a stored procedure Avoid using a subquery November 8, 2004

PROGRAMMING WITH VARIABLES Rules for Local Variables Variable names must begin with @ Variables must have a system or user-defined datatype Any properties associated with the user-defined datatype are not inherited Any rules or defaults bound to a user-defined datatype are not inherited Variables are local to the batch, stored procedure, or trigger in which they are declared When the batch, stored procedure, or trigger terminates, the variable is dropped November 8, 2004

PROGRAMMING WITH VARIABLES Declaring Local Variables declare variable_name datatype [, .] declare @var1 int, @var2 char(10) Variables must be declared before they can be used When declared, the value of a local variable is set to NULL November 8, 2004

PROGRAMMING WITH VARIABLES To view the value of a local variable select @var1 declare @var1 int select @var1 NULL To assign a value to a local variable Assignment select using an expression Assignment select using a table value Assignment update November 8, 2004

PROGRAMMING WITH VARIABLES Assignment select and Expressions select @variable = expression [, .] declare @var1 int, @var2 char(2) select @var1 = 15, @var2 = AB Do not assign a variable a value and use that variable in the same select statement. You may get unexpected results. November 8, 2004

PROGRAMMING WITH VARIABLES Assignment select and Table values select @variable = column_name from declare @var1 int, @var2 char(2)

select @var1 = acct_id, @var2 = state from customers where name = Tom Smith No information is returned to the user Only the variables are updated with the values If more than one row is returned, the variables contain the values for the last row November 8, 2004

PROGRAMMING WITH VARIABLES Assignment update update table_name set @variable = expression declare @pub_name varchar(40) update publishers set @pub_name = pub_name where pub_id = 0736

No information is returned to the user If the update modifies multiple rows, only the last assigned value remains in the variable November 8, 2004

PROGRAMMING WITH VARIABLES Restrictions on local variables Variables can be used only in place of constants If an assignment select returns no values, the variable value remains unchanged If an assignment select returns multiple values, the variable retains the last value November 8, 2004

PROGRAMMING WITH VARIABLES A Global Variable is a named location in memory defined and maintained by ASE Rules for global variables Names start with @@ Cannot be created by users Cannot be assigned values by users Value assignment may be local to the server or to the connection Global variables are T-SQL Extensions November 8, 2004

PROGRAMMING WITH VARIABLES Commonly used global variables @@version Returns the server version string @@rowcount Returns the number of rows affected by the last statement @@error Returns the error number generated by the last statement @@identity Returns the value last inserted into an IDENTITY column by this session Complete list of global variables in the T-SQL User s Guide and Quick Reference Guide November 8, 2004

PROGRAMMING WITH VARIABLES Static SQL SQL whose text is specified when the application, script, or stored procedure is created The keywords and referenced objects are fixed at the time the statements are written All of the examples we ve seen so far are static SQL Dynamic SQL SQL whose text is specified at execution time The keywords and referenced objects are determined at the time the statement is executed November 8, 2004

PROGRAMMING WITH VARIABLES Executing T-SQL Dynamically exec[ute] ( {string constant | char_variable} declare @table_name varchar(30), @col_list varchar(30) select @table_name = publishers , @col_list = pub_name, state exec ( select + @col_list + go November 8, 2004 from + @table_name)

PROGRAMMING WITH VARIABLES Restrictions on dynamic SQL Variables used in the execute statement must be char or varchar Statements that cannot be executed dynamically exec or execute use Transaction control statements begin tran, commit tran, rollback tran, save tran create table statements that create temp tables Outside of the execute statement, you cannot use a variable where a keyword, object name, or table column is syntactically required Cannot use: select * from @table_name November 8, 2004

AGENDA Contd. Function Categories Date, Math, String, Aggregate Programming Batches, Comments Programming with variables Programming with Control-of-flow Statements November 8, 2004

CONTROL-OF-FLOW STATEMENTS By default, ASE executes statements in the order in which they appear T-SQL control-of-flow statements supersede the default flow of execution if else begin end if exists while break continue return goto November 8, 2004

CONTROL-OF-FLOW STATEMENTS if else allows for conditional execution of two or more branches delete from titles where type = mod_cook if @@error <> 0 select An error has occurred! else select The delete was successful. The condition in the if statement can contain an embedded select statement, but it must be in parentheses if (select avg(price) from titles) > $20

November 8, 2004

CONTROL-OF-FLOW STATEMENTS Nested else conditions You can embed an if statement into the else clause to create three or more branches declare @num_rows int delete from titles where type = "mod_cook" select @num_rows = @@rowcount if @num_rows = 0 select "No rows were deleted." else if @num_rows = 1 select "One row was deleted." else select "Multiple rows were deleted. November 8, 2004

CONTROL-OF-FLOW STATEMENTS begin end lets you define multiple statements as a block begin statement1 statement2 end if @temp_id = ABC begin select @temp_type = Cookbook delete from titles where type = @temp_type end November 8, 2004

CONTROL-OF-FLOW STATEMENTS if exists checks to see if data matching a given condition exists if [not] exists (select_statement) code_to_execute_when_true [else code_to_execute_when_false] if exists (select * from titles where price >= $50.00) update titles set price = price * $0.90 else print All titles priced under $50.00 Processing stops when the first matching row is found November 8, 2004

CONTROL-OF-FLOW STATEMENTS A useful application is to check if an object exists before attempting to create it if exists (select * from sysobjects where name = vw_authors and type = V ) drop view vw_authors go create view vw_authors as

November 8, 2004

CONTROL-OF-FLOW STATEMENTS while executes a set of statements repeatedly until a given condition becomes false while <condition> block_to_execute while (select avg(price) from titles) < $40 begin update titles set price = price + $2 end November 8, 2004

CONTROL-OF-FLOW STATEMENTS Beware of infinite while loops declare @price money select @price = price from titles where title_id = while @price < $30 begin update titles set price = price * $1.10 where title_id = PS1252 end

PS1252

Since the value of @price never gets updated after the initial value, this loop will never terminate November 8, 2004

CONTROL-OF-FLOW STATEMENTS break causes execution to exit the while loop while (select avg(price) from titles) > $20 begin update titles set price = price / if (select max(price) from titles) < $40 break end As long as the average price is above $20, this loop cuts all prices in half. If the maximum price falls below $40, the loop is terminated. November 8, 2004

CONTROL-OF-FLOW STATEMENTS continue causes execution to return to the top of the while loop while @price < $20 begin select @price = @price + $1.00 if (select count(price) from titles where price = @price) >= 5 continue else update titles set price = price * $1.10 where price = @price end If there are already 5 or more books at @price, we restart the loop, otherwise we raise the price by 10%. November 8, 2004

CONTROL-OF-FLOW STATEMENTS return causes execution to exit the batch or stored proc declare @avg_price money select @avg_price = avg(price) from titles if @avg_price < $10 return while @avg_price < $20 begin update titles set price = price * $1.05 select @avg_price = avg(price) from titles end November 8, 2004

CONTROL-OF-FLOW STATEMENTS Message statements return text information to users select print raiserror November 8, 2004

CONTROL-OF-FLOW STATEMENTS select is useful for returning information in the result set select The average price is too low. select The average price is , @avg_price select The average price is , avg(price) from titles Can return text, variable values, and table data in any combination November 8, 2004

CONTROL-OF-FLOW STATEMENTS print can be useful for returning debugging messages print There is no user by that name. print @temp_title_id Variables used directly by print must be char or varchar Arguments can be passed to the print statement print Table %1! is not owned by user %2! , @table, @user Placeholders must be of the form %n! n is an integer 1-20 Values of n are used sequentially Arguments can be any datatype except text or image They are temporarily converted to char November 8, 2004

CONTROL-OF-FLOW STATEMENTS raiserror is used for returning error messages in the message window raiserror 70500 Table %1! not found , @my_table raiserror returns two pieces of information Error number, which gets stored in @@error User-defined error message Error messages may or may not be reusable, depending on where they are specified If specified only in the raiserror statement not reusable If specified in sysusermessages table - reusable November 8, 2004

CONTROL-OF-FLOW STATEMENTS Returning non-reusable error messages raiserror error_num { error message | variable} [,arguments] raiserror 30250 The title does not exist. raiserror 30250 @no_title_text raiserror 70500 Table %1! not found. , @my_table raiserror 70500 @no_table_text, @my_table Message numbers must be 20000 or greater Technically, can be > 17000, but these are used by system stored procedures, so good practice to use 20000 or higher If a message is not stored in sysusermessages, then it must be stated every time it is used November 8, 2004

CONTROL-OF-FLOW STATEMENTS Creating reusable error messages sp_addmessage 30250, The title does not exist. sp_addmessage 70500, Table %1! not found. To drop a message sp_dropmessage 30250 Returning a reusable error message raiserror 30250 raiserror 70500, @my_table The message number must be in sysusermessages If the message contains placeholders, you must include the argument list November 8, 2004

WHAT S NEXT / HELP Next month is Part 3 of the Series Database Maintenance Basics Help is available Sybase supplied stored procedures can be great examples or starting points for your code Look in $SYBASE/ASE-12_5/scripts/installmaster Or use sp_helptext <sproc name> forums.sybase.com/sybase.public.ase.linux All ASE Linux versions discussed A support contract can be purchased November 8, 2004

SPROC EXAMINATION create procedure sp_who @loginame varchar(30) = NULL as declare declare declare declare declare @low int @high int @spidlow int @spidhigh int @len1 int, @len2 int, @len3 int

if @@trancount = 0 begin set chained off end set transaction isolation level 1 select @low = @@minsuid, @high = @@maxsuid, @spidlow = @@minspid, @spidhigh = @@maxspid November 8, 2004

SPROC EXAMINATION if @loginame is not NULL begin select @low = suser_id(@loginame), @high = suser_id(@loginame) if @low is NULL begin if @loginame like "[0-9]%" begin select @spidlow = convert(int, @loginame), @spidhigh = convert(int, @loginame), @low = 0, @high = @@maxsuid end else begin /* ** 17231, "No login with the specified name exists." */ raiserror 17231 return (1) end end end November 8, 2004

SPROC EXAMINATION select @len1 = max(datalength(suser_name(suid))), @len2 = max(datalength(db_name(dbid))), @len3 = max(datalength(suser_name(origsuid))) from master..sysprocesses where suid >= @low and suid <= @high and spid >= @spidlow and spid <= @spidhigh if (@len1 > 8 or @len2 > 6 or @len3 > 8) begin select fid,spid,status,loginame=suser_name(suid), origname=isnull(suser_name(origsuid), suser_name(suid)), hostname, blk_spid=convert(char(5),blocked), dbname=db_name(dbid),cmd, block_xloid from master..sysprocesses where suid >= @low and suid <= @high and spid >= @spidlow and spid <= @spidhigh order by fid,spid,dbname end November 8, 2004

SPROC EXAMINATION else begin select fid,spid,status,loginame=convert(char(12), suser_name(suid)), origname=convert(char(12),isnull(suser_name(origsuid), suser_name(suid))), hostname,blk_spid=convert(char(5),blocked), dbname=convert(char(10),db_name(dbid)), cmd, block_xloid from master..sysprocesses where suid >= @low and suid <= @high and spid >= @spidlow and spid <= @spidhigh order by fid,spid,dbname end return (0) go November 8, 2004

Potrebbero piacerti anche