Professional Documents
Culture Documents
Testers Preparation Guide
Testers Preparation Guide
Testing consultants
MS-BUIT OASIS Onsite
Table of Contents
Document Change History......................................................................................................... 3
1.
Introduction.......................................................................................................................... 4
2.
Questions.............................................................................................................................. 5
2.1.
2.2.
2.3.
2.4.
MS SQL Server Interview Questions with Expected Answers.......................................17
2.4.1.
Basics................................................................................................................. 17
2.4.2.
T-SQL Programming........................................................................................... 18
3.
3.2.
Physical Database Organization...................................................................................28
3.2.1.
Table and Index Architecture...............................................................................28
3.2.2.
Organization of Data Pages................................................................................28
3.3.
Indexes......................................................................................................................... 30
3.3.1.
Clustered Indexes...............................................................................................31
3.3.2.
Nonclustered Indexes......................................................................................... 31
3.4.
Using Joins................................................................................................................... 32
3.4.1.
Using Cross Joins............................................................................................... 33
3.4.2.
Null Values and Joins.......................................................................................... 34
3.4.3.
Using Outer Joins................................................................................................35
3.4.4.
Using Left Outer Joins......................................................................................... 35
3.4.5.
Using Right Outer Joins......................................................................................37
3.4.6.
Using Full Outer Joins.........................................................................................38
3.4.7.
Using Self-Joins.................................................................................................. 40
3.5.
Constraints.................................................................................................................... 41
3.5.1.
Classes of Constraints........................................................................................ 41
3.5.2.
Column and Table Constraints............................................................................43
3.6.
SQL Server security model........................................................................................... 44
3.6.1.
Login................................................................................................................... 44
3.6.2.
User.................................................................................................................... 44
3.6.3.
Fixed server roles................................................................................................46
3.6.4.
Fixed database roles........................................................................................... 47
3.6.5.
Application roles.................................................................................................. 47
3.7.
3.8.
Confidential
Page 2 of 57
1.1.
Version No
1.0
1.1
Date created
31st October
2005
14th November
2005
Author
Vinay Sundarapalli
Vinay Sundarapalli
Confidential
Description of Change
FAQs and reading material for
Testers.
Updated with more FAQs on Testing
and some answers for existing ones.
Page 3 of 57
2. Introduction
The purpose of this Guide is to help our consultants (Testers) succeed in Microsoft
Redmond Interviews.
This document covers most of the interview questions in various topics such as Testing,
SQL Server, data warehouse, and basic .NET concepts. Also reading material included
for the above mentioned areas.
Confidential
Page 4 of 57
3. Questions
3.1.
Testing interview Questions
Following list include questions for Tester as well for Test Lead. Interviewer evaluates
the candidates real time experience and in-depth knowledge of testing process. Answers
are not given for some of the questions.
1.
Confidential
Page 5 of 57
1.Context Sensitive:
Records your Operations in terms of GUI Object in your application.
WinRunner identifes each object you click (window, menu, list or button), and the
type of operation you perform (press, enable, move or select).
2. Analog:
WinRunner records the exact co-ordinates travelled by the mouse, as well
as mouse clicks and keyboard inputs.
Choose Context Sensitive mode if:
a. The Application contains GUI objects.
b. Exact mouse movements are not required.
c. Plan to reuse the test in different versions of the application.
Choose Analog mode if:
a. The Application contains bitmap areas.
b. Exact mouse movements are required.
7. What are the check points in winrunner and Types of check points
Checkpoints allow you to compare the current behavior of the application being
tested to its behavior in an earlier version.
GUI Checkpoints verify information about GUI obects.
Bitmap Checkpoints take a "snapshot" of a window or area of application and
compare this to an image captured in an earlier version.
Text Checkpoints read text in GUI objects and in bitmaps and enable you to verify
their contents.
Database Checkpoints check the contents and number of rows and columns of a
result set, which is based on a query you create on your database.
8. What is TSL
When you record a test, a test script is generated in Mecury Interactive's
Test Script Language. Each TSL statement in the test script represents keboard
and/or mouse input to the application being tested.
TSL is a C-like programming language designed for creating test scripts. It
combines functions developed specifically for testing with general purpose
programming language features such as variables, control-flow statements, arrays
and user defined functions. You can enhance a recorded test script simply by
typing programming elements into the test window.
9. What is System testing and integration testing
Confidential
Page 6 of 57
System testing - black box type testing that is based on overall requirement
specifications; covers all combined parts of a system.
Integration testing - An integration test verifies that all the parts of an application
"Integrate" together or work as expected together. This is important because after all the
units are tested individually we need to ensure that they are tested progressively.
10. Have u done Integration testing.?
11. Who will do integration testing, is it tester or developer?
12. What is the BVA (Boundary Value Analysis)?
13. What is the Equivalence partitioning testing?
14. Have u done components testing if yes how is the process?
15. What is regression testing
Regression testing is re-testing after fixes or modifications of the software or its
environment.
The selective retesting of a software system that has been modified, to ensure that
any bugs have been fixed and that no other previously working functions have
failed as a result of the modification and that newly added features have not
created problems with previous versions of the software.
16. How do u write test cases
17. What are the testing techniques used for writing the test cases.
18. Have u done any programming.
19. If their r four modules A, B, C, D, development of each module takes 1 month
time then how do u plan integration testing.
20. Tell some 5 function names in Winrunner
Function Categories - Analog functions, Context-sensitive functions,
customization function and Standard Functions.
Analog functions - check_window (compares bitmap of an AUT window to an
expected bitmap)
click, click_on_text, dbl_click, get_x, get_y, wait_window
Context Sensitive - obj_check_bitmap, win_check_bitmap, button_press,
button_set, button_check_info, button_check_state, db_check, db_connect,
db_disconnect, db_execute_query, db_get_field_value
21. As u said that u r leading a team of 2 members how will u motivate the team
point out their plus points, even if they fail to commit activities. Tell them how to
meet commitments in future. keep monitor them, analyze, give feedback.
22. If u are to do regression testing for n number of times, do u think doing the same
work is a boring?
Confidential
Page 7 of 57
Confidential
Page 8 of 57
Confidential
Page 9 of 57
84. How do you troubleshoot when 404 err occurs while trying to access a website
application?
85. Dev is unable to repro the bug. What would you do?
86. How do you log a bug in the product studio? Ans: Bug Description, Title, Reprosteps, expected result, actual results, defect screen shots etc.
87. How do you set severity of a bug? Ans: explain different severity levels
88. What would you test when a new column is added in a table and there is a view
already exists on that table?
89. How do you validate data that is moved from a source server to destination
server? Write the queries if any?
90. Describe yourself and your job experience? Ans: give more info about your job
experience and roles & responsibilities.
91. Explain your previous project architecture?
92. What is a Triage meeting? What is the need of it and who all participate in it?
Who drives it? Ans: Triage meeting will be driven by Test Lead to primarily
discuss the priority level of the bug resolution. Mandatory participants would be
Test lead, Dev Lead, Business analyst, Program manager.
93. How do you test a Web service?
94. Where do you check event log?
95. What are all different categories of test cases for testing a website like
hotmail.com?
96. What is performance testing? Give an example
97. Why do you think we should give you this job?
98. Write test cases for a word application over web. It is a scenario that the word
application is available over web and users can subscribe it for a day or month or
a year and so on. You have to write test cases to test this feature.
99. Explain SDLC process and what would be the test involvement at each phase?
100. You are a test lead and you have all the test cases and scripts ready to test a
software. Required time for test pass is five days and your Dev manager wants to
complete the test pass in 3 days. How do you handle this situation?
101. What is Localization testing? How do you perform it?
102. Explain SDLC process as per x-BUIT standards? And what is the exit criteria in
each phase?
103. How do you install a build/drop in test environment? Ans: Test expects a
build/drop installation notes with the release and build engineer or QA team
would install the drop based on the install notes provided.
104. How do you perform test estimation for a project?
3.2.
.NET and C# questions
Sometimes there are requirements where the candidate should have both development
as well as test experience. Having basic knowledge is sufficient to get thru.
1.
Confidential
Page 10 of 57
2. write a function to find distance between two points? (Ans: Square root of (a2 +
b2))
3. Write code or algorithm to check a point in a rectangle.
4. Algorithm to find out a duplicate element in a integer array
containing 1001 elements without accessing the array variable more than once.
5. What is difference between Const & ReadOnly keywords?
6. What you do and don't like with C# language?
7. How do you load xml from an xml file into a Dataset?
8. What is .Net frame work all about
Its a framework with some standards. So that all applications which written
with .net can run virtually any machine / os/ hardware which supports .net
framework. its o/s indepenedent/ language independent/ vendor independent. A
dll we wrote in C# can be accessible with VB.NET
9. Winforms: what are different methods you have in a mouse event?
10. write a function in C# for Anagrams check.
Ex: str1= DEAL, Str2=LEAD Pass
Str1=SALESMAN, str2=SALESMEN fail
11. What is .NET?
12. What is MSIL?
13. What is CLR?
14. What is CLS?
15. What is CTS?
16. What is assembly? Difference between shared assembly and private assembly?
17. What is application domain?
18. What is Reflection?
19. What is a manifest?
20. Difference between managed code and unmanaged code?
21. What is the use of VS.NET?
3.3.
This is a set of more than a hundred Microsoft Testing interview questions. Testers
are expected to have good knowledge in SQL Server. Some questions listed below are
open-ended, and some of them do not have answer.
1. What is normalization? - Well a relational database is basically composed of
tables that contain related data. So the Process of organizing this data into tables is
actually referred to as normalization.
2. What is a Stored Procedure? - Its nothing but a set of T-SQL statements combined
to perform a single task of several tasks. Its basically like a Macro so when you
invoke the Stored procedure, you actually run a set of statements.
3. Can you give an example of Stored Procedure? - sp_helpdb , sp_who2,
sp_renamedb are a set of system defined stored procedures. We can also have user
defined stored procedures which can be called in similar way.
Confidential
Page 11 of 57
Confidential
Page 12 of 57
percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any
damage.
16. What command do we use to rename a db? - sp_renamedb oldname , newname
17. Well sometimes sp_reanmedb may not work you know because if some one is
using the db it will not accept this command so what do you think you can do in
such cases? - In such cases we can first bring to db to single user using
sp_dboptions and then we can rename that db and then we can rerun the
sp_dboptions command to remove the single user mode.
18. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Having Clause is basically used only with the GROUP BY function in a query.
WHERE Clause is applied to each row before they are part of the GROUP BY
function in a query.
19. What would you test when a new column is added in a table and there is a view
already exists on that table?
20. What is a Join in SQL Server? - Join actually puts data from two or more tables
into a single result set.
21. Can you explain the types of Joins that we can have with Sql Server? - There are
three types of joins: Inner Join, Outer Join, Cross Join
22. When do you use SQL Profiler? - SQL Profiler utility allows us to basically track
connections to the SQL Server and also determine activities such as which SQL
Scripts are running, failed jobs etc..
23. What is a Linked Server? - Linked Servers is a concept in SQL Server by which
we can add other SQL Server to a Group and query both the SQL Server dbs
using T-SQL Statements.
24. Write a query to display duplicate records?
25. Which stored procedure will you be running to add a linked server? sp_addlinkedserver, sp_addlinkedsrvlogin
26. What are the OS services that the SQL Server installation adds? - MS SQL
SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac coordinator)
27. Can you explain the role of each service? - SQL SERVER - is for running the
databases SQL AGENT - is for automation such as Jobs, DB Maintanance,
Backups DTC - Is for linking and connecting to other SQL Servers
28. What are the authentication modes in SQL Server? - Windows mode and mixed
mode (SQL & Windows).
29. Where do you think the users names and passwords will be stored in sql server? They get stored in master db in the sysxlogins table.
30. What is log shipping? Can we do logshipping with SQL Server 7.0
Logshipping is a new feature of SQL Server 2000. We should have two SQL
Server - Enterprise Editions. From Enterprise Manager we can configure the
logshipping. In logshipping the transactional log file from one server is
automatically updated into the backup database on the other server. If one server
fails, the other server will have the same db and we can use this as the DR
(disaster recovery) plan.
31. Let us say the SQL Server crashed and you are rebuilding the databases
including the master database what procedure to you follow?
Confidential
Page 13 of 57
For restoring the master db we have to stop the SQL Server first and then from
command line we can type SQLSERVER m which will basically bring it into the
maintenance mode after which we can restore the master db.
32. Let us say master db itself has no backup. Now you have to rebuild the db so
what kind of action do you take? - (I am not sure- but I think we have a
command to do it).
33. What is BCP? When do we use it? - BulkCopy is a tool used to copy huge
amount of data from tables and views. But it wont copy the structures of the
same.
34. What should we do to copy the tables, schema and views from one SQL
Server to another? - We have to write some DTS packages for it.
35. What are the different types of joins and what does each do?
36. What are the four main query statements?
37. What is a sub-query? When would you use one?
38. What are three SQL keywords used to change or set someones permissions?
39. What is the difference between HAVING clause and the WHERE clause?
40. What is referential integrity? What are the advantages of it?
41. What is database normalization?
42. Which command using Query Analyzer will give you the version of SQL server
and operating system?
43. Using query analyzer, name 3 ways you can get an accurate count of the number
of records in a table?
44. What is a trigger?
45. What is an execution plan? When would you use it? How would you view the
execution plan?
46. What is the STUFF function and how does it differ from the REPLACE function?
47. What does it mean to have quoted_identifier on? What are the implications of
having it off?
48. What are the different types of replication? How are they used?
49. What is the difference between a local and a global variable?
50. What is the difference between a Local temporary table and a Global temporary
table? How is each one used?
51. What are cursors? Name four types of cursors and when each one would be
applied?
52. What is the purpose of UPDATE STATISTICS?
53. How do you use DBCC statements to monitor various aspects of a SQL server
installation?
54. How do you load large data to the SQL server database?
55. How do you check the performance of a query and how do you optimize it?
56. How do SQL server 2000 and XML linked? Can XML be used to access data?
57. What is SQL server agent?
58. What is referential integrity and how is it achieved?
59. What is indexing?
60. What is normalization and what are the different forms of normalizations?
61. Difference between server.transfer and server.execute method?
Confidential
Page 14 of 57
Confidential
Page 15 of 57
101. Difference between truncate and delete and which is the fastest and what are the
disadvantages of it?
102. Why do we go for recompile and when does recompile happen and how to force
it? Various ways to force recompiling in the SP?
103. How will you find poorly performing queries?
104. How will tune the poorly performing queries? What are the strategies you
follow?
105. Difference between subquery and Correlated subquery?
106. Different type of temporary tables
107. How Many indexes can be created in a view and what r the rules?
108. Architecture of your recent project?
109. how will you get XML output from sql queries
110. OLAP concepts? Star schema?
111. What is the process followed in the Development and unit testing? How do u
document unit testing?
112. Have you worked on replication? What are the different types of replication?
113. How do I create a # table inside a trigger?
114. I want to create a # table without using create table #table name. How do I do
that?
115. What are the drawbacks of using of using a # table?
116. I have Table A with two columns C1(primary key) & C2, I have used select *
into Table B from Table B. Now I would like to compare the data is Table A and
Table B. Please use the board and write a query?
117. Suppose I have Server A, and Server B. I want to read the data from Server B
and insert data into a table in Server A. How would I do that?
118. What is the difference between the OLTP database and OLAP database?
119. Query to get employees hired between two given particular dates
120.
x_Emp table:
Emp_id
Name
Dept
Supervisor
y_Emp table:
Emp_id
Payrate
StartDate
Enddate
Write a query to get Emp name, supervisor, Payrate for all employees without
using JOIN.
Confidential
Page 16 of 57
Interview with Ken Agogila, Jagan, Renata and 2 more persons on 21st Nov at Samm-C
1.
2.
3.
4.
5.
6.
7.
Confidential
Page 17 of 57
Confidential
Page 18 of 57
Confidential
Page 19 of 57
3.4.
What are the new features introduced in SQL Server 2000 (or the latest release of SQL
Server at the time of your interview)? What changed between the previous version of SQL
Server and the current version?
This question is generally asked to see how current your knowledge is. Generally there is
a section in the beginning of the books online titled "What's New", which has all such
information. Of course, reading just that is not enough; you should have tried those things
to better answer the questions. Also check out the section titled "Backward
Compatibility" in books online which talks about the changes that have taken place in the
new version.
What are constraints? Explain different types of constraints.
Constraints enable the RDBMS enforce the integrity of the database automatically,
without needing you to create triggers, rule or defaults.
Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN
KEY
For an explanation of these constraints see books online for the pages titled:
"Constraints" and "CREATE TABLE", "ALTER TABLE"
What is an index? What are the types of indexes? How many clustered indexes can be
created on a table? I create a separate index on each column of a table. what are the
advantages and disadvantages of this approach?
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve
the data quicker.
Indexes are of two types. Clustered indexes and non-clustered indexes. When you create
a clustered index on a table, all the rows in the table are stored in the order of the
clustered index key. So, there can be only one clustered index per table. Non-clustered
indexes have their own storage separate from the table data storage. Non-clustered
indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes
having the index key and its row locater. The row located could be the RID or the
Clustered index key, depending up on the absence or presence of clustered index on the
table.
If you create an index on each column of a table, it improves the query performance, as
the query optimizer can choose from all the existing indexes to come up with an efficient
execution plan. At the same time, data modification operations (such as INSERT,
UPDATE, DELETE) will become slow, as every time data changes in the table, all the
Confidential
Page 20 of 57
indexes need to be updated. Another disadvantage is that, indexes need disk space, the
more indexes you have, more disk space is used.
3.4.2.
T-SQL Programming
Page 21 of 57
Confidential
Page 22 of 57
/* The following command links 'sa' login on SERVER_02 with the 'sa' login of
SERVER_01 */
EXEC sp_addlinkedsrvlogin @rmtsrvname = 'SERVER_01', @useself = 'false',
@locallogin = 'sa', @rmtuser = 'sa', @rmtpassword = 'sa password of SERVER_01'
GO
SELECT a.title_id
FROM SERVER_01.pubs.dbo.titles a
INNER JOIN SERVER_02.pubs.dbo.titles b
ON a.title_id = b.title_id
GO
Stored Procedures
How to get the complete error message from T-SQL while error handling?
Unfortunately, the error handling capabilities of SQL Server are limited. When an error
occurs, all you can get is the error number, using the @@ERROR global variable. There
is no @@ERROR_MESSAGE global variable to get the error description.
For a complete error message, you can always query the master..sysmessages table using
the error number, but most of these messages have place holders (like %s, %l etc.), and
hence we can't get the complete error message.
However, the client applications using an object model such as RDO, ADO have access
to the complete error message.
How to get the first day of the week, last day of the week and last day of the month using
T-SQL date functions?
Here's the code:
DECLARE @Date datetime
SET @Date = '2001/08/31'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 1),@Date) AS 'First day of the
week'
SELECT DATEADD(dd,-(DATEPART(dw, @Date) - 7),@Date) AS 'Last day of the
week'
SELECT DAY(DATEADD(d,
-DAY(DATEADD(m,1,@Date)),DATEADD(m,1,@Date))) AS 'Last day of the month'
How to pass a table name, column name etc. to the stored procedure so that I can
dynamically select from a table?
Basically, SELECT and other commands like DROP TABLE won't let you use a variable
instead of a hardcoded table name. To overcome this problem, you have to use dynamic
Confidential
Page 23 of 57
sql. But dynamic SQL has some disadvantages. It's slow, as the dynamic SQL statement
needs to be parsed everytime it's executed. Further, the user who is executing the
dynamic SQL string needs direct permissions on the tables, which defeats the purpose of
having stored procedures to mask the underlying tables. Having said that, here are some
examples of dynamic SQL: (Also see sp_executesql in SQL Server Books Online)
CREATE PROC DropTable
@Table sysname
AS
EXEC ('DROP TABLE ' + @Table)
GO
EXEC DropTable 'MyTable'
GO
CREATE PROC SelectTable
@Table sysname
AS
EXEC ('SELECT * FROM ' + @Table)
GO
EXEC SelectTable 'MyTable'
For a complete discussion on the pros and cons of dynamic SQL check out Erland's
article:
The curse and blessings of dynamic SQL
How to save the output of a query/stored procedure to a text file using T-SQL?
T-SQL by itself has no support for saving the output of queries/stored procedures to text
files. But you could achieve this using the command line utilities like isql.exe and
osql.exe. You could either invoke these exe files directly from command prompt/batch
files or from T-SQL using the xp_cmdshell command. Here are the examples:
From command prompt:
osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC sp_who2" -o "E:\output.txt"
From T-SQL:
EXEC master..xp_cmdshell 'osql.exe -S YourServerName -U sa -P secretcode -Q "EXEC
sp_who2" -o "E:\output.txt"'
Query Analyzer lets you save the query output to text files manually. The output of stored
procedures that are run as a part of a scheduled job, can also be saved to a text file.
BCP and Data Transformation Services (DTS) let you export table data to text files.
Confidential
Page 24 of 57
What are cursors? Explain different types of cursors. What are the disadvantages of
cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the resultsets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for
more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a
network roundtrip, where as a normal SELECT query makes only one rowundtrip,
however large the resultset is. Cursors are also costly because they require more
resources and temporary storage (results in more IO operations). Furthere, there are
restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an
example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike
In this situation many developers tend to use a cursor, determine each employee's salary
and update his salary according to the above formula. But the same can be achieved by
multiple update statements or can be combined in a single UPDATE statement as shown
below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
Another situation in which developers tend to use cursors: You need to call a stored
procedure when a column in a particular row meets certain condition. You don't have to
use cursors for this. This can be achieved using WHILE loop, as long as there is a unique
key to identify each row. For examples of using WHILE loop for row by row processing,
check out the 'My code library' section of my site or search for WHILE.
Triggers
What are triggers? How many triggers you can have on a table? How to invoke a trigger
on demand?
Triggers are special kind of stored procedures that get executed automatically when an
INSERT, UPDATE or DELETE operation takes place on a table.
Confidential
Page 25 of 57
In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for
UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone,
and you could create multiple triggers per each action. But in 7.0 there's no way to
control the order in which the triggers fire. In SQL Server 2000 you could specify which
trigger fires first or fires last using sp_settriggerorder
Triggers can't be invoked on demand. They get triggered only when an associated action
(INSERT, UPDATE, DELETE) happens on the table on which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be
used to extend the referential integrity checks, but wherever possible, use constraints for
this purpose, instead of triggers, as constraints are much faster.
Till SQL Server 7.0, triggers fire only after the data modification operation happens. So
in a way, they are called post triggers. But in SQL Server 2000 you could create pre
triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers.
Also check out books online for 'inserted table', 'deleted table' and
COLUMNS_UPDATED()
How to programmatically find out when the SQL Server service started?
Everytime SQL Server starts, it recreates the tempdb database. So, the creation date and
time of the tempdb database tells us the date and time at which SQL Server service
started. This information is stored in the crdate column of the sysdatabases table in master
database. Here's the query to find that out:
SELECT crdate AS 'SQL Server service started approximately at:'
FROM master.dbo.sysdatabases
WHERE name = 'tempdb'
SQL Server error log also has this information (This is more accurate) and the error log
can be queried using xp_readerrorlog
How to get rid of the time part from the date returned by GETDATE function?
We have to use the CONVERT function to strip the time off the date. Any of the
following commands will do this:
SELECT CONVERT(char,GETDATE(),101)
SELECT CONVERT(char,GETDATE(),102)
SELECT CONVERT(char,GETDATE(),103)
SELECT CONVERT(char,GETDATE(),1)
See SQL Server Books Online for more information on CONVERT function.
Confidential
Page 26 of 57
How to run an SQL script file that is located on the disk, using T-SQL?
There's no direct command to read a script file and execute it. But the isql.exe and
osql.exe come in handy when you have to execute a script file from within T-SQL. Just
call any of these exes using xp_cmdshell and pass the script file name as parameter to it.
See SQL Server Books Online for more information about the input parameters of these
exes. Here are some quick examples:
EXEC master..xp_cmdshell 'osql -Svaio -Usa -Pzaassds1 -ic:\MySQl.sql -n'
EXEC master..xp_cmdshell 'isql -Svaio -Usa -Pzaassds1 -ic:\MySQl.sql -n'
See xp_cmdshell in SQL Server Books Online if you are having permissions problems in
getting this technique to work.
Miscellaneous
Why are my insert, update statements failing with the following error?
Server: Msg 8152, Level 16, State 9, Line 1
String or binary data would be truncated.
The statement has been terminated.
This error occurs, when the length of the value entered by you into a char, varchar, nchar,
nvarchar column is longer than the maximum length of the column. For example,
inserting 'FAQ' into a char(2) column would result in this error.
Profiler is handy in troubleshooting this error. If data truncation is okay with you and you
don't want to see this error, then turn off ANSI WARNINGS by using the following SET
command: SET ANSI_WARNINGS OFF.
Steps to reproduce the problem:
CREATE TABLE MyTable
(
Pkey int PRIMARY KEY,
Col1 char(10)
)
GO
INSERT INTO MyTable (Pkey, Col1) VALUES (1, 'SQL Server Clustering FAQ')
GO
Make sure, you restrict the length of input, in your front-end applications. For example,
you could use the MAXLENGTH property of the text boxes in HTML forms. E.g:
<INPUT NAME = "Name" TYPE= TEXTBOX MAXLENGTH=20>
How to convert timestamp data to date data (datetime datatype)?
Confidential
Page 27 of 57
The name timestamp is a little misleading. Timestamp data has nothing to do with dates
and times and can not be converted to date data. A timestamp is a unique number within
the database and is equivalent to a binary(8)/varbinary(8) datatype. A table can have only
one timestamp column. Timestamp value of a row changes with every update of the row.
To avoid the confusion, SQL Server 2000 introduced a synonym to timestamp, called
rowversion.
How to run jobs from T-SQL?
Use the procedure msdb..sp_start_job to start jobs programmatically. See SQL Server
Books Online for more information.
I forgot/lost the sa password. What to do?
Forgot or lost your sa password? Don't worry, there is a way out :)
Login to the SQL Server computer as the Administrator of that computer. Open Query
Analyzer and connect to SQL Server using Windows NT authentication. Run
sp_password as show below to reset the sa password:
sp_password @new = 'will_never_forget_again', @loginame = 'sa'
Can you have a nested transaction?
Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and
@@TRANCOUNT
What is the system function to get the current user's user id?
USER_ID(). Also check out other system functions like USER_NAME(),
SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(),
HOST_NAME().
Confidential
Page 28 of 57
Confidential
Page 29 of 57
Create separate tables for each group of related data and identify each row with a
unique column or set of columns (the primary key).
Second normal form (2NF) further addresses the concept of removing duplicative data:
Remove subsets of data that apply to multiple rows of a table and place them in
separate tables.
Create relationships between these new tables and their predecessors through the
use of foreign keys.
Third normal form (3NF) goes one large step further:
Remove columns that are not dependent upon the primary key.
Finally, fourth normal form (4NF) has one requirement:
A relation is in 4NF if it has no multi-valued dependencies.
Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it
must first fulfill all the criteria of a 1NF database.
Confidential
Page 30 of 57
4.2.
Objects in a Microsoft SQL Server 2000 database are stored as a collection of 8-KB
pages. This topic describes the way the pages for tables and indexes are organized.
SQL Server 2000 supports indexes on views. The first index allowed on a view is a
clustered index. At the time a CREATE INDEX statement is executed on a view, the
result set for the view is materialized and stored in the database with the same structure as
a table that has a clustered index. The result set that is stored is the same as that which is
produced by this statement.
SELECT * FROM ViewName
The data rows for each table or indexed view are stored in a collection of 8-KB data
pages. Each data page has a 96-byte header containing system information such as the
identifier (ID) of the table that owns the page. The page header also includes pointers to
the next and previous pages that are used if the pages are linked in a list. A row offset
table is at the end of the page. Data rows fill the rest of the page.
4.2.2.
SQL Server 2000 tables use one of two methods to organize their data pages:
Confidential
Page 31 of 57
data rows. Clustered tables and indexed views keep their data rows in order based on the
clustered index key. The collection of data pages for a heap is not affected if nonclustered
indexes are defined for the table. The data pages remain in a heap unless a clustered index
is defined.
The pages holding text, ntext, and image data are managed as a single unit for each
table. All of the text, ntext, and image data for a table is stored in one collection of
pages.
All of the page collections for tables, indexes and indexed views are anchored by page
pointers in the sysindexes table. Every table and indexed view has one collection of data
pages, plus additional collections of pages to implement each index defined for the table
or view.
Each table, index and indexed view has a row in sysindexes uniquely identified by the
combination of the object identifier (id) column and the index identifier (indid) column.
The allocation of pages to tables, indexes, and indexed views is managed by a chain of
IAM pages. The column sysindexes.FirstIAM points to first IAM page in the chain of
IAM pages managing the space allocated to the table, index or indexed view.
Each table has a set of rows in sysindexes:
Each nonclustered index created for a table or view has a row in sysindexes.
The values for indid in the rows for each nonclustered index range from 2
through 250. The root column points to the top of the nonclustered index B-tree.
Each table that has at least one text, ntext, or image column also has a row in
sysindexes with indid = 255.
The column FirstIAM points to the chain of IAM pages that manage the text,
ntext, and image pages.
In SQL Server version 6.5 and earlier, sysindexes.first always points to the start of a
heap, the start of the leaf level of an index, or the start of a chain of text and image
Confidential
Page 32 of 57
pages. In SQL Server version 7.0 and later, sysindexes.first is largely unused. In SQL
Server version 6.5 and earlier, sysindexes.root in a row with indid = 0 points to the last
page in a heap. In SQL Server version 7.0 and later, sysindexes.root in a row with indid
= 0 is unused.
4.3.
Indexes
Indexes in databases are similar to indexes in books. In a book, an index allows you to
find information quickly without reading the entire book. In a database, an index allows
the database program to find data in a table without scanning the entire table. An index in
a book is a list of words with the page numbers that contain each word. An index in a
database is a list of values in a table with the storage locations of rows in the table that
contain each value. Indexes can be created on either a single column or a combination of
columns in a table and are implemented in the form of B-trees. An index contains an
entry with one or more columns (the search key) from each row in a table. A B-tree is
sorted on the search key, and can be searched efficiently on any leading subset of the
search key. For example, an index on columns A, B, C can be searched efficiently on A,
on A, B, and A, B, C.
Most books contain one general index of words, names, places, and so on. Databases
contain individual indexes for selected types or columns of data: this is similar to a book
that contains one index for names of people and another index for places. When you
create a database and tune it for performance, you should create indexes for the columns
used in queries to find data.
In the pubs sample database provided with Microsoft SQL Server 2000, the
employee table has an index on the emp_id column. The following illustration shows
how the index stores each emp_id value and points to the rows of data in the table with
each value.
When SQL Server executes a statement to find data in the employee table based on a
specified emp_id value, it recognizes the index for the emp_id column and uses the
index to find the data. If the index is not present, it performs a full table scan starting at
the beginning of the table and stepping through each row, searching for the specified
emp_id value.
SQL Server automatically creates indexes for certain types of constraints (for example,
PRIMARY KEY and UNIQUE constraints). You can further customize the table
definitions by creating indexes that are independent of constraints.
The performance benefits of indexes, however, do come with a cost. Tables with indexes
require more storage space in the database. Also, commands that insert, update, or delete
data can take longer and require more processing time to maintain the indexes. When you
design and create indexes, you should ensure that the performance benefits outweigh the
extra cost in storage space and processing resources.
Confidential
Page 33 of 57
4.3.1.
Clustered Indexes
Clustered indexes have one row in sysindexes with indid = 1. The pages in the data chain
and the rows in them are ordered on the value of the clustered index key. All inserts are
made at the point the key value in the inserted row fits in the ordering sequence.
Microsoft SQL Server 2000 indexes are organized as B-trees. Each page in an index
holds a page header followed by index rows. Each index row contains a key value and a
pointer to either a lower-level page or a data row. Each page in an index is called an index
node. The top node of the B-tree is called the root node. The bottom layer of nodes in the
index are called the leaf nodes. The pages in each level of the index are linked together in
a doubly-linked list. In a clustered index, the data pages make up the leaf nodes. Any
index levels between the root and the leaves are collectively known as intermediate
levels.
For a clustered index, sysindexes.root points to the top of the clustered index. SQL
Server navigates down the index to find the row corresponding to a clustered index key.
To find a range of keys, SQL Server navigates through the index to find the starting key
value in the range, and then scans through the data pages using the previous or next
pointers. To find the first page in the chain of data pages, SQL Server follows the leftmost
pointers from the root node of the index.
This illustration shows the structure of a clustered index.
4.3.2.
Nonclustered Indexes
Nonclustered indexes have the same B-tree structure as clustered indexes, with two
significant differences:
The data rows are not sorted and stored in order based on their nonclustered keys.
The leaf layer of a nonclustered index does not consist of the data pages.
Instead, the leaf nodes contain index rows. Each index row contains the
nonclustered key value and one or more row locators that point to the data row (or
rows if the index is not unique) having the key value.
If the table is a heap (does not have a clustered index), the row locator is a pointer
to the row. The pointer is built from the file identifier (ID), page number, and
number of the row on the page. The entire pointer is known as a Row ID.
Confidential
Page 34 of 57
If the table does have a clustered index, or the index is on an indexed view, the
row locator is the clustered index key for the row. If the clustered index is not a
unique index, SQL Server 2000 makes duplicate keys unique by adding an
internally generated value. This value is not visible to users; it is used to make the
key unique for use in nonclustered indexes. SQL Server retrieves the data row by
searching the clustered index using the clustered index key stored in the leaf row
of the nonclustered index.
Because nonclustered indexes store clustered index keys as their row locators, it is
important to keep clustered index keys as small as possible. Do not choose large columns
as the keys to clustered indexes if a table also has nonclustered indexes.
4.4.
Using Joins
Join conditions can be specified in either the FROM or WHERE clauses; specifying them
in the FROM clause is recommended. WHERE and HAVING clauses can also contain
search conditions to further filter the rows selected by the join conditions.
Joins can be categorized as:
Inner joins (the typical join operation, which uses some comparison operator like
= or <>). These include equi-joins and natural joins.
Inner joins use a comparison operator to match rows from two tables based on the
values in common columns from each table. For example, retrieving all rows
where the student identification number is the same in both the students and
courses tables.
Outer joins. Outer joins can be a left, a right, or full outer join.
Outer joins are specified with one of the following sets of keywords when they
are specified in the FROM clause:
Confidential
Page 35 of 57
Cross joins.
Cross joins return all rows from the left table, each row from the left table is
combined with all rows from the right table. Cross joins are also called Cartesian
products.
For example, here is an inner join retrieving the authors who live in the same city and
state as a publisher:
USE pubs
SELECT a.au_fname, a.au_lname, p.pub_name
FROM authors AS a INNER JOIN publishers AS p
ON a.city = p.city
AND a.state = p.state
ORDER BY a.au_lname ASC, a.au_fname ASC
The tables or views in the FROM clause can be specified in any order with an inner join
or full outer join; however, the order of tables or views specified when using either a left
or right outer join is important. For more information about table ordering with left or
right outer joins, see Using Outer Joins.
4.4.1.
A cross join that does not have a WHERE clause produces the Cartesian product of the
tables involved in the join. The size of a Cartesian product result set is the number of
rows in the first table multiplied by the number of rows in the second table. This is an
example of a Transact-SQL cross join:
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors CROSS JOIN publishers
ORDER BY au_lname DESC
The result set contains 184 rows (authors has 23 rows and publishers has 8; 23
multiplied by 8 equals 184).
However, if a WHERE clause is added, the cross join behaves as an inner join. For
example, these Transact-SQL queries produce the same result set:
Confidential
Page 36 of 57
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors CROSS JOIN publishers
WHERE authors.city = publishers.city
ORDER BY au_lname DESC
-- Or
USE pubs
SELECT au_fname, au_lname, pub_name
FROM authors INNER JOIN publishers
ON authors.city = publishers.city
ORDER BY au_lname DESC
4.4.2.
When there are null values in the columns of the tables being joined, the null values do
not match each other. The presence of null values in a column from one of the tables
being joined can be returned only by using an outer join (unless the WHERE clause
excludes null values).
Here are two tables that each have NULL in the column that will participate in the join:
table1
a
b
------- -----1
one
NULL three
4
join4
table2
c
d
-----------NULL
two
4
four
A join that compares the values in column a against column c does not get a match on the
columns that have values of NULL:
SELECT *
FROM table1 t1 JOIN table2 t2
ON t1.a = t2.c
ORDER BY t1.a
Only one row with 4 in column a and c is returned:
a
b
c
d
----------- ------ ----------- -----4
join4 4
four
(1 row(s) affected)
Confidential
Page 37 of 57
Null values returned from a base table are also difficult to distinguish from the null values
returned from an outer join. For example, this SELECT statement does a left outer join
on these two tables:
SELECT *
FROM table1 t1 LEFT OUTER JOIN table2 t2
ON t1.a = t2.c
ORDER BY t1.a
Here is the result set:
a
b
c
d
----------- ------ ----------- -----NULL
three NULL
NULL
1
one NULL
NULL
4
join4 4
four
(3 row(s) affected)
The results do not make it easy to distinguish a NULL in the data from a NULL that
represents a failure to join. When null values are present in data being joined, it is usually
preferable to omit them from the results by using a regular join.
4.4.3.
Inner joins return rows only when there is at least one row from both tables that matches
the join condition. Inner joins eliminate the rows that do not match with a row from the
other table. Outer joins, however, return all rows from at least one of the tables or views
mentioned in the FROM clause, as long as those rows meet any WHERE or HAVING
search conditions. All rows are retrieved from the left table referenced with a left outer
join, and all rows from the right table referenced in a right outer join. All rows from both
tables are returned in a full outer join
Microsoft SQL Server 2000 uses these SQL-92 keywords for outer joins specified in
a FROM clause:
SQL Server supports both the SQL-92 outer join syntax and a legacy syntax for
specifying outer joins based on using the *= and =* operators in the WHERE clause. The
SQL-92 syntax is recommended because it is not subject to the ambiguity that sometimes
results from the legacy Transact-SQL outer joins.
4.4.4.
Page 38 of 57
Consider a join of the authors table and the publishers table on their city columns. The
results show only the authors who live in cities in which a publisher is located (in this
case, Abraham Bennet and Cheryl Carson).
To include all authors in the results, regardless of whether a publisher is located in the
same city, use an SQL-92 left outer join. The following is the query and results of the
Transact-SQL left outer join:
USE pubs
SELECT a.au_fname, a.au_lname, p.pub_name
FROM authors a LEFT OUTER JOIN publishers p
ON a.city = p.city
ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC
Here is the result set:
au_fname
au_lname
pub_name
-------------------- ------------------------------ ----------------Reginald
Blotchet-Halls
NULL
Michel
DeFrance
NULL
Innes
del Castillo
NULL
Ann
Dull
NULL
Marjorie
Green
NULL
Morningstar
Greene
NULL
Burt
Gringlesby
NULL
Sheryl
Hunter
NULL
Livia
Karsen
NULL
Charlene
Locksley
NULL
Stearns
MacFeather
NULL
Heather
McBadden
NULL
Michael
O'Leary
NULL
Sylvia
Panteley
NULL
Albert
Ringer
NULL
Anne
Ringer
NULL
Meander
Smith
NULL
Dean
Straight
NULL
Dirk
Stringer
NULL
Johnson
White
NULL
Akiko
Yokomoto
NULL
Abraham
Bennet
Algodata Infosystems
Cheryl
Carson
Algodata Infosystems
(23 row(s) affected)
The LEFT OUTER JOIN includes all rows in the authors table in the results, whether or
not there is a match on the city column in the publishers table. Notice that in the results
Confidential
Page 39 of 57
there is no matching data for most of the authors listed; therefore, these rows contain null
values in the pub_name column.
4.4.5.
Consider a join of the authors table and the publishers table on their city columns. The
results show only the authors who live in cities where a publisher is located (in this case,
Abraham Bennet and Cheryl Carson). The SQL-92 right outer join operator, RIGHT
OUTER JOIN, indicates all rows in the second table are to be included in the results,
regardless of whether there is matching data in the first table.
To include all publishers in the results, regardless of whether a city has a publisher
located in the same city, use an SQL-92 right outer join. Here is the Transact-SQL query
and results of the right outer join:
USE pubs
SELECT a.au_fname, a.au_lname, p.pub_name
FROM authors AS a RIGHT OUTER JOIN publishers AS p
ON a.city = p.city
ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC
Here is the result set:
au_fname
au_lname
pub_name
-------------------- ------------------------ -------------------Abraham
Bennet
Algodata Infosystems
Cheryl
Carson
Algodata Infosystems
NULL
NULL
Binnet & Hardley
NULL
NULL
Five Lakes Publishing
NULL
NULL
GGG&G
NULL
NULL
Lucerne Publishing
NULL
NULL
New Moon Books
NULL
NULL
Ramona Publishers
NULL
NULL
Scootney Books
(9 row(s) affected)
An outer join can be further restricted by using a predicate (such as comparing the join to
a constant). This example contains the same right outer join, but eliminates all titles that
have sold fewer than 50 copies:
USE pubs
SELECT s.stor_id, s.qty, t.title
FROM sales s RIGHT OUTER JOIN titles t
ON s.title_id = t.title_id
AND s.qty > 50
ORDER BY s.stor_id ASC
Confidential
Page 40 of 57
Page 41 of 57
Using Self-Joins
A table can be joined to itself in a self-join. For example, you can use a self-join to find
out the authors in Oakland, California who live in the same ZIP Code area.
Confidential
Page 42 of 57
Because this query involves a join of the authors table with itself, the authors table
appears in two roles. To distinguish these roles, you must give the authors table two
different aliases (au1 and au2) in the FROM clause. These aliases are used to qualify the
column names in the rest of the query. This is an example of the self-join Transact-SQL
statement:
USE pubs
SELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lname
FROM authors au1 INNER JOIN authors au2
ON au1.zip = au2.zip
WHERE au1.city = 'Oakland'
ORDER BY au1.au_fname ASC, au1.au_lname ASC
Here is the result set:
au_fname
au_lname
au_fname
au_lname
-------------------- ------------------- -------------------- --------Dean
Straight
Dean
Straight
Dean
Straight
Dirk
Stringer
Dean
Straight
Livia
Karsen
Dirk
Stringer
Dean
Straight
Dirk
Stringer
Dirk
Stringer
Dirk
Stringer
Livia
Karsen
Livia
Karsen
Dean
Straight
Livia
Karsen
Dirk
Stringer
Livia
Karsen
Livia
Karsen
Marjorie
Green
Marjorie
Green
Stearns
MacFeather
Stearns
MacFeather
(11 row(s) affected)
To eliminate the rows in the results in which the authors match themselves and to
eliminate rows that are identical, except the order of the authors is reversed, make this
change to the Transact-SQL self-join query:
USE pubs
SELECT au1.au_fname, au1.au_lname, au2.au_fname, au2.au_lname
FROM authors au1 INNER JOIN authors au2
ON au1.zip = au2.zip
WHERE au1.city = 'Oakland'
AND au1.state = 'CA'
AND au1.au_id < au2.au_id
ORDER BY au1.au_lname ASC, au1.au_fname ASC
Here is the result set:
au_fname
au_lname
au_fname
au_lname
Confidential
Page 43 of 57
Constraints
Constraints allow you to define the way Microsoft SQL Server 2000 automatically
enforces the integrity of a database. Constraints define rules regarding the values allowed
in columns and are the standard mechanism for enforcing integrity. Using constraints is
preferred to using triggers, rules, and defaults. The query optimizer also uses constraint
definitions to build high-performance query execution plans.
4.5.1.
Classes of Constraints
NOT NULL specifies that the column does not accept NULL values.
CHECK constraints enforce domain integrity by limiting the values that can be
placed in a column.
A CHECK constraint specifies a Boolean (evaluates to TRUE or FALSE) search
condition that is applied to all values entered for the column; all values that do not
evaluate to TRUE are rejected. You can specify multiple CHECK constraints for
each column. This sample shows the creation of a named constraint, chk_id, that
further enforces the domain of the primary key by ensuring that only numbers
within a specified range are entered for the key.
Confidential
Page 44 of 57
primary keys do not allow null values. A UNIQUE constraint is preferred over a
unique index.
PRIMARY KEY constraints identify the column or set of columns whose values
uniquely identify a row in a table.
No two rows in a table can have the same primary key value. You cannot enter a
NULL for any column in a primary key. NULL is a special value in databases that
represents an unknown value, which is distinct from a blank or 0 value. Using a
small, integer column as a primary key is recommended. Each table should have a
primary key.
A table may have more than one combination of columns that could uniquely
identify the rows in a table; each combination is a candidate key. The database
administrator picks one of the candidate keys to be the primary key. For example,
in the part_sample table both part_nmbr and part_name could be candidate
keys, but only part_nmbr is chosen as a primary key.
Confidential
Page 45 of 57
CASCADE specifies that all the rows with foreign keys pointing to the
deleted row are also deleted.
The ON UPDATE clause defines the actions that are taken if you attempt to
update a candidate key value to which existing foreign keys point. It also supports
the NO ACTION and CASCADE options.
4.5.2.
Table constraints must be used when more than one column must be included in a
constraint.
For example, if a table has two or more columns in the primary key, you must use a table
constraint to include both columns in the primary key. Consider a table that records
events happening in a computer in a factory. Assume that events of several types can
happen at the same time, but that no two events happening at the same time can be of the
same type. This can be enforced in the table by including both the type and time columns
in a two-column primary key.
CREATE TABLE factory_process
(event_type
int,
event_time
datetime,
event_site
char(50),
event_desc
char(1024),
CONSTRAINT event_key PRIMARY KEY (event_type, event_time) )
Confidential
Page 46 of 57
4.6.
Login
A valid login name is required to connect to an SQL Server instance. A login could be:
A Windows NT/2000 login that has been granted access to SQL Server
These login names are maintained within the master database. So, it is essential to backup
the master database after adding new logins to SQL Server.
4.6.2.
User
A valid user account within a database is required to access that database. User accounts
are specific to a database. All permissions and ownership of objects in the database are
controlled by the user account. SQL Server logins are associated with these user
accounts. A login can have associated users in different databases, but only one user per
database.
During a new connection request, SQL Server verifies the login name supplied, to make
sure, that login is authorized to access SQL Server. This verification is called
Authentication. SQL Server supports two authentication modes:
Confidential
Page 47 of 57
Creates a new login that allows users to connect to SQL Server using
SQL Server authentication
sp_grantlogin
sp_droplogin
sp_revokelogin
sp_denylogin
sp_password
Confidential
Page 48 of 57
sp_helplogins
sp_defaultdb
sp_grantdbaccess
Now let's talk about controlling access to objects within the database and managing
permissions. Apart from managing permissions at the individual database user level, SQL
Server 7.0/2000 implements permissions using roles. A role is nothing but a group to
which individual logins/users can be added, so that the permissions can be applied to the
group, instead of applying the permissions to all the individual logins/users. There are
three types of roles in SQL Server 7.0/2000:
These are server-wide roles. Logins can be added to these roles to gain the associated
administrative permissions of the role. Fixed server roles cannot be altered and new
server roles cannot be created. Here are the fixed server roles and their associated
permissions in SQL Server 2000:
Fixed server
role
Description
Sysadmin
serveradmin
setupadmin
securityadmin
processadmin
Dbcreator
Diskadmin
Bulkadmin
Here is a list of stored procedures that are helpful in managing fixed server roles:
Confidential
Page 49 of 57
sp_helpsrvrole
Each database has a set of fixed database roles, to which database users can be added.
These fixed database roles are unique within the database. While the permissions of fixed
database roles cannot be altered, new database roles can be created. Here are the fixed
database roles and their associated permissions in SQL Server 2000:
Fixed database role Description
db_owner
db_accessadmin
db_securityadmin
db_ddladmin
Can select all data from any user table in the database
db_datawriter
db_denydatareader Cannot select any data from any user table in the database
db_denydatawriter Cannot modify any data in any user table in the database
Here is a list of stored procedures that are helpful in managing fixed database roles:
sp_addrole
sp_addrolemember
sp_helpdbfixedrole
sp_helprole
sp_helprolemember
Confidential
Page 50 of 57
sp_droprolemember
4.6.5.
Application roles
Application roles are another way of implementing permissions. These are quite different
from the server and database roles. After creating and assigning the required permissions
to an application role, the client application needs to activate this role at run-time to get
the permissions associated with that application role. Application roles simplify the job of
DBAs, as they don't have to worry about managing permissions at individual user level.
All they need to do is to create an application role and assign permissions to it. The
application that is connecting to the database activates the application role and inherits
the permissions associated with that role. Here are the characteristics of application roles:
Here are the stored procedures that are required to manage application roles:
sp_addapprole
sp_setapprole
Now that we discussed different kinds of roles, let's talk about granting/revoking
permissions to/from database users and database roles and application roles. The
following T-SQL commands are used to manage permissions at the user and role level.
GRANT: Grants the specific permission (Like SELECT, DELETE etc.) to the
specified user or role in the current database
Confidential
Page 51 of 57
DENY: Denies a specific permission to the specified user or role in the current
database
Microsoft SQL Server provides the stored procedure mechanism to simplify the database
development process by grouping Transact-SQL statements into manageable blocks.
Benefits
Precompiled execution. SQL Server compiles each stored procedure once and
then reutilizes the execution plan. This results in tremendous performance boosts when
stored procedures are called repeatedly.
Enhanced security controls. You can grant users permission to execute a stored
procedure independently of underlying table permissions.
Structure
Stored procedures are extremely similar to the constructs seen in other programming
languages. They accept data in the form of input parameters that are specified at
execution time. These input parameters (if implemented) are utilized in the execution of
a series of statements that produce some result. This result is returned to the calling
environment through the use of a recordset, output parameters and a return code. That
may sound like a mouthful, but you'll find that stored procedures are actually quite
simple. Let's take a look at a practical example.
Example
Assume we have the following table named Inventory:
ID
Product
Warehouse
142
214
825
Green Beans NY
Peas FL
200
Corn NY
140
Quantity
100
Confidential
Page 52 of 57
512
491
379
Lima Beans
Corn FL
Watermelon
NY
80
FL
180
85
This information is updated in real-time and warehouse managers are constantly checking
the levels of products stored at their warehouse and available for shipment. In the past,
each manager would run queries similar to the following:
SELECT Product, Quantity
FROM Inventory
WHERE Warehouse = 'FL'
This resulted in very inefficient performance at the SQL Server. Each time a warehouse
manager executed the query, the database server was forced to recompile the query and
execute it from scratch. It also required the warehouse manager to have knowledge of
SQL and appropriate permissions to access the table information.
We can simplify this process through the use of a stored procedure. Let's create a
procedure called sp_GetInventory that retrieves the inventory levels for a given
warehouse. Here's the SQL code:
CREATE PROCEDURE sp_GetInventory
@location varchar(10)
AS
SELECT Product, Quantity
FROM Inventory
WHERE Warehouse = @location
Our Florida warehouse manager can then access inventory levels by issuing the command
EXECUTE sp_GetInventory 'FL'
The New York warehouse manager can use the same stored procedure to access that
area's inventory.
EXECUTE sp_GetInventory 'NY'
Granted, this is a simple example, but the benefits of abstraction can be seen here. The
warehouse manager does not need to understand SQL or the inner workings of the
procedure. From a performance perspective, the stored procedure will work wonders.
The SQL Sever creates an execution plan once and then reutilizes it by plugging in the
appropriate parameters at execution time.
Now that you've learned the benefits of stored procedures, get out there and use them!
Try a few examples and measure the performance enhancements achieved -- you'll be
amazed!
Confidential
Page 53 of 57
Confidential
Page 54 of 57
Some general issues that you could talk about would be: No indexes, table
scans, missing or out of date statistics, blocking, excess recompilations of
stored procedures, procedures and triggers without SET NOCOUNT ON,
poorly written query with unnecessarily complicated joins, too much
normalization, excess usage of cursors and temporary tables.
Confidential
Page 55 of 57
The transaction log is not implemented as a table but as a separate file or set of
files in the database. The log cache is managed separately from the buffer cache
for data pages, resulting in simple, fast, and robust code within the database
engine.
The format of log records and pages is not constrained to follow the format of
data pages.
Confidential
Page 56 of 57
The transaction log can be implemented on several files. The files can be defined
to autogrow as required. This reduces the potential of running out of space in the
transaction log, while at the same time reducing administrative overhead.
The mechanism to truncate unused parts of the log is quick and has minimal effect
on transaction throughput.
http://www.sqlServercentral.com
http://www.sqldts.com
http://www.sql-Server-performance.com
http://www.lc.leidenuniv.nl/awcourse/oracle/
Confidential
Page 57 of 57