You are on page 1of 24

Transact-SQL

Submitted to: Sir Fiaz Majeed. Submitted by:


Anum Safder Iqra Mustafa 08020656-026 08020656-036

BS(Hons) IT 8th Semester.

University of Gujrat

Transact-SQL:
Short for Transaction-SQL, an extended form of SQL that adds declared variables, transaction control, error and exception handling and row processing to SQLs existing functions. Structured Query language (SQL) is the most widely used relational database query language.

History of T-SQL :
SQL, on which Transact-SQL is based, was developed in the mid-1970s as an IBM Product called SEQUEL. SEQUEL stood for Structured English Query Language. After some legal problems, IBM changed the name to SQL, the Structured Query Language. The language was designed to provide a standard method for accessing data in a relational database. Ironically, just like so many things first developed at IBM, Oracle was the first company to bring a SQLusing product to market. Today, many different relational database systems utilize SQL as the primary means for accessing and manipulating data. When the American National Standards Institute (ANSI) published a standard for the SQL language in 1989, they set a universal standard to which database vendors could adhere. Later, in 1992, ANSI released an update to the SQL standard, known as SQL-92. The standards helped formalize many of the behaviors and syntax structures of SQL. The ANSI standard covered lots of important details concerning the querying and manipulation of data. The syntax was formalized for many commands; some of these are SELECT, INSERT, UPDATE, DELETE, CREATE, and DROP.

Syntax: Data Types:


Sybase and Microsoft's SQL Server support the following data types: Character Strings 1. Char stores fixed-length character strings, such as STATE abbreviations, when you know that the column will always be two characters. 2. Varchar stores variable-length character strings, such as an individual's name, where the exact length of a name is not specified, for example, AL RAY to WILLIAM STEPHENSON. 3. Text stores strings with nearly unlimited size, such as a remarks column or description of a type of service. Numeric Data Types 1. Int stores integers from -2,147,483,647 to +2,147,483,647. 2. Smallint stores integers from -32,768 to 32,767.

3. Tinyint stores integers from 0 to 255. 4. Float expresses numbers as real floating-point numbers with data precisions. Decimals are allowed with these data types. The values range from +2.23E-308 to +1.79E308. 5. Real expresses real numbers with data precisions from +1.18E-38 to +3.40E38. DATE Data Types 1. Datetime values range from Jan 1, 1753 to Dec 31, 9999. 2. Smalldatetime values range from Jan 1, 1900 to Jun 6, 2079. Money Data Types 1. Money stores values up to +922,337,203,685,477.5808. 2. Smallmoney stores values up to +214,748.3647. Money values are inserted into a table using the dollar sign; for example: insert payment_tbl (customer_id, paydate, pay_amt) values (012845, "May 1, 1997", $2099.99) Binary Strings 1. Binary stores fixed-length binary strings. 2. Varbinary stores variable-length binary strings. 3. Image stores very large binary strings, for example, photographs and other images. bit: A Logical Data Type The data type bit is often used to flag certain rows of data within a table. The value stored within a column whose data type is bit is either a 1 or 0. For example, the value 1 may signify the condition true, whereas 0 denotes a false condition. The following example uses the bit data type to create a table containing individual test scores: create table test_flag ( ind_id int not null, test_results int not null, result_flag bit not null)

Variables:
Declaring Local Variables: Every programming language enables some method for declaring local (or global) variables that can be used to store data. Transact-SQL is no exception. Declaring a variable using Transact-SQL is an extremely simple procedure. The keyword that must be used is the DECLARE keyword. The syntax looks like this: Syntax: declare @variable_name data_type To declare a character string variable to store players' names, use the following statement: declare @name char(30) go

Declaring Global Variables Declaring your own global variables is particularly useful when using stored procedures. SQL Server also maintains several system global variables that contain information that might be useful to the database system user.

Variable Name
@@char_convert 0 @@client_csid @@client_csname @@connections

Purpose if character set conversion is in effect. Client's character set ID. Client's character set name. Number of logons since SQL Server was started. Amount of time, in ticks, the CPU has been busy since SQL Server was started. Contains error status. Last value inserted into an identity column. Amount of time, in ticks, that SQL Server has been idle since started. Amount of time, in ticks, that SQL Server has spent doing I/O. Current isolation level of the Transact-SQL program. Defines local language ID. Defines the name of the local language. Maximum length of a character. Maximum number of connections that can be made with SQL Server. Average length of a national character.

@@cpu_busy

@@error @@identity @@idle

@@io_busy

@@isolation

@@langid @@language @@maxcharlen @@max_connections

@@ncharsize

@@nestlevel @@pack_received

Nesting level of current execution. Number of input packets read by SQL Server since it was started. Number of output packets sent by SQL Server since it was started. Number of errors that have occurred since SQL Server was started. ID of the currently executing stored procedure. Number of rows affected by the last command. Name of the local SQL Server. Process ID number of the current process. Contains status information. Maximum length of text or image data returned with SELECT statement. Change in free space required to activate a threshold. Number of errors that have occurred while reading or writing. Number of disk reads since SQL Server was started. Number of disk writes since SQL Server was started.

@@pack_sent

@@packet_errors

@@procid @@rowcount @@servername @@spid @@sqlstatus

@@textsize @@thresh_hysteresis

@@total_errors

@@total_read

@@total_write

Using Variables The DECLARE keyword enables you to declare several variables with a single statement(although this device can sometimes look confusing when you look at your code later). An example of this type of statement appears here: declare @batter_name char(30), @team int, @average float go

Flow Control:
Probably the most powerful set of Transact-SQL features involves its capability to control program flow. BEGIN and END Statements Transact-SQL uses the BEGIN and END statements to signify the beginning and ending points of blocks of code. Syntax: BEGIN statement1 statement2 statement3... END IF...ELSE Statements One of the most basic programming constructs is the IF...ELSE statement. Nearly every programming language supports this construct, and it is extremely useful for checking the value of data retrieved from the database. The Transact-SQL syntax for the IF...ELSE statement looks like this: Syntax: if (condition) begin (statement block) end else if (condition) begin statement block) end . . . else begin (statement block) End The WHILE Loop Another popular programming construct that Transact-SQL supports is the WHILE loop. This command has the following syntax:

Syntax: WHILE logical_expression statement(s)

Date Conversions:
Sybase and Microsoft's SQL Server can insert dates into a table in various formats; they can also extract dates in several different types of formats. This section shows you how to use SQL Server's CONVERT command to manipulate the way a date is displayed. Syntax: CONVERT (datatype [(length)], expression, format)

Select statements:
Syntax in SQL is quite flexible, although there are rules to follow as in any programming language. A simple query illustrates the basic syntax of an SQL select statement.

Example: SELECT NAME, STARTTERM, ENDTERM FROM PRESIDENTS WHERE NAME = 'LINCOLN'; In this example everything is capitalized, but it doesn't have to be. The preceding query would work just as well if it were written like this: select name, startterm, endterm from presidents where name = 'LINCOLN'; Notice that LINCOLN appears in capital letters in both examples. Although actual SQL statements are not case sensitive, references to data in a database are. Note: Commands in SQL are not case sensitive.

The Building Blocks of Data Retrieval: SELECT and FROM


Syntax: SELECT <COLUMN NAMES> FROM <TABLE> SQL> select * from checks;

The asterisk (*) in select * tells the database to return all the columns associated with the given table described in the FROM clause. The database determines the order in which to return the columns. Terminating an SQL Statement: In some implementations of SQL, the semicolon at the end of the statement tells the interpreter that you are finished writing the query.

Changing the Order of the Columns:

The preceding example of an SQL statement used the * to select all columns from a table, the order of their appearance in the output being determined by the database. To specify the order of the columns, you could type something like: Syntax: SQL> SELECT payee, remarks, amount, check# from checks; Selecting Individual Columns: Suppose you do not want to see every column in the database. You used SELECT * to find out what information was available, and now you want to concentrate on the check number and the amount. Syntax: SQL> SELECT CHECK#, amount from checks;

Queries with Distinction:


If in table, you see that some of the data repeats. Syntax: SQL> select amount from checks; And if you wanted to see how many different amounts were in this column? Try this: Syntax: SQL> select DISTINCT amount from checks;

Expressions:
The definition of an expression is simple: An expression returns a value. Expression types are very broad, covering different data types such as String, Numeric, and Boolean. In fact, pretty much anything following a clause (SELECT or FROM, for example) is an expression. In the following example amount is an expression that returns the value contained in the amount column. SELECT amount FROM checks;

In the following statement NAME, ADDRESS, PHONE and ADDRESSBOOK are expressions: SELECT NAME, ADDRESS, PHONE FROM ADDRESSBOOK;

Conditions:
To find a particular item or group of items in database, we need one or more conditions. Conditions are contained in the WHERE clause. In the preceding example, the condition is NAME = 'BROWN' To find everyone in organization who worked more than 100 hours last month, condition would be: NUMBEROFHOURS > 100 The WHERE Clause: The syntax of the WHERE clause is

Syntax: WHERE <SEARCH CONDITION>

Operators:
Operators are the elements you use inside an expression to articulate how you want specified conditions to retrieve data. Operators fall into six groups: arithmetic, comparison, character, logical, set, and miscellaneous.

Arithmetic Operators: The arithmetic operators are plus (+), minus (-), divide (/), multiply (*), and modulo (%). The first four are self-explanatory. Modulo returns the integer remainder of a division. Here are two examples: 5%2=1 6%2=0 The modulo operator does not work with data types that have decimals, such as Real or Number. If you place several of these arithmetic operators in an expression without any parentheses, the operators are resolved in this order: multiplication, division, modulo, addition, and subtraction.

Comparison Operators:

True to their name, comparison operators compare expressions and return one of three values: TRUE, FALSE, or Unknown. Syntax: SQL> SELECT * FROM PRICE WHERE WHOLESALE = NULL; no rows selected Equal (=)

Syntax: SQL> SELECT * FROM FRIENDS WHERE FIRSTNAME = 'JD'; Greater Than (>) and Greater Than or Equal To (>=) The greater than operator (>) works like this:

Syntax: SQL> SELECT * FROM FRIENDS WHERE AREACODE > 300; Less Than (<) and Less Than or Equal To (<=) As you might expect, these comparison operators work the same way as > and >= work, only in reverse: Syntax: SQL> SELECT * FROM FRIENDS WHERE STATE < 'LA'; Inequalities (< > or !=) When you need to find everything except for certain data, use the inequality symbol, which can be either < > or !=, depending on your SQL implementation. For example, to find everyone who is not AL, type this: Syntax: SQL> SELECT * FROM FRIENDS WHERE STATE != 'CA';

Character Operators:

You can use character operators to manipulate the way character strings are represented, both in the output of data and in the process of placing conditions on data to be retrieved. Syntax: SQL> SELECT * FROM PARTS WHERE LOCATION LIKE '%BACK%';

Concatenation (||) The || (double pipe) symbol concatenates two strings. Try this:

Syntax: SQL> SELECT FIRSTNAME || LASTNAME ENTIRENAME FROM FRIENDS;

Logical Operators:
Logical operators separate two or more conditions in the WHERE clause of an SQL statement. Suppose your company gives each employee 12 days of leave each year. Using what you have learned and a logical operator, find all the employees whose names start with B and who have more than 50 days of leave coming. Syntax: SQL> SELECT LASTNAME, YEARS * 12 - LEAVETAKEN REMAINING FROM VACATION WHERE LASTNAME LIKE 'B%' AND YEARS * 12 - LEAVETAKEN > 50; AND AND means that the expressions on both sides must be true to return TRUE. If either expression is false, AND returns FALSE. For example, to find out which employees have been with the company for 5 years or less and have taken more than 20 days leave, try this: Syntax: SQL> SELECT LASTNAME FROM VACATION WHERE YEARS <= 5 AND LEAVETAKEN > 20 ;

OR

You can also use OR to sum up a series of conditions. If any of the comparisons is true, OR returns TRUE. To illustrate the difference, conditions run the last query with OR instead of with AND: Syntax: SQL> SELECT LASTNAME WORKAHOLICS FROM VACATION WHERE YEARS >= 5 OR ((YEARS *12)-LEAVETAKEN)/(YEARS * 12) >= 0.50; NOT NOT means just that. If the condition it applies to evaluates to TRUE, NOT make it FALSE. If the condition after the NOT is FALSE, it becomes TRUE. For example, the following SELECT returns the only two names not beginning with B in the table: Syntax: SQL> SELECT * FROM VACATION WHERE LASTNAME NOT LIKE 'B%';

Set Operators:
UNION and UNION ALL UNION returns the results of two queries minus the duplicate rows. The following two tables represent the rosters of teams: Syntax: SQL> SELECT NAME FROM SOFTBALL UNION SELECT NAME FROM FOOTBALL; INTERSECT INTERSECT returns only the rows found by both queries. The next SELECT statement shows the list of players who play on both teams: Syntax: SQL> SELECT * FROM FOOTBALL INTERSECT SELECT * FROM SOFTBALL;

MINUS (Difference) Minus returns the rows from the first query that were not present in the second.

Syntax: SQL> SELECT * FROM FOOTBALL MINUS SELECT * FROM SOFTBALL;

Miscellaneous Operators: IN and BETWEEN:


The two operators IN and BETWEEN provide a shorthand for functions you already know how to do. If you wanted to find friends in Colorado, California, and Louisiana. Syntax; SQL> SELECT * FROM FRIENDS WHERE STATE= 'CA' OR STATE ='CO' OR STATE = 'LA';

Functions:
Functions allow you shortcuts to manipulate and manage data. There are a large number of functions to choose from, but they fall into these basic categories:

Aggregate functions:
Aggregate functions compute a single value result, such as the sum or average value of a given column in a table. Syntax: SQL> SELECT * FROM TEAMSTATS; COUNT function: The function COUNT returns the number of rows that satisfy the condition in the WHERE clause. Say you wanted to know how many ball players were hitting under 350. You would type: Syntax: SQL> SELECT COUNT(*) FROM TEAMSTATS WHERE HITS/AB < .35; COUNT(*) -------4

SUM SUM does just that. It returns the sum of all values in a column. Syntax: SQL> SELECT SUM(SINGLES) TOTAL_SINGLES FROM TEAMSTATS; AVG The AVG function computes the average of a column. Syntax: SQL> SELECT AVG(SO) AVE_STRIKE_OUTS FROM TEAMSTATS; MAX If you want to find the largest value in a column, use MAX. Syntax: SQL> SELECT MAX(HITS) FROM TEAMSTATS; MIN MIN does the expected thing and works like MAX except it returns the lowest member of a column. To find out the fewest at bats, type Syntax: SQL> SELECT MIN(AB) FROM TEAMSTATS; VARIANCE VARIANCE produces the square of the standard deviation, a number vital to many statistical calculations.

Syntax: SQL> SELECT VARIANCE(HITS) FROM TEAMSTATS;

Arithmetic Functions:
Many of the uses you have for the data you retrieve involve mathematics. ABS The ABS function returns the absolute value of the number you point to. For example: SQL> SELECT ABS(A) ABSOLUTE_VALUE FROM NUMBERS; CEIL and FLOOR CEIL returns the smallest integer greater than or equal to its argument. FLOOR does just the reverse, returning the largest integer equal to or less than its argument. For example: SQL> SELECT B, CEIL(B) CEILING

FROM NUMBERS; COS, COSH, SIN, SINH, TAN, and TANH The COS, SIN, and TAN functions provide support for various trigonometric concepts. They all work on the assumption that n is in radians. The following statement returns some unexpected values if you don't realize COS expects A to be in radians. For example: SQL> SELECT A, COS(A) FROM NUMBERS; EXP EXP enables you to raise e (e is a mathematical constant used in various formulas) to a power. Here's how EXP raises e by the values in column A: SQL> SELECT A, EXP(A) FROM NUMBERS; LN and LOG These two functions center on logarithms. LN returns the natural logarithm of its argument. For example: SQL> SELECT A, LN(A) FROM NUMBERS; POWER To raise one number to the power of another, use POWER. In this function the first argument is raised to the power of the second: SQL> SELECT A, B, POWER(A,B) FROM NUMBERS; SIGN SIGN returns -1 if its argument is less than 0, 0 if its argument is equal to 0, and 1 if its argument is greater than 0, as shown in the following example: SQL> SELECT A, SIGN(A) SQRT The function SQRT returns the square root of an argument. Because the square root of a negative number is undefined, you cannot use SQRT on negative numbers. SQL> SELECT A, SQRT(A) FROM NUMBERS;

Character Functions
Many implementations of SQL provide functions to manipulate characters and strings of characters. This section covers the most common character functions. The examples in this section use the table CHARACTERS.

Syntax: SQL> SELECT * FROM CHARACTERS; CHR CHR returns the character equivalent of the number it uses as an argument. The character it returns depends on the character set of the database. For this example the database is set to ASCII. The column CODE includes numbers. Syntax: SQL> SELECT CODE, CHR(CODE) FROM CHARACTERS; CONCAT The || symbol splices two strings together, as does CONCAT. It works like this:

SQL> SELECT CONCAT(FIRSTNAME, LASTNAME) "FIRST AND LAST NAMES" FROM CHARACTERS; INITCAP INITCAP capitalizes the first letter of a word and makes all other characters lowercase. SQL> SELECT FIRSTNAME
LOWER and UPPER

As you might expect, LOWER changes all the characters to lowercase; UPPER does just the reverse. The following example starts by doing a little magic with the UPDATE function (you learn more about this next week) to change one of the values to lowercase: SQL> UPDATE CHARACTERS SET FIRSTNAME = 'kelly' WHERE FIRSTNAME = 'KELLY';

Conversion functions:
There are a few versatile functions within Transact-SQL that allow you to convert data from one data type to another or to reformat data. SQL> SELECT TESTNUM, TO_CHAR(TESTNUM) FROM CONVERT; TO_NUMBER TO_NUMBER is the companion function to TO_CHAR, and of course, it converts a string into a number. For example: SQL> SELECT NAME, TESTNUM, TESTNUM*TO_NUMBER(NAME) FROM CONVERT;

Miscellaneous Functions
Here are three miscellaneous functions you may find useful. GREATEST and LEAST These functions find the GREATEST or the LEAST member from a series of expressions. For example: SQL> SELECT GREATEST('ALPHA', 'BRAVO','FOXTROT', 'DELTA') FROM CONVERT; USER USER returns the character name of the current user of the database.

Syntax: SQL> SELECT USER FROM CONVERT;

Date functions:
Date functions manipulate DATETIME and SMALLDATETIME values.

Mathematical functions:
These functions provide statistical, trigonometric, logarithmic, and exponential capabilities when manipulating numbers.

String functions:
A number of string functions allow you to analyze and modify CHAR, VARCHAR, and, in some cases, TEXT columns and variables.

System functions:
System functions allow you to retrieve information from system tables and parameters. In this usage, they are somewhat like global variables. Some system functions also provide a way to perform logical comparison of data.

Text and image functions:


Manipulation of TEXT and IMAGE data differs from other types, because they have several usage restrictions. Transact-SQL provides several specialized functions to support the use and manipulation of these data types.

Joining Tables:
Syntax: SELECT * FROM TABLE1,TABLE2 Multiple Tables in a Single SELECT Statement: To join two tables, type this:

Finding the Correct Column:


When you joined TABLE1 and TABLE2, you used SELECT *, which returned all the columns in both tables. In joining ORDERS to PART, the SELECT statement is a bit more complicated: SELECT O.ORDEREDON, O.NAME, O.PARTNUM, P.PARTNUM, P.DESCRIPTION Equi-Joins An extract from the PART/ORDERS join provides a clue as to what is missing: 30-JUN-1996 TRUE WHEEL 42 54 PEDALS 30-JUN-1996 BIKE SPEC 54 54 PEDALS 30-MAY-1996 BIKE SPEC 10 54 PEDALS Notice the PARTNUM fields that are common to both tables.

So, SELECT O.ORDEREDON, O.NAME, O.PARTNUM, P.PARTNUM, P.DESCRIPTION FROM ORDERS O, PART P WHERE O.PARTNUM = P.PARTNUM Non-Equi-Joins Because SQL supports an equi-join, you might assume that SQL also has a nonequi-join. Whereas the equi-join uses an = sign in the WHERE statement, the non-equijoin uses everything but an = sign. For example: SELECT O.NAME, O.PARTNUM, P.PARTNUM, O.QUANTITY * P.PRICE TOTAL FROM ORDERS O, PART P WHERE O.PARTNUM > P.PARTNUM

Outer Joins versus Inner Joins Just as the non-equi-join balances the equi-join, an outer join complements the inner join. An inner join is where the rows of the tables are combined with each other, producing a number of new rows equal to the product of the number of rows in each table. Also, the inner join uses these rows to determine the result of the WHERE clause. An outer join groups the two tables in a slightly different way. Using the PART and ORDERS tables from the previous examples, perform the following inner join: SELECT P.PARTNUM, P.DESCRIPTION,P.PRICE, O.NAME, O.PARTNUM FROM PART P JOIN ORDERS O ON ORDERS.PARTNUM = 54

Joining a Table to Itself Today's final topic is the often-used technique of joining a table to itself. The syntax of this operation is similar to joining two tables. For example, to join table TABLE1 to itself, type this: SELECT * FROM TABLE1, TABLE1

Manipulating Data:
The three statements are as follows: 1. The INSERT statement 2. The UPDATE statement 3. The DELETE statement

The INSERT Statement The INSERT statement enables you to enter data into the database. It can be broken down into two statements: INSERT...VALUES and INSERT...SELECT The INSERT...VALUES Statement The INSERT...VALUES statement enters data into a table one record at a time. It is useful for small operations that deal with just a few records. The syntax of this statement is as follows: Syntax: INSERT INTO table_name (col1, col2...) VALUES(value1, value2...) Inserting NULL Values A NULL value means that the value is empty. It is neither a zero, in the case of an integer, nor a space, in the case of a string. Instead, no data at all exists for that record's column. If a column is defined as NOT NULL (that column is not allowed to contain a NULL value), you must insert a value for that column when using the INSERT statement. The INSERT is canceled if this rule is broken, and you should receive a descriptive error message concerning your error. Example: SQL> insert into collection values ('SPORES MILDEW FUNGUS', 50.00, ' '); Inserting Unique Values

Many database management systems also allow you to create a UNIQUE column attribute. This attribute means that within the current table, the values within this column must be completely unique and cannot appear more than once. This limitation can cause problems when inserting or updating values into an existing table, as the following exchange demonstrates: SQL> INSERT INTO COLLECTION VALUES('STRING', 50, 'MORE STRING'); The INSERT...SELECT Statement The INSERT...VALUES statement is useful when adding single records to a database table, many database systems also support temporary tables. Temporary tables exist for the life of your database connection and are deleted when your connection is terminated. The INSERT...SELECT statement can take the output of a SELECT statement and insert these values into a temporary table. Here is an example: SQL> insert into tmp_tbl select * from table; The UPDATE Statement The purpose of the UPDATE statement is to change the values of existing records. The syntax is: Syntax: UPDATE table_name SET columnname1 = value1 [, columname2 = value2]... WHERE search_condition The DELETE Statement In addition to adding data to a database, you will also need to delete data from a database. The syntax for the DELETE statement is Syntax: DELETE FROM tablename WHERE condition Depending on the use of the DELETE statement's WHERE clause, SQL can do the following: 1. Delete single rows 2. Delete multiple rows 3. Delete all rows 4. Delete no rows

The CREATE DATABASE Statement:


Syntax: CREATE DATABASE database_name

The CREATE TABLE Statement:


The process of creating a table is far more standardized than the CREATE DATABASE statement. Here's the basic syntax for the CREATE TABLE statement: Syntax: CREATE TABLE table_name ( field1 datatype [ NOT NULL ], field2 datatype [ NOT NULL ], field3 datatype [ NOT NULL ]...) Creating a Table from an Existing Table The most common way to create a table is with the CREATE TABLE command. However, some database management systems provide an alternative method of creating tables, using the format and data of an existing table. This method is useful when you want to select the data out of a table for temporary modification. It can also be useful when you have to create a table similar to the existing table and fill it with similar data. (You won't have to reenter all this information.) The syntax for Oracle follows. Syntax: CREATE TABLE NEW_TABLE(FIELD1, FIELD2, FIELD3) AS (SELECT FIELD1, FIELD2, FIELD3 The ALTER TABLE Statement The ALTER TABLE statement enables the database administrator or designer to change the structure of a table after it has been created. The ALTER TABLE command enables you to do two things: 1. Add a column to an existing table 2. Modify a column that already exists The syntax for the ALTER TABLE statement is as follows: Syntax: ALTER TABLE table_name <ADD column_name data_type; | MODIFY column_name data_type;>

The DROP TABLE Statement SQL provides a command to completely remove a table from a database. The DROP TABLE command deletes a table along with all its associated views and indexes. After this command has been issued, there is no turning back. The most common use of the DROP TABLE statement is when you have created a table for temporary use. When you have completed all operations on the table that you planned to do, issue the DROP TABLE statement with the following syntax: Syntax: DROP TABLE table_name;

T-SQL Stored Procedures Using Parameters


Parameters can be passed to the stored procedures. This makes the procedure dynamic. The following points are to be noted:

One or more number of parameters can be passed in a procedure. The parameter name should proceed with an @ symbol. The parameter names will be local to the procedure in which they are defined.
The parameters are used to pass information into a procedure from the line that executes the parameter. The parameters are given just after the name of the procedure on a command line. Commas should separate the list of parameters. The values can be passed to stored procedures by: Example Code: CREATE PROCEDURE spSelectStudent (@Course INTEGER, @Grade INTEGER) AS SELECT * FROM Students WHERE Std_Course=@Course AND Std_Grade <= @Grade GO EXEC spSelectStudent 3, 2; Output: Id Name Std_Course Phone Std_Grade By supplying the parameter values exactly in the same order as given in the CREATE PROCEDURE statement. By explicitly naming the parameters and assigning the appropriate value.

3 4

Harri Robins Joe Philip

3 3

78788 46456

1 2

(2 row(s) affected)

Explanation: In the above example, the procedure is defined with two parameters. It should be noted that while executing the procedure the parameters should be passed in the same order of that in the CREATE statement. In this case, the first argument corresponds to Std_Course and second argument to Std_Grade. `

Features:
Transact-SQL Objects and Transaction Control One of the key features of Microsoft SQL Server and Sybase Adaptive Server is the ability to store Transact-SQL objects (triggers, views, and stored procedures) within the database itself. These blocks of Transact-SQL code can then be invoked by any user or system session that has adequate privileges to perform the task. In fact, both Sybase and Microsoft support the use of remote procedure calls (RPCs), allowing a single local server to invoke a stored procedure on a remote server. Through Transact-SQL objects, the database becomes a repository for both application code and data. Transact-SQL objects are stored in their own memory area, the procedure cache, within the database's memory space. At a more elemental level, transactions can be closely controlled and monitored in a Transact-SQL program using the global variables @@transtate and @@trancount. A transaction is a SQL or Transact-SQL statement that produces a measurable unit of work by retrieving, inserting, deleting, or modifying data. You can allow Transact-SQL to use implicit transactions, or you can explicitly define a transaction using the BEGIN TRAN, COMMIT TRAN, and ROLLBACK TRAN statements. By properly gauging and constructing your transactions, you can greatly reduce or even eliminate the possibility of blocks in an application supporting multiple concurrent connections.

Tracing and Debugging


A wide variety of tracing and debugging features are supplied by Transact-SQL using the DBCC and SET commands. In addition to providing tracing and debugging capabilities, these commands allow you to control server behavior, monitor performance, and alter the session environment and behavior. The DBCC command offers functions that fall into several general categories: 1. Database consistency checks Commands like DBCC NEWALLOC and DBCC UPDATEUSAGE check a given database for inconsistencies in the data and, in some cases, take remedial action. 2. Database and server configuration In dire straits, you can use DBCC command to drop or shrink databases.

3. Debugging Common debugging applications for the DBCC command include controlling tracing functions and examining the input and output buffer of various system and user sessions on the database server. 4. Performance tuning and monitoring A wide variety of DBCC commands allow you to monitor the behavior and performance of the server. Other commands enable you to pin tables into memory, rebuild indexes, reestablish fill factors, or display the selectivity and value of a given index. Conversely, the SET command enables you to mandate specific behaviors for a given session or user connection. You can use the SET command to enable or disable certain ANSI standards, determine deadlock resolution preference, and perform a wide range of other functionalities.

You might also like