* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Lecture 16 PowerPoint
Entity–attribute–value model wikipedia , lookup
Commitment ordering wikipedia , lookup
Oracle Database wikipedia , lookup
Tandem Computers wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Serializability wikipedia , lookup
Microsoft Access wikipedia , lookup
Database model wikipedia , lookup
Concurrency control wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Team Foundation Server wikipedia , lookup
Clusterpoint wikipedia , lookup
Relational model wikipedia , lookup
Instructor: Craig Duckett Lecture 16: Tuesday, May 23rd, 2017 Summary: Stored Procedures, Functions; Introduction: Transactions 1 • Assignment 3 is due LECTURE 20, Tuesday, June 6th • Database Presentation is due LECTURE 20, Tuesday, June 6th • Final Exam is LECTURE 12, Thursday, June 8th 2 3 x 150 Points (450 points Total) • Assignment 1 GRADED! • Assignment 2 GRADED! • Assignment 3 (Stage 3): DUE LECTURE 20 Tuesday, June 6th • Database Presentation: DUE LECTURE 20 Tuesday, June 6th 3 Tuesday/Thursday (LECTURE 16) • Database Design for Mere Mortals: Chapters 12, 13 4 • Stored Procedures Revisited • Functions Revisited • Transactions 5 SQL Server STORED PROCEDURES Revisited SQL Server: Stored Procedure Run Through TERMS • Variable is a container to hold data values while working with the value in a function or stored procedure • Data type describes the "size and shape" of a container that holds data, either a variable or column • SQL Server Global Variable is a function that returns current information SQL Server provides a massive number of global variables, which are very effective to use in our regular Transact-SQL. Global variables represent a special type of variable. The server always maintain the values of these variables. All the global variables represent information specific to the server or a current user session. Global variable names begin with a @@ prefix. You do not need to declare them, since the server constantly maintains them. They are system-defined functions and you cannot declare them. @@connections – the number of logins or attempted logins since SQL Server started @@identity – the auto-incremented ID of the last inserted item @@error – the error number, if any, from the last statement that was executed http://www.codeproject.com/Articles/39131/Global-Variables-in-SQL-Server SQL Server: Stored Procedure Run Through CREATE A STORED PROCEDURE • Start with a specific set of DML statements that do the main work of the procedure. Test this for a variety of different values to see how it works • Add parameter(s) to the DML statements to make the work more general. Include any variables and flow control needed to deal with different possible situations. • Add the header information including a reasonable stored procedure name and the needed parameters along with their data types and default values. • Compile the procedure (run the CREATE command) and test it using the EXECUTE command SQL Server: Stored Procedure Run Through CREATE A STORED PROCEDURE: EXAMPLE SQL Server: Stored Procedure Run Through CREATE A STORED PROCEDURE 1. Open SQL Server 2. 3. 4. 5. Open database folder (From Query): Select New Query Write the procedure, Execute (From Programmability): Right-click on Stored Procedures • Select New Stored procedure… • Write the procedure, Execute SQL Server: Stored Procedure Run Through ENABLING LINE NUMBERS IN QUERY WINDOW 1. 2. 3. 4. 5. 6. 7. 8. Open SQL Server Select Tools from menu bar Select Options Select Text Editor Select Transact-SQL Select General Check Line Numbers OK You can use Control + G to go to a particular line number HINT If you have an error message, you can double-click on the line number in the message to be taken to the coinciding line number in the query SQL Server: Stored Procedure Run Through EXECUTE A STORED PROCEDURE 1. Open SQL Server 2. 3. 4. 5. Open database folder (From Query): Select New Query Write the EXEC statement, Execute (From Programmability): Right-click on Stored Procedures • Right-click on stored procedure • Select Execute Stored Procedure…, Go SQL Server: Stored Procedure Run Through ALTER (Modify) A STORED PROCEDURE 1. Open SQL Server 2. 3. 4. 5. 6. Open database folder Open Programmability Open Stored Procedures Right-click on Stored Procedures • Right-click on stored procedure • Select Modify Make changes, Execute SQL Server: Stored Procedure Run Through ADDING 'GO' EXEC to the ALTER PROCEDURE for TESTING the PROCEDURE 1. Open SQL Server 2. 3. 4. 5. 6. Open database folder Open Programmability Open Stored Procedures Right-click on Stored Procedures • Right-click on stored procedure • Select Modify Make changes, Execute SQL Server: Stored Procedure Run Through RETURNING DATA USING DATA SETS 1. Open SQL Server 2. 3. 4. 5. 6. Open database folder Open Programmability Open Stored Procedures Right-click on Stored Procedures • Right-click on stored procedure • Select Modify Make changes, Execute Enlarged screen cap on next slide SQL Server: Stored Procedure Run Through RETURNING DATA USING DATA SETS SQL Server: Stored Procedure Run Through RETURNING DATA USING DATA SETS HINT You can use Control + R to close the Query Results | Messages Window SQL Server: Stored Procedure Run Through USING SECURITY AND PERMISSIONS SQL Server: Stored Procedure Run Through GIVING A USER LIMITED PERMISSION TO USE A STORED PROCEDURE 1. 2. 3. 4. 5. Open SQL Server Open database folder Open Programmability Open Stored Procedures Right-click on stored procedure • Select Properties • Select Permissions • Select Search • Browse to user, or type in a portion of user name to filter search • Check Permissions to grant, OK SQL Server FUNCTIONS Revisited SQL Server: Function Run Through CREATING A FUNCTION 1. Open SQL Server 2. 3. 4. 5. Open database folder (From Query): Select New Query Write the function, Execute (From Programmability): Right-click on Functions • Select New • Inline Table-valued Function… • Multi-statement Table-valued Function… • Scalar-valued Function… SQL Server: Function Run Through RUNNING A FUNCTION 1. Open SQL Server 2. 3. 4. Open database folder (From Query): Select New Query Write the query, calling the function as part of a SELECT statement, Execute SQL Server: Function Run Through ALTER (Modify) A FUNCTION 1. Open SQL Server 2. 3. 4. 5. Open database folder Open Programmability Open Functions • Right-click on stored procedure • Select Modify Make changes, Execute SQL Server: Function Run Through Common Mistake with Functions • The Data type mismatch • You can CREATE | ALTER a FUNCTION with a data type mismatch, but you cannot call and run it SQL Server: Function Run Through Common Mistakes with Functions • Mixing up RETURNS and RETURN CORRECT INCORRECT SQL Server TRANSACTION First Look SQL Server: Transactions A transaction is a series of steps that perform a logical unit of work. Transactions must adhere to ACID properties, that is: • Atomicity: Either all of the steps must succeed or none of them may succeed. • Consistency: The data must be left in a predictable and usable state. • Isolation: Changes made must not be influenced by other concurrent transactions. • Durability: The changes made must be permanent in the database and survive even system failures. http://www.codeproject.com/Articles/4451/SQL-Server-Transactions-and-Error-Handling SQL Server: Transactions SQL Server records all changes made in the transaction log to allow any changes to be undone (rolled back) or redone (rolled forward) in case of a system failure. When updating or inserting a record into a database, the record is first allocated in buffer memory, and the buffer manager guarantees that the transaction log is written before the changes to the database file are written. It does this by keeping track of a log position using a log sequence number (LSN). Introduction to Log Sequence Numbers http://msdn.microsoft.com/en-us/library/ms190411.aspx What is a LSN? http://rusanu.com/2012/01/17/what-is-an-lsn-log-sequence-number/ Transaction Log Physical Architecture http://msdn.microsoft.com/en-us/library/ms179355.aspx SQL Server: Transactions Why Does the Transaction Log Exist? The transaction log stores a record of all the data modifications performed in a database. In the event of an unexpected shut-down, the data in the transaction log can be used during recovery to roll forward any transactions completed, but not written to the database file on disk at the time of the shut-down. In addition, any uncompleted transactions that were partially written to the database file on disk before the failure can be rolled back during recovery. Both of these actions ensure database integrity and the ACID properties of transactions. This is the reason the Transaction Log exists. SQL Server: Transactions Checkpoints At certain intervals, SQL Server issues a checkpoint in the transaction log that issues a write from the transaction log to the data file. Depending on the setting of the transaction log defined in the database recovery model, the transaction log will keep the committed and written records in the transaction log or truncate the log. Autorecovery This process of working with the transaction log and recording actions in the transaction log before applying them to the actual data files allows SQL Server to recover from failures in case of an unexpected shutdown. SQL Server: Transactions Autorecovery The autorecovery process will check the database to see what the lastissued checkpoint and written log sequence number (LSN) were and will then write all committed records from the transaction log that were not recorded yet in the data file to the data file. This process is a rollforward. Different from other database systems such as Oracle, SQL Server automatically issues a transaction (autocommitted) on every statement, so you don’t need to explicitly commit these transactions. Free Ebook: SQL Server Transaction Log Management https://www.simple-talk.com/books/sql-books/sql-server-transaction-log-management-by-tony-davis-and-gail-shaw/ SQL Server: Transactions Transaction Logs SQL Server uses a buffer cache, which is an in-memory structure, into which it retrieves data pages from disk for use by applications and users. Each modification to a data page is made to the copy of the page in the buffer cache. A modified buffer page in the cache that has not yet been written to disk is called a dirty page. SQL Server: Transactions Transaction Logs The modification is recorded in the transaction log before it is written to disk. For this reason, the SQL Server transaction log is called a write-ahead transaction log. SQL Server has internal logic to ensure that a modification is recorded in the transaction log before the associated dirty page is written to disk. When SQL Server writes the dirty page in the cache to the disk, it is called flushing the page. SQL Server: Transactions Checkpoints The checkpoint process is designed to minimize the recovery time if the server fails by minimizing the number of pages in the buffer cache that have not been written to disk. Checkpoints occur whenever: • • • • A CHECKPOINT statement is issued. The ALTER DATABASE statement is used. An instance of SQL Server is stopped normally. An automatic checkpoint is issued. Automatic checkpoints are generated periodically based on the number of records in the active portion of the transaction log, not on the amount of time that has elapsed since the last checkpoint. SQL Server: Transactions How We Think of Database and Transaction Log Files This is a logical view, not a physical view of the MDF and LDF files. SQL Server: Transactions Looking at the MDF File SQL Server: Transactions Looking at the LDF File SQL Server: Transactions What Are Log Records? Every modification to the database creates multiple log records. Log records describe what is being changed and what the change is. A log record’s size will vary, depending on the nature of the change. Log records are written sequentially (although mixed with other log records) to the log file and stored in Virtual Log Files (VLFs), as previously discussed. Besides log records, extra space in the log is reserved in case a roll back occurs and compensation log records need to be written to the log. This is one reason why logging takes up more space that the actual modification. Log records are assigned LSNs (Log Sequence Number), an ever-increasing, three-part number that uniquely defines the position of a log record within the transaction log , and they are critical as the are used to identify which log records need to be rolled back or rolled forward during recovery. SQL Server: Transactions A VLF Can Be in One of Four States SQL Server: Transactions Simple Transaction Log Example SQL Server: Transactions Log Records Are Added SQL Server: Transactions Transaction Log Backup is Performed SQL Server: Transactions SQL Server: Transactions Log Records Are Added After Backup SQL Server: Transactions SQL Server: Transactions How Are Log Records Written to the Transaction Log? Now that we know a little about how the transaction log works internally, we need to learn how transaction log records are written to the transaction log. It is important to understand how log records are written to the LDF file, as how this works can directly affect the performance of a SQL Server instance SQL Server: Transactions Introducing the Log Buffer SQL Server: Transactions Following the Life of a Transaction Through to the Transaction Log Now that we have a basic understanding of the architecture, let’s look at a specific example . Let’s assume that we have a transaction that wants to INSERT a single row into a table. To keep things simple, let’s assume there is no other activity going on and that the data cache and log buffer are empty. SQL Server: Transactions When a transaction begins, here’s what happens: • A BeginTran log record is written to the log buffer. • A data page is retrieved from disk and put into a page of the data cache. • SQL Server then creates an INSERT log record, which is then added to the log buffer. • The new row is then inserted into the data page stored in the data cache and the page is marked as being dirty. • Now that the row has been inserted, a Commit log record is created and written to the log buffer, and all of the log records associated with the transaction are now flushed (written) to the transaction log file from the log buffer. • This process is known as write-ahead logging. In other words , all data modifications must first be made to the transaction log before it is considered a complete transaction. • Now that the transaction is complete, the client is notified that the batch completed successfully . SQL Server: Transactions A Visual Example SQL Server: Transactions Read Log Activity Every time a transaction has to be rolled back, log records have to be read so the roll back can occur. Creating a database snapshot requires crash recovery to be run, which reads the transaction log. Running DBCC CHECKDB creates a database snapshot as part of its internal process, and as we just noted, creating a database snapshot requires crash recovery to be run, and the transaction log read. Any kind of backup—full, differential, or log—all require the transaction log to be read. http://msdn.microsoft.com/en-us/library/aa258278%28v=sql.80%29.aspx SQL Server: Transactions Read Log Activity If a database is in the simple recovery mode, every time a checkpoint occurs, the transaction log has to be read. Transactional replication reads the transaction log in order to move changes from the publisher to the distributor. Using Change Data Capture uses the transactional replication log reader to track changes, which in turn reads the transaction log. Database mirroring reads the transaction log in order to move changes from the primary to the mirror. SQL Server: Transactions Executing Implicit and Explicit Transactions By default, SQL Server automatically commits a transaction to the database, and every transaction is handled as a single process. Because this process occurs without any explicit request from you to confirm the action, this is called an autocommit. Explicit Transaction: A group of SQL statements enclosed within transaction delimiters that define both the start and end of the transaction. Implicit Transaction: A connection option in which each SQL Statement executed by the connection is considered a separate transaction. SQL Server: Transactions Transaction Rollback When you want to confirm a transaction, you issue a COMMIT TRANSACTION statement. This will close the open statements and confirm the grouped DML statements. If you don’t want a transaction to occur, that is, you want to cause a transaction rollback, you issue a ROLLBACK TRANSACTION statement. SQL Server: Transactions Locks Locks prevent users from reading or modifying data that other users are in the process of changing. Two main types of lock come into play: Read locks: Read locks ensure other users don’t change the data you are retrieving but allow other users to read the data at the same time. Write locks: Write locks ensure no other users can examine or change the data you are updating. SQL Server: Transactions Deadlock A deadlock is a situation when two (or more) users, each having a lock on one piece of data, attempt to acquire a lock on the other’s piece. Unless one of the user processes is terminated, each user would wait indefinitely for the other to release the lock. SQL Server detects deadlocks and terminates one user’s process. SQL Server: Transactions Locks and Serialization Locks permit the serialization of transactions, meaning only one person can change a data element at a time. During a transaction, SQL Server controls and sets the appropriate level of locking. You can control how some locks are used by including locking hints in your query. SQL Server: Transactions Concurrency Specific types of locks allow users to access and update data at the same time. A SELECT may be allowed at the same time as an UPDATE, but the UPDATE blocks a second UPDATE. This concept, known as concurrency, can increase response time from the user’s perspective. Concurrency control means changes made by one person do not adversely affect modifications other users make. SQL Server: Transactions Concurrency There are two types of concurrency control: Pessimistic: Pessimistic concurrency control locks data when data are read in preparation for an update. Optimistic: Optimistic concurrency control does not lock data when data are initially read. SQL Server: Transactions Locks and Transaction Integrity When users access data concurrently, a risk exists that one user’s actions might affect the records another user is accessing. Locks can prevent the following situations that compromise transaction integrity: • • • • Lost updates Uncommitted dependencies (dirty read) Inconsistent analysis (non-repeatable read) Phantom reads SQL Server: Transactions Locks and Concurrent Transactions SQL Server uses different locking modes to control how resources can be accessed by concurrent transactions. These types of locks are: • Shared • Exclusive • Intent • Update • Schema • Bulk update SQL Server: Transactions SQL Server: Transactions SQL Server ERROR-HANDLING Revisited SL Server: Error Handling LINKS OF INTEREST http://www.codeproject.com/Articles/4451/SQL-Server-Transactions-and-Error-Handling https://www.simple-talk.com/sql/t-sql-programming/sql-server-error-handling-workbench/ SL Server: Error Handling Error Handling Terms • Error-handling involves anticipating possible errors and providing program cases for dealing with them gracefully. • A TRY block encloses all statements that may cause an anticipated error • A CATCH block encloses program logic for dealing with an anticipated error • ERROR functions provide useful information about the current system error SL Server: Error Handling Using a TRY-CATCH Block SL Server: Error Handling Transaction Terms • A TRANSACTION is a set of Data Manipulation Language (DML) statements that must hang together: if one of them cannot execute, then none of them should. • A COMMIT statement causes all of the transaction statements to write to the database • A ROLLBACK statement causes all of the transaction statements to clear without writing to the database. SL Server: Error Handling Sample Error Handling with a Transaction SQL Server: Error Handling The TRY…CATCH Block Since the release of SQL Server 2005, you’ve been able to handle errors in your T-SQL code by including a TRY…CATCH block that controls the flow of your script should an error occur, similar to how procedural languages have traditionally handled errors. The TRY…CATCH block makes it easy to return or audit error-related data, as well as take other actions. And within the block—specifically, the CATCH portion—you’ve been able to include a RAISERROR statement in order to re-throw error-related data to the calling application. NOTE: With the release of SQL Server 2012, there is a replacement for RAISERROR, the THROW statement, which makes it easier than ever to capture the error-related data. For THROW information, see http://msdn.microsoft.com/en-us/library/ee677615.aspx SQL Server: Error Handling This stored procedure will delete an owner/user and all of the toys associated with the owner/user, given the user/owner Name SQL Server: Error Handling SQL Server: Error Handling The main body of the procedure definition, enclosed in the BEGIN…END block, contains the TRY…CATCH block, which itself is divided into the TRY block and the CATCH block. The TRY block starts with BEGIN TRY and ends with END TRY and encloses the T-SQL necessary to carry out the procedure’s actions. In this case, I include a DELETE statement that will delete an owner and all the toys associated with that owner. Examples vary in terms of where they include the transaction-related statements. (Some don’t include the statements at all.) Just keep in mind that you want to commit or rollback your transactions at the appropriate times, depending on whether an error has been generated. SQL Server: Error Handling If the DELETE statement runs successfully, the User value is deleted and the operation is completed, in which case, the code in the CATCH block is never executed. However, if the DELETE statement fails and SQL Server generates an error, the transaction is terminated and the database engine jumps to the CATCH block. For the DeleteOwnerEH stored procedure, the first step I take in the CATCH block is to roll back the transaction if it is still running. I start by using the @@TRANCOUNT function to determine whether any transactions are still open. @@TRANCOUNT is a built-in SQL Server function that returns the number of running transactions in the current session. In this case, there should be only one (if an error occurs), so I roll back that transaction. SQL Server: Error Handling Next, I declare a set of variables based on system functions that SQL Server makes available within the scope of the CATCH block. The functions return error-related information that you can reference in your T-SQL statements. Currently, SQL Server supports the following functions for this purpose: • • • • • • ERROR_NUMBER( ): The number assigned to the error. ERROR_LINE( ): The line number inside the routine that caused the error. ERROR_MESSAGE( ): The error message text, which includes the values supplied for any substitutable parameters, such as times or object names. ERROR_SEVERITY( ): The error’s severity. ERROR_STATE( ): The error’s state number. ERROR_PROCEDURE( ): The name of the stored procedure or trigger that generated the error. For this example, I use all but the last function, though in a production environment, you might want to use that one as well. SQL Server: Error Handling After I declare the variables, I include two PRINT statements that display the values of the @ErrorNumber and @ErrorLine variables (along with some explanatory text). The reason I do this is to demonstrate the difference between what the actual values are and what the RAISERROR statement returns, as you’ll see shortly. The RAISERROR statement comes after the PRINT statements. The statement returns error information to the calling application. Generally, when using RAISERROR, you should include an error message, error severity level, and error state. The rules that govern the RAISERROR arguments and the values they return are a bit complex and beyond the scope of this class, but for the purposes of this example, I simply pass in the @ErrorMessage, @ErrorSeverity, and @ErrorState variables as arguments. RAISERROR Information http://msdn.microsoft.com/en-us/library/ms178592.aspx SQL Server: Error Handling As expected, the information we included in the CATCH block has been returned. But notice that the actual error number (547) is different from the RAISERROR message number (50000) and that the actual line number (10) is different from the RAISERROR line number (28). In theory, these values should coincide. But as I mentioned earlier, the rules that govern RAISERROR are a bit quirky http://msdn.microsoft.com/en-us/library/ms178592%28v=sql.105%29.aspx SQL Server: Error Handling SQL Server SECURITY LEVELS A First Look SQL Server: Security LINKS OF INTEREST Security Considerations for SQL Server http://msdn.microsoft.com/en-us/library/ms161948.aspx SQL Server Security Best Practices http://www.greensql.com/content/sql-server-security-best-practices SQL Server: Security Data Manipulation Language (DML) and Data Definition Language (DDL) statements comprise the lion’s share of the code we are expected to know in SQL. When it comes time to allow a new user to work with SQL Server, we should understand what it takes to create an account for them and how permissions and security work. This section discusses how to set the level of access to SQL Server using Data Control Language (DCL) statements. Introduction to Security Security in SQL Server starts by creating types of accounts such as logins and user. It is essential to know how to create logins and then GRANT or DENY them the required permissions. There are different types of logins for different networks and different ways to set security. That subject itself is an entire other course! In this section, we’ll get familiar with the most common security terms. SQL Server: Security Securables and Permissions Okay, a scenario: Rex Winkus works at Contoso, Ltd and wants to access the printer to print out a report. The printer does not need to access Rex, but it does need to know who is making the request. Since Rex wants access, he is known as the principal. The printer he wishes to access is known as the securable. Permissions control the level of access principals have to securables. In reality the principal, Rex, has no permissions. The list of permissions resides with the securable. The printer is the securable and contains a list of principals and permissions. When a match is found, the securable allows its use by the authorized principal. There are many types of principals in SQL Server. The type of principal we'll learn about today is called a login. Logins will want access to securables such as resources, databases, and tables. SQL Server: Security Creating SQL Logins Logins are the principals for the SQL Server security scope. To create logins, we use the CREATE keyword. The following code creates the login named RexWinkus with the ABCDEFG password: USE master GO CREATE LOGIN RexWinkus WITH PASSWORD='ABCDEFG' This code will likely not work, depending on the operating system this instance of SQL Server is running on. Beginning with SQL Server 2005, SQL Server likes to enforce the same level of password policies that Windows Server is running. Windows Server does not consider passwords secure if they contain only alphabetical characters. If SQL Server is enforcing password complexity, it will issue an error message: SQL Server: Security Creating SQL Logins Most password complexity requirements call for at least seven characters with at least one numeral and one capital letter. The code sample shown shown here will create the RexWinkus login without an error. Once the Winkus login is created, we can verify it with the Object Explorer. We simply need to navigate to the Logins folder located inside the Security folder to see the login named Winkus amongst several others. Object Explorer > Security > Logins > RexWinkus Currently SQL Server knows about RexWinkus and his password, but no permissions to securables have yet been granted to him. By default, new accounts get public level permissions, which means RexWinkus can login and browse the database list. However, he would have no permissions to open, use or query databases or tables. SQL Server: Security Authentication Modes When we open SQL Server Management Studio, SQL Server wants to know who we are. One way to do this is with a password like the one given to RexWinkus. If we are already logged into a Windows Operating System with a password, SQL Server can ask Windows for our login token for authentication and not ask us again while it is running. This is "Geek Speak" for saying SQL Server can authenticate us manually, or trust that Windows has already effectively done this. When SQL Server is configured for Windows Authentication mode, we will not be allowed access when logging in with a SQL Server password. We can try this out for ourselves by logging in as RexWinkus with the ABC$$123 password using the SQL Server Authentication mode. SQL Server: Security Authentication Modes CONTINUED While in the Connect to Server dialog box, use the Authentication drop-down list to choose SQL Server Authentication. The dialog box will refresh immediately and enable the Login and Password text entry boxes. Type RexWinkus into the Login box and type ABC$$123 into the Password text box and then click the Connect button. SQL Server: Security Authentication Modes CONTINUED Had the SQL Server properties been configured differently, you might have received an error message when you tried to login as RexWinkus using the SQL Server Authentication. To find out why we received an error message with SQL Server Authentication, we will need to use the Object Explorer to access the System properties. Right-click the instance of SQL Server at the top of the Object Explorer panel, then select Properties and the Server Properties dialog box will come up. SQL Server: Security Authentication Modes CONTINUED SQL Server is often set up to let Windows do all authentications, so it will recognize us by our Windows login. If we want SQL Server to only allow logins to be authenticated by Windows, then we would set the Server authentication to Windows Authentication mode. Likewise, if we wanted SQL Server to handle all login authentication for nonWindows accounts, we would use the setting for SQL Server and Windows Authentication mode. It is possible to configure SQL Server to allow RexWinkus to login via his account. We can make this change while still on the Security page by simply clicking on the SQL Server and Windows Authentication mode radio button and then clicking the OK button to register this change with SQL Server. SQL Server: Security Authentication Modes CONTINUED In order to make this change to SQL Server allowing RexWinkus to login using SQL Server Authentication mode, SQL Server needs to be manually stopped (turned off) and restarted. Just closing out of the SQL Server Management System (SSMS) console window will not accomplish this. To manually stop and restart SQL Server you need to use the SQL Server Configuration Manager in Start > All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager. SQL Server: Security Dropping SQL Logins If we wanted to get rid of a login, we only need to know the name of the login. Let’s say we had created a login named Bernie with the following code: CREATE LOGIN Bernie WITH PASSWORD = 'ABC$$321' Time goes by and now Bernie no longer works for our organization, so we want to remove his access to SQL Server. This is as easy as writing the following code: DROP LOGIN Bernie Dropping a login is rare and must be done carefully. Once a login has been dropped, there is no way to get it back. If we made a mistake and learned that Bernie was actually still with the organization, we would need to recreate a brand new login for him. SQL Server does not allow logins to be reused or reinstated. When working with logins we no longer need, it is considered to be a best practice to disable them, rather than dropping them altogether. To disable the Bernie login, we would use the code sample shown here: ALTER LOGIN Bernie DISABLE SQL Server: Security Granting Permissions RexWinkus can login to SQL Server, but he can do virtually nothing in it. When clicking on a database, he is unceremoniously denied access. RexWinkus might try another way to gain access to a database (like toy_auction_v3, for example) by running a query, but once again SQL Server will deny him entrance, with a message stating the server principal "RexWinkus" is not able to access the database. SQL Server: Security Granting Permissions CONTINUED Now, RexWinkus does have access to the master database but will be unable to access any user databases until appropriate permissions are granted. To double-check that RexWinkus does, indeed, have access to master, I run a quick query to confirm. The master database is a powerful database. From there we can drop other databases. Does RexWinkus have the power to drop users databases from within the master database context? SQL Server: Security Granting Permissions CONTINUED RexWinkus may use the master database context, but may not perform any DDL statements (CREATE, ALTER or DROP). Attempting to do so will result in an error message about permissions. The zTest2013 database is a securable, and the RexWinkus principal wants some level of access to it. We can change the securable to authorize RexWinkus by giving him permissions. The GRANT keyword adds permission listings that allow principals access to these securables. SQL Server: Security Authentication Modes CONTINUED NOW, Although RexWinkus can login to SQL Server using SQL Server Authentication mode and he can see all the databases, he is still unable to access any of them. Double-clicking on any of the databases will produce an error message. SQL Server: Security Granting Permissions CONTINUED There are different levels of permissions for each securable. We might want total control for a database while another user just needs to make DDL changes. NOTE: The following example is for a fictitious login and will not actually run. The sample shown here will GRANT the Rick login control of the entire server: USE Master GO GRANT CONTROL SERVER TO Rick GO The principal is Rick and the securable is the server. The level of permission that the server is granting to Rick is called control. Control allows a login account to run all DML, DDL and DCL statements for any database on the server. Log in as an administrator (Windows login) to issue Data Control Language (DCL) statements, such as GRANT. SQL Server: Security Granting Permissions CONTINUED Oftentimes the control level of permissions is higher than an employee really needs. For RexWinkus, we want to allow him to CREATE, ALTER or DROP databases. A DBA could GRANT RexWinkus the ability to alter any database with this code: USE master GO GRANT ALTER ANY DATABASE TO RexWinkus GO However, if all we really want is to allow RexWinkus to have access to a specific database and not the whole shebang, then we could do so in a short query: SQL Server: Security Granting Permissions CONTINUED While giving RexWinkus login rights to a database will permit him to click on and open a database, it does not actually permit him to do anything while he is there (he cannot see any of the database tables, for instance). For this to happen, he needs to be given explicit permissions. SQL Server: Security Granting Permissions CONTINUED As an administrator or database owner, I can elevate RexWinkus to a particular role within a database, by executing the SQL Server stored procedure sp_addrolemember (of, course I can also do this through the SQL Server Management Studio interface). SQL Server: Security Granting Permissions CONTINUED Now when I login as RexWinkus, I can successfully access AND see all the elements of the databases I've been added the role of db_owner, and use the database tables, stored procedures, functions, etc. SQL Server: Security Revoking and Denying Permissions We learned that the GRANT keyword is a DCL statement that creates permissions on a securable and grants these permissions to a principal. OK, that is geek speak again, so let’s use an example. With the GRANT keyword, we instructed the server (securable) to allow control (permission level) to Rick (principal). Principal Securable Permissions Rick SQL Server Control Server = Grant Alter Any Database = Grant We also learned that we can give a user permission to access and control a specific database by first slowing them login capability and then elevating his or her role to that of db_owner (of course there are a slew of others roles available besides db_owner) Database-Level Roles http://msdn.microsoft.com/en-us/library/ms189121.aspx SQL Server: Security Revoking and Denying Permissions CONTINUED Previously, the administrator had granted Rick to ability to control the Server, but what if the administrator wanted Rick to be able to do everything except alter any database? The administrator could simply run a query that would keep the control server but remove the ability to alter databases. DENY ALTER ANY DATABASE TO Rick Now Rick can go in and access and use any of the databases available, but he is unable to create a new database or drop any of the old ones. If it is realized that Rick actually does need to be able to alter (create or drop) existing databases, then the 'DENY ALTER' can be revoked. Revoke sounds like a penalty or a roadblock to someone’s permissions. This indeed can be the case, as REVOKE takes away Grants. REVOKE also removes denied permissions. In reality, the REVOKE would free up Rick. The following code would again give Rick complete control over the server again: REVOKE ALTER ANY DATABASE TO Rick GO SQL Server: Security SQL Injection A SQL injection attack consists of insertion or "injection" of a SQL query via the input data from the client to the application. A successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), execute administration operations on the database (such as shutdown the DBMS), recover the content of a given file present on the DBMS file system and in some cases issue commands to the operating system. SQL injection attacks are a type of injection attack, in which SQL commands are injected into data-plane input in order to effect the execution of predefined SQL commands. • • • SQL injection attacks allow attackers to spoof identity, tamper with existing data, cause repudiation issues such as voiding transactions or changing balances, allow the complete disclosure of all data on the system, destroy the data or make it otherwise unavailable, and become administrators of the database server. SQL Injection is very common with PHP and ASP applications due to the prevalence of older functional interfaces. Due to the nature of programmatic interfaces available, J2EE and ASP.NET applications are less likely to have easily exploited SQL injections. The severity of SQL Injection attacks is limited by the attacker’s skill and imagination, and to a lesser extent, defense in depth countermeasures, such as low privilege connections to the database server and so on. In general, consider SQL Injection a high impact severity. SQL Server: Security SQL Injection LINKS OF INTEREST SQL Injection http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx SQL Injection Walkthrough http://www.securiteam.com/securityreviews/5DP0N1P76E.html SQL Injection Attacks by Example http://www.unixwiz.net/techtips/sql-injection.html SQL Injection Attacks and Some Tips on How to Prevent Them http://www.codeproject.com/Articles/9378/SQL-Injection-Attacks-and-Some-Tips-on-How-to-Prev SQL Injection Cheat Sheet