• Save
MS SQL Server 1
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,036
On Slideshare
2,036
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
0
Comments
0
Likes
3

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • The DataReader was developed to get at data and in read-only forward-only fashion and provide the data as fast as possible to enable the developers as fast as possible. With the help of DataSet, it takes a snapshot of the data from database and storing this data offline for as long as necessary. When the end user using this copy of data he can persist the data and any changes to the data right back to data store.
  • Among the above 6 core namespaces ADO.NET classes are divided into three categories: Disconnected : These classes provides basic structure of ADO.NET includes DataTable, etc., The objects of this class are capable of storing data without any dependency on specific data provider. Shared: Set of base classes for data providers and shared among all data providers. Includes DataSet, DataRow, DataTable, Constraint, etc., Data Providers: These classes are meant to work with different data sources. Performs all database management operations on a specific database. Eg: SqlClient data provider works only with SQL Server Database.
  • ADO.NET ships with four database client namespaces. They are: System.Data.SqlClient System.Data.OracleClient System.Data.OleDb System.Data.Odbc. Within the .NET Framework data providers are light weight, creating minimal layer between the data source and code, increasing performance without scarifying functionality.
  • The SqlConnection Properties the DataSource, Database and State are read-only properties to read database server , database name and state of connection respectively.
  • Calling a stored procedure with a Command object is just assigning the stored procedure name to CommandText property of SqlCommand instance also setting the CommnadType property to CommandType.StoredProcedure value. Finally execute the one of previously stated method. The default ComandTimeout value is 30 seconds. The SqlRecord object contains only single returned row. When you begin transaction you can choose isolation level for commands executed within that transaction. This isolation levels specifies how changes made in one database session are viewed by another. These isolation levels are: ReadCommitted ReadUncomitted RepeatableRead Serializable ExecuteNonQuery() method is commonly user for UPDATE, INSERT or DELETE statements: This call will returns only the number of records effected. This call however can return results if you call a stored procedure that has output parameters.
  • While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
  • While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
  • SelectCommand: Gets or sets an object of type SqlCommand . This command is automatically executed to fill a DataTable with the result set. InsertComand: Gets or sets an object of type SqlCommand . This command used automatically executed to insert a new record to the database. UpdateCommand: Gets or sets an object of type SqlCommand . This command used to update the existing record on database. DeleteCommand: Gets or sets an object of type SqlCommand . Used to delete an existing record on database.
  • ParameterName: Gets or sets the name of the parameter SqlDbType: SQL server database type of the parameter value Size: Gets or sets the size of the parameter value. Direction: Gets or sets the direction of parameter such as input, output, or InputOutput . SourceColumn: Maps a column from a DataTable to the parameter. It enables you to execute multiple commands from SqlDataAdapter object and pick the correct parameter value from a DataTable column during the command execution. Value : Sets or gets the value provided by the parameter object. This value passed to the parameter defined in the command during the runtime.
  • Here links means primary key and Foreign key relation ships etc., In the above DataColumn instance we have given column name to CustomerID . If we don’t give there will be auto-generated column name(1, 2, .., ) is assigned by runtime. DataRow versions are described as: Current : The value existing at present column within the column. If no edit has occurred since received from database then it will be same as original value. Default: The default value. Original: The value of the column when originally selected from database. Proposed: When changes are proposed for a row it is possible to retrieve this modified value. (In between BeginEdit() and EndEdit() methods). Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet .
  • Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet . Server Explorer : In visual studio menu items select Data  Generate Data Set;; It will creates Connection, adapter and xsd files. Using the DataAdapter : Open a connection Create a DataAdapter Finally Fill DataSet. To create DataSet programmatically: Define data column object Add DataColumn object to a DataTable Add DataTable object to a DataSet
  • If you select data from database and populating it with adapter class runtime automatically creates the schema for your DataTable. It is also possible to create a DataTable programmatically. So creating schemas programmatically. Finally .NET framework also supports for using XML schemas to define a DataSet class, DataTable class and other classes. In the above relationships means Primary key and Foreign key relationship between the columns of different tables. The key difference between DataSet class and old style hierarchical Recordset object is in the way relationship is presented. In Recordset object the relationship was presented was a pseudo-column within the row. This column itself was a Recordset object. The below constrains are enforced within a DataSet class if the EnforcedConstraints property of the DataSet is true. Cascade: If the parent key has been updated copy new key value to all child records. If the parent record has been deleted then delete all the child records also. None: No action in child records whatsoever. This option leaves orphand rows within the child data table. SetDefault: Each child record affected has the foreign key column set to its default value if one has defined. SetNull: All child rows have the key column set to DBNull.
  • If you are working on a single table just use DataTable instead of DataSet. If you are working with multiple table and you need container for those tables to make relations use DataSet . To load the data from DataReader to DataTable just call Load() method on DataTable . SqlDataReader myReader = cmd.ExecuteReader(..); DataTable myTable = new DataTable(); myTable.Load(myReader); In reverse if you want a reader from DataTable then use: DataTableReader myReader = myTable.CreateDataReader();

Transcript

  • 1.  
  • 2. Introduction
    • SQL is an ANSI (American National Standards Institute) standard computer language for accessing and manipulating database systems. SQL statements are used to retrieve and update data in a database.
  • 3. What is SQL?
    • Structured Query Language
    • Communicate with databases
    • Used to created and edit databases.
    • Also used to create queries, forms, and reports
  • 4. Working with SQL A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger
  • 5. Table Basics
    • A Table is an object
    • Database data is stored in Tables
    • Each table has a unique name
    • Columns have various attributes, such as column name and data type
    • Rows contain records or data for the columns
  • 6. Creating Tables
    • The statement to use is create table
    • Here is the syntax:
    • create table “tablename”
    • (“columnname”, “datatype”,
    • “ columnname2”, “datatype”,
    • “ columnname3”, “datatype”);
  • 7. Example of Table creation
    • Here is a real example:
    • create table employee
    • (first varchar(15),
    • last varchar(20),
    • age number(3),
    • address varchar(30),
    • city varchar(20),
    • state varchar(20));
  • 8. Creating Tables - Steps
    • Use the command create table
    • Follow it with the correct table name
    • Put a parenthesis and type in the first column name
    • Follow it with the variable type (we will list them in a minute) then a comma
    • Continue the previous two steps until you have all your columns accounted for
    • Then put a parenthesis to close the columnname section and add a ; after it
  • 9. Creating Tables - Rules
    • Table and column names must start with a letter
    • They can not exceed 30 characters
    • They can not be key words such as create, insert, select, etc.
  • 10. SQL Queries With SQL, we can query a database and have a result set returned. A query like this: SELECT LastName FROM Persons Gives a result set like this: LastName Hansen Svendson Pettersen
  • 11. SQL Data Manipulation Language (DML)
    • SQL (Structured Query Language) is a syntax for executing queries. But the SQL language also includes a syntax to update, insert, and delete records.
    • These query and update commands together form the Data Manipulation Language (DML) part of SQL:
      • SELECT - extracts data from a database table
      • UPDATE - updates data in a database table
      • DELETE - deletes data from a database table
      • INSERT INTO - inserts new data into a database table
  • 12. SQL Data Definition Language (DDL)
    • The Data Definition Language (DDL) part of SQL permits database tables to be created or deleted. We can also define indexes (keys), specify links between tables, and impose constraints between database tables.
    • The most important DDL statements in SQL are: 
    • CREATE TABLE - creates a new database table
    • ALTER TABLE - alters (changes) a database table
    • DROP TABLE - deletes a database table
    • CREATE INDEX - creates an index (search key)
    • DROP INDEX  - deletes an index
  • 13. Selecting Data The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set). Syntax SELECT column_name(s) FROM table_name
  • 14. Select few columns To select the columns named "LastName" and "FirstName", use a SELECT statement like this: SELECT LastName, FirstName FROM Persons Persons LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger Result LastName FirstName Hansen Ola Svendson Tove Pettersen Kari
  • 15. Select All Columns
    • To select all columns from the "Persons" table, use a * symbol instead of column names, like this:
    • SELECT * FROM Persons
    LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger
  • 16. The Result Set
    • The result from a SQL query is stored in a result-set.
  • 17. Conditions Used In Where Clause = equals > greater than < less than >= greater than or equal to <= less than or equal to <> not equal to
  • 18. Using the WHERE Clause
    • To select only the persons living in the city &quot;Sandnes&quot;, we add a WHERE clause to the SELECT statement:
    • SELECT * FROM Persons
    • WHERE City='Sandnes'
    LastName FirstName Address City Year Hansen Ola Timoteivn 10 Sandnes 1951 Svendson Tove Borgvn 23 Sandnes 1978 Svendson Stale Kaivn 18 Sandnes 1980 Pettersen Kari Storgt 20 Stavanger 1960 LastName FirstName Address City Year Hansen Ola Timoteivn 10 Sandnes 1951 Svendson Tove Borgvn 23 Sandnes 1978 Svendson Stale Kaivn 18 Sandnes 1980
  • 19. Using Quotes Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes. For text values: This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove
  • 20. The LIKE Condition
      • The LIKE condition is used to specify a search for a pattern in a column.
    • Syntax
    • SELECT column FROM table
    • WHERE column LIKE pattern
    • A &quot;%&quot; sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern.
  • 21. Using LIKE The following SQL statement will return persons with first names that start with an 'O': SELECT * FROM Persons WHERE FirstName LIKE 'O%' The following SQL statement will return persons with first names that end with an 'a': SELECT * FROM Persons WHERE FirstName LIKE '%a' The following SQL statement will return persons with first names that contain the pattern 'la': SELECT * FROM Persons WHERE FirstName LIKE '%la%'
  • 22. The INSERT INTO Statement The INSERT INTO statement is used to insert new rows into a table. Syntax INSERT INTO table_name VALUES (value1, value2,....) You can also specify the columns for which you want to insert data: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
  • 23. Insert a New Row And this SQL statement: INSERT INTO Persons VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes
  • 24. Insert Data in Specified Columns And This SQL statement: INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes Rasmussen Storgt 67
  • 25. Inserting Information into Tables Steps
    • All strings should be enclosed by single quotes: 'string'**
    • Use the keyword &quot;insert into&quot; followed by the tablename
    • Then on the next line, in parenthesis, list all the columns you are inserting values for.
    • Then on the line after, type values, then in parenthesis, put the values in the same order as the columns they belong to
  • 26. The Update Statement The UPDATE statement is used to modify the data in a table. Syntax UPDATE table_name SET column_name = new_value WHERE column_name = some_value
  • 27. Update one Column in a Row We want to add a first name to the person with a last name of &quot;Rasmussen&quot;: UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Storgt 67 LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Storgt 67
  • 28. The Delete Statement The DELETE statement is used to delete rows in a table. Syntax DELETE FROM table_name WHERE column_name = some_value
  • 29. Delete a Row &quot;Nina Rasmussen&quot; is going to be deleted: DELETE FROM Person WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Stien 12 Stavanger LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger
  • 30. Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name Or DELETE * FROM table_name
  • 31.
    • Thank You !