Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

Intro to tsql unit 11

666 visualizaciones

Publicado el

Publicado en: Tecnología
  • Sé el primero en comentar

  • Sé el primero en recomendar esto

Intro to tsql unit 11

  1. 1. Introduction To SQL Unit 11 Modern Business Technology Introduction To TSQL Unit 11 Developed by Michael Hotek
  2. 2. Batches <ul><li>Most SQL statements have the ability to be run as batches </li></ul><ul><li>A batch is nothing more than a group of SQL statements executed at the same time </li></ul><ul><li>The batch is submitted and processed by the server </li></ul><ul><li>If there is an error in any statement in the batch, the entire batch is rejected </li></ul>
  3. 3. Batches <ul><li>select title from titles </li></ul><ul><li>select au_lname from authors </li></ul><ul><li>select stor_name from stores </li></ul><ul><li>title </li></ul><ul><li>-------------------------------------------------------------------------- </li></ul><ul><li>The Busy Executive's Database Guide </li></ul><ul><li>Cooking with Computers: Surreptitious Balance Sheets </li></ul><ul><li>You Can Combat Computer Stress! </li></ul><ul><li>Straight Talk About Computers </li></ul><ul><li>Silicon Valley Gastronomic Treats </li></ul><ul><li>The Gourmet Microwave </li></ul><ul><li>The Psychology of Computer Cooking </li></ul><ul><li>But Is It User Friendly? </li></ul><ul><li>... </li></ul><ul><li>(18 row(s) affected) </li></ul><ul><li>au_lname </li></ul><ul><li>---------------------------------------- </li></ul><ul><li>White </li></ul><ul><li>Green </li></ul><ul><li>Carson </li></ul><ul><li>O'Leary </li></ul><ul><li>Straight </li></ul><ul><li>... </li></ul><ul><li>(23 row(s) affected) </li></ul><ul><li>stor_name </li></ul><ul><li>---------------------------------------- </li></ul><ul><li>Eric the Read Books </li></ul><ul><li>Barnum's </li></ul><ul><li>.. </li></ul><ul><li>(6 row(s) affected) </li></ul>
  4. 4. Batch Restrictions <ul><li>Some SQL statements can not be combined with others in a batch </li></ul><ul><ul><li>use </li></ul></ul><ul><ul><li>create rule </li></ul></ul><ul><ul><li>create default </li></ul></ul><ul><ul><li>create trigger </li></ul></ul><ul><ul><li>declare cursor </li></ul></ul><ul><li>An object can not be dropped and recreated in the same batch </li></ul><ul><li>Stored procedures in a batch must be preceded by an exec or execute unless they are the first statement </li></ul>
  5. 5. Comments <ul><li>You can add comments to any of your SQL batches to improve readability and also to document the batch </li></ul><ul><li>The are two ways to comment in SQL Server: /*…*/ and -- </li></ul><ul><li>/* The comments included between these delimiters can span multiple lines*/ </li></ul><ul><li>--The double hyphen must precede every </li></ul><ul><li>--line of your comment </li></ul>
  6. 6. Datatypes <ul><li>All pieces of data in a database have a specific datatype </li></ul><ul><li>Each column is defined as being of a specific datatype </li></ul><ul><li>This means that if a column is defined an integer datatype, you will not be able to enter alphabetic characters into it </li></ul>
  7. 7. Datatypes <ul><li>The common datatypes in SQL Server, and most DBMSs, are: </li></ul><ul><ul><li>char fixed width alphanumeric data </li></ul></ul><ul><ul><li>varchar variable width alphanumeric data </li></ul></ul><ul><ul><li>integer whole number values </li></ul></ul><ul><ul><li>datetime Date and time values </li></ul></ul><ul><li>The main difference in char and varchar columns is in the amount of storage space they require </li></ul><ul><li>A varchar is also not space padded </li></ul><ul><li>Examples: </li></ul><ul><li>Refer to the data model </li></ul>
  8. 8. Variables <ul><li>Variables in SQL can have one of two scopes, local or global </li></ul><ul><li>All of the variables you will create will be local in scope </li></ul><ul><li>Global variables are reserved for use by SQL Server and can not be assigned values by the user </li></ul>
  9. 9. Local Variables <ul><li>Local variables are: </li></ul><ul><ul><li>User defined </li></ul></ul><ul><ul><li>Created using declare </li></ul></ul><ul><ul><li>Have a name and datatype </li></ul></ul><ul><ul><li>Can be assigned values by the user </li></ul></ul><ul><ul><li>Are initialize to null when created </li></ul></ul><ul><ul><li>Are confined to the batch, stored procedure, or trigger they are declared in </li></ul></ul><ul><li>declare @variable_name datatype </li></ul><ul><li>declare @mmyvar char(10) </li></ul>
  10. 10. Local Variables <ul><li>Variable names must be preceded by an @ symbol, can be up to 30 characters in length, and can not be reserved words </li></ul><ul><li>To assign values to a variable, use a select </li></ul><ul><ul><li>select @variable = expression [,@variable = expression]… </li></ul></ul><ul><ul><li>[from…] </li></ul></ul><ul><ul><li>[where…]… </li></ul></ul><ul><li>declare @myvar int </li></ul><ul><li>select @myvar = 42 </li></ul>
  11. 11. Local Variables <ul><li>You can assign constants, values from a table, or an expression to a variable </li></ul><ul><li>Variables are scalar; they contain exactly one value </li></ul><ul><li>They can only be used in place of constants </li></ul><ul><li>They can not be used in place of table names, column names, or other database objects </li></ul>
  12. 12. Local Variables <ul><li>If no values are returned by the assignment select, the variable remains unchanged </li></ul><ul><li>If more than one value is returned by the assignment select, the last value is stored in the variable </li></ul><ul><li>An assignment select does not return any data to the user </li></ul><ul><li>To return the value of a variable to a user, use a select on the variable </li></ul>
  13. 13. Local Variables <ul><li>declare @myvar int </li></ul><ul><li>select @myvar = 42 </li></ul><ul><li>select @myvar </li></ul><ul><li>-------- </li></ul><ul><li>42 </li></ul><ul><li>declare @sales money </li></ul><ul><li>select @sales = price*ytd_sales from titles where title_id = 'BU1032' </li></ul><ul><li>select @sales </li></ul><ul><li>(1 row(s) affected) </li></ul><ul><li>-------------------------- </li></ul><ul><li>81,859.05 </li></ul><ul><li>(1 row(s) affected) </li></ul>
  14. 14. Local Variables <ul><li>declare @myvar int --@myvar is null </li></ul><ul><li>select @myvar = 1 --@myvar is 1 </li></ul><ul><li>select @myvar = ytd_sales from titles where title_id = '99999' </li></ul><ul><li>--row does not exists </li></ul><ul><li>--@myvar is still 1 </li></ul><ul><li>select @myvar = ytd_sales from titles where title_id = 'BU1032' </li></ul><ul><li>--row does exist </li></ul><ul><li>select @myvar </li></ul><ul><li>(1 row(s) affected) </li></ul><ul><li>(0 row(s) affected) </li></ul><ul><li>(1 row(s) affected) </li></ul><ul><li>----------- </li></ul><ul><li>4095 </li></ul><ul><li>(1 row(s) affected) </li></ul>
  15. 15. Local Variables <ul><li>Local variables are used for a variety of things in SQL Server </li></ul><ul><ul><li>Perform conditional branching based on a variable's value </li></ul></ul><ul><ul><li>Pass values to and from stored procedures </li></ul></ul><ul><ul><li>Eliminate the need to use subqueries for aggregates </li></ul></ul><ul><ul><li>Reuse of constants throughout a batch </li></ul></ul><ul><ul><li>Return custom messages to the user </li></ul></ul>
  16. 16. Common Errors <ul><li>declare @myvar int </li></ul><ul><li>select @myvar = 'This is an error' </li></ul><ul><li>This results in an error, because the datatypes do not match. The DBMS will first try to implicitly convert the value </li></ul><ul><li>This can result in other types of errors </li></ul><ul><ul><li>Rounding errors </li></ul></ul><ul><ul><ul><li>Assigning a money datatype to an integer removes the cents </li></ul></ul></ul><ul><ul><li>Insufficient space </li></ul></ul><ul><ul><ul><li>Assigning a 30 character string to a variable defined as char(10) </li></ul></ul></ul><ul><li>Select more than one value into a variable </li></ul>
  17. 17. Global Variables <ul><li>Global variables are defined and managed by the server </li></ul><ul><li>They can not be assigned values by the user </li></ul><ul><li>Are preceded by an @@ </li></ul><ul><li>@@error </li></ul><ul><li>@@identity </li></ul><ul><li>@@rowcount </li></ul><ul><li>@@version </li></ul><ul><li>@@max_connections </li></ul><ul><li>@@servername </li></ul>
  18. 18. Global Variables <ul><li>@@error - contains the error number generated by the last statement </li></ul><ul><ul><li>Assigned by connection </li></ul></ul><ul><li>@@identity - contains the last identity value used </li></ul><ul><ul><li>Assigned by connection </li></ul></ul><ul><li>@@rowcount - contains the number of rows affected by the last statement </li></ul><ul><ul><li>Assigned by connection </li></ul></ul><ul><li>Variables assigned by connection mean that each connection has it's own copy of the variable. Changes to the variable for one connection do not affect any others </li></ul>
  19. 19. Global Variables <ul><li>@@version - Contains the SQL Server version number </li></ul><ul><ul><li>Assigned by server </li></ul></ul><ul><li>@@max_connections - contains the maximum number of user connections allowed </li></ul><ul><ul><li>Assigned by the server </li></ul></ul><ul><li>@@servername - contains the name of the SQL Server </li></ul><ul><ul><li>Assigned by the server </li></ul></ul><ul><li>Assigned by the server means that there is one copy of this variable for access by all connections </li></ul>
  20. 20. Global Variables <ul><li>The two most common global variables you will use extensively are @@error and @@rowcount </li></ul><ul><li>@@error will be used in much of your error checking to branch to appropriate error handling </li></ul><ul><li>@@rowcount will be used to verify the number of rows affected by an operation. It will also be used to determine if you need to step through a result set via a cursor </li></ul>
  21. 21. Control Of Flow <ul><li>No language would be complete without the ability to branch to other parts of code or perform many iterations of a task </li></ul><ul><li>SQL accomplishes this through a small set of constructs </li></ul><ul><li>if…else </li></ul><ul><li>begin…end </li></ul><ul><li>while… </li></ul><ul><li>return </li></ul><ul><li>waitfor </li></ul><ul><li>goto </li></ul><ul><li>case </li></ul>
  22. 22. Control Of Flow <ul><li>if…else allows you to conditionally execute a statement </li></ul><ul><li>begin…end groups statements into a block </li></ul><ul><li>while loops through a set of commands </li></ul><ul><li>return exits a batch </li></ul><ul><li>waitfor executes based on an event </li></ul><ul><li>goto branches to a user defined label </li></ul>
  23. 23. If…else <ul><li>if boolean_expression </li></ul><ul><ul><li>statement </li></ul></ul><ul><li>[else [if boolean_expression] </li></ul><ul><ul><li>statement] </li></ul></ul><ul><li>A boolean expression evaluates to either true or false </li></ul><ul><li>You can include a select statement in the boolean expression, but it must return only one value and the select must be enclosed in parenthesis </li></ul>
  24. 24. If…else <ul><li>declare @myvar money </li></ul><ul><li>select @myvar = avg(price) from titles </li></ul><ul><li>if @myvar < 15 </li></ul><ul><ul><li>update titles set price = price * 2 </li></ul></ul><ul><li>else </li></ul><ul><ul><li>update titles set price = price * 1.1 </li></ul></ul><ul><li>You can only nest up to 150 levels deep </li></ul>
  25. 25. If…else <ul><li>An if statement will execute the only next statement </li></ul><ul><li>Consider the following: </li></ul><ul><li>declare @myvar money </li></ul><ul><li>select @myvar = avg(price) from titles </li></ul><ul><li>if @myvar < 15 </li></ul><ul><ul><li>update titles set price = price * 2 </li></ul></ul><ul><ul><li>select @myvar = avg(price) from titles </li></ul></ul><ul><li>The second statement will execute every time through the batch. It is not dependent on the if statement </li></ul>
  26. 26. Begin…end <ul><li>What happens if we want to execute more than one statement following a conditional test? </li></ul><ul><li>To overcome this, the begin…end construct is used </li></ul><ul><li>The begin…end allows two or more statements to follow an if and be executed as a group </li></ul><ul><li>begin </li></ul><ul><ul><li>statement block </li></ul></ul><ul><li>end </li></ul>
  27. 27. Begin…end <ul><li>declare @myvar money </li></ul><ul><li>select @myvar = avg(price) from titles </li></ul><ul><li>if @myvar < 15 </li></ul><ul><li>begin </li></ul><ul><ul><li>update titles set price = price * 2 </li></ul></ul><ul><ul><li>print &quot;Prices doubled&quot; </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>else </li></ul><ul><li>begin </li></ul><ul><ul><li>update titles set price = price * 1.1 </li></ul></ul><ul><ul><li>print &quot;Prices increased by 10%&quot; </li></ul></ul><ul><ul><li>end </li></ul></ul>
  28. 28. If [not] exists <ul><li>Using exists and not exists are useful when you are only concerned whether data exists </li></ul><ul><li>declare @name varchar(30) </li></ul><ul><li>select @name = 'Smith' </li></ul><ul><li>if exists (select * from authors where au_lname = @name) </li></ul><ul><ul><li>select &quot;There is a match&quot; </li></ul></ul><ul><li>else </li></ul><ul><ul><li>select &quot;There is no match&quot; </li></ul></ul><ul><li>An if exists query stops processing as soon as it finds a match. Because of this, it is very useful for enforcing referential integrity </li></ul>
  29. 29. Return <ul><li>Return is used to exit a batch, trigger, or stored procedure unconditionally </li></ul><ul><li>Any statements following the return are not executed </li></ul><ul><li>if not exists (select 1 from titles where title_id = @t_id) </li></ul><ul><ul><li>begin </li></ul></ul><ul><ul><ul><li>print &quot;No such title&quot; </li></ul></ul></ul><ul><ul><ul><li>return </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>insert into salesdetail... </li></ul>
  30. 30. While <ul><li>While is used to execute a statement(s) repeatedly </li></ul><ul><li>while boolean_expression </li></ul><ul><ul><li>statement block to execute as long as the condition is true </li></ul></ul><ul><li>while (select avg(price) from titles) < 40 </li></ul><ul><li>begin </li></ul><ul><ul><li>update titles set price = price + 2 </li></ul></ul><ul><ul><li>select avg(price) from titles </li></ul></ul><ul><li>end </li></ul>
  31. 31. While <ul><li>You can control the statements in a while loop via break or continue </li></ul><ul><li>break exits the loop, but not the batch </li></ul><ul><li>continue restarts processing at the beginning of the loop </li></ul><ul><li>while (select avg(price) from titles) > 20 </li></ul><ul><li>begin </li></ul><ul><ul><li>update titles set price = price - 2 </li></ul></ul><ul><ul><li>if (select max(price) from titles) < 40 </li></ul></ul><ul><ul><ul><li>break </li></ul></ul></ul><ul><ul><li>else </li></ul></ul><ul><ul><li>if (select avg(price) from titles) > 20 </li></ul></ul><ul><ul><ul><li>continue </li></ul></ul></ul><ul><li>end </li></ul>
  32. 32. Case <ul><li>A case statement is a more compact way of expressing nested if…else statements </li></ul><ul><li>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, &quot;Shortened Title&quot; = CONVERT(varchar(30), title), Price = price FROM titles WHERE price IS NOT NULL ORDER BY type COMPUTE AVG(price) BY type </li></ul>
  33. 33. Case - Results <ul><li>Category Shortened Title Price </li></ul><ul><li>------------------- ------------------------------ ----------------------- </li></ul><ul><li>Business The Busy Executive's Database 19.99 </li></ul><ul><li>Business Cooking with Computers: Surrep 11.95 </li></ul><ul><li>Business You Can Combat Computer Stress 2.99 </li></ul><ul><li>Business Straight Talk About Computers 19.99 </li></ul><ul><li>avg ======================= </li></ul><ul><li>13.73 </li></ul><ul><li>Category Shortened Title Price </li></ul><ul><li>------------------- ------------------------------ ----------------------- </li></ul><ul><li>Modern Cooking Silicon Valley Gastronomic Tre 19.99 </li></ul><ul><li>Modern Cooking The Gourmet Microwave 2.99 </li></ul><ul><li>avg ======================= </li></ul><ul><li>11.49 </li></ul><ul><li>Category Shortened Title Price </li></ul><ul><li>------------------- ------------------------------ ----------------------- </li></ul><ul><li>Popular Computing But Is It User Friendly? 22.95 </li></ul><ul><li>Popular Computing Secrets of Silicon Valley 20.00 </li></ul><ul><li>avg ======================= </li></ul><ul><li>21.48 </li></ul><ul><li>.. </li></ul><ul><li>(21 row(s) affected) </li></ul>
  34. 34. Goto <ul><li>goto will branch to a user defined label </li></ul><ul><li>… if @@error != 0 </li></ul><ul><ul><li>begin </li></ul></ul><ul><ul><ul><li>select @errno = 30000 </li></ul></ul></ul><ul><ul><ul><li>select @errmsg = 'Some error message' </li></ul></ul></ul><ul><ul><ul><li>goto error </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>... </li></ul><ul><li>/* Errors handling */ </li></ul><ul><li>error: </li></ul><ul><li>raiserror @errno @errmsg </li></ul><ul><li>rollback transaction </li></ul><ul><li>end </li></ul>
  35. 35. Waitfor <ul><li>waitfor allows execution to be delayed until an event occuurs </li></ul><ul><li>waitfor {delay time | time time…} </li></ul><ul><ul><li>delay suspends execution until a specified time has elapsed (up to 24 hours) </li></ul></ul><ul><ul><li>time suspends execution until a specified time of day (you can not specify a date) </li></ul></ul><ul><li>--endless loop that records number of locks </li></ul><ul><li>--every half hour </li></ul><ul><li>while 2 > 1 </li></ul><ul><ul><li>begin </li></ul></ul><ul><ul><ul><li>waitfor delay '0:30:00' --30 minutes </li></ul></ul></ul><ul><ul><ul><li>insert into num_procs </li></ul></ul></ul><ul><ul><ul><li>select getdate(), count(*) from master..syslocks </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>waitfor is superceded by tasks in MS SQL Server </li></ul>
  36. 36. Unit 11 Review <ul><li>Batches consist of more than one SQL statement </li></ul><ul><li>You can add comments two ways: /*…*/ or --… </li></ul><ul><li>Datatypes define what types of data can be contained within a column </li></ul><ul><li>Variables can be either global or local </li></ul><ul><li>Global variables can be accessed but not written to by the user and are preceeded by an @@ </li></ul><ul><li>Local variables are created and managed by the user and are preceeded by an @ </li></ul><ul><li>A select is used to assign a value to a local variable </li></ul><ul><li>Control of flow in batches can be accomplished via 7 main constructs </li></ul><ul><ul><li>if…else </li></ul></ul><ul><ul><li>begin…end </li></ul></ul><ul><ul><li>while... </li></ul></ul><ul><ul><li>goto </li></ul></ul><ul><ul><li>case </li></ul></ul><ul><ul><li>return </li></ul></ul><ul><ul><li>waitfor </li></ul></ul>
  37. 37. Unit 11 Exercises <ul><li>There are no exercises for this unit </li></ul>