In this section you will learn about: .NET Framework SQL Server 2005 tools Grouping data by using the UNPIVOT operator Read the following topic in the Introduction to SQL Server 20
Trang 1Collaborate Ch
Trang 3In this section you will learn about:
NET Framework
SQL Server 2005 tools
Grouping data by using the UNPIVOT operator
Read the following topic in the Introduction to SQL Server 2005 section of Chapter 1 of the book Querying and Managing Data Using SQL Server 2005:
The NET Framework
Read the following section of Chapter 1 of the book Querying and Managing Data Using SQL Server 2005:
Identifying the SQL Server 2005 Tools
The UNPIVOT operator allows database users to normalize the data that has earlier been pivoted The UNPIVOT operator transforms the multiple column values of a record into multiple records with the same values in a single column For example, a table that stores applicants’ records has one row for each applicant The table stores the applicant’s name, qualification and grade After applying the UNPIVOT operator on the table, the table contains a different row for each qualification that the applicant has completed
Knowledge Byte
.NET Framework
Working with SQL Server 2005 Tools
Grouping Data by Using the UNPIVOT Operator
Trang 4¤NIIT 1.4 Querying, Managing, and Administering Databases Using SQL Server 2005
The following table shows the structure of the Applicant table before using the UNPIVOToperator
Column
Name
Applicant Name
Matriculation Higher Secondary Graduation
Applicant Table Before Using the UNPIVOT Operator
The following table shows the structure of the Applicant table after using the UNPIVOT operator
Column Name Applicant Name Qualification Grade
Trang 5The syntax for using the UNPIVOT operator is:
Trang 6¤NIIT 1.6 Querying, Managing, and Administering Databases Using SQL Server 2005
This section contains:
or no procedural logic Programming languages that are compatible with the NET Framework are best-suited for computationally-intensive functions and procedures that feature complex logic or for situations where you want to take advantage of the NET Framework class library
To rotate the data of a table you can use the PIVOT and UNPIVOT operators, instead of using complex JOIN statements
SQL Server 2005 provides three new data types for storing long columns: VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) These new data types are easier to use than the older large object data types, such as TEXT, NTEXT, and IMAGE When building a new application that needs to store a column that possibly might exceed 8000 bytes, you should consider using these new large value data types
The total characters displayed in the Query Editor Results window are limited to 256 characters If the result exceeds the limit of 256 characters, it gets truncated In this case, you can use the Options tab in Management Studio to set the maximum column size under the Results section
The result sets that you return from your database should be kept as small as possible This greatly improves the performance and makes the database much more scalable
From the Expert’s Desk
Best Practices
Trang 7The following tips and tricks will help you perform effective query by using SQL Server 2005:
When writing calculation expressions such as “expr1 * expr2”, ensure that the expression sweeping the largest area/volume is on the left side For instance, write
“Sales * ExchangeRate” instead of “ExchangeRate * Sales”, and “Sales * 1.15” instead of “1.15 * Sales” Here Sales value will be larger than the exchange rate
Consider replacing simple “Measure1 + Measure2” calculations with computed columns in the SQL data source
Avoid using Select * in your query design Instead, ensure that you use the proper column names in the query Using the proper column names decreases network traffic, puts less load on the database, and therfore, improves performance
What are the two new components introduced with SQL Server 2005?
The two new components introduced with SQL are:
z SQL Server Management Studio
z SQL Server Business Intelligence Development Studio
Can we use the PIVOT and UNPIVOT operators in SQL Server 2000?
No, SQL Server 2000 does not support the PIVOT and UNPIVOT operators To achieve the same functionality as that of the PIVOT and UNPIVOT operators, you can use JOINS in SQL Server 2000
Which framework is supported by SQL Server 2005?
SQL Server 2005 supports Framework V2.0
Which application architecture does SQL Server 2005 support?
SQL Server 2005 supports n-tier architecture
Which service of SQL Server 2005 allows you to gather and integrate data from various disparate data sources available in an organization?
Integration services of SQL Server 2005 allow you to gather and integrate data from various disparate data sources available in an organization
Tips and Tricks
FAQs
Trang 8¤NIIT 1.8 Querying, Managing, and Administering Databases Using SQL Server 2005
1 Which of the following is not a component of the NET Framework?
a Development tools and languages
b Base class library
c Service Broker
d Common Language Runtime
2 Which of the following component of the NET Framework is used to create the interface for the Windows forms?
a Base class library
b Service Broker
c Development tools and languages
d Common Language Runtime
3 Which component of the NET Framework provides an environment for the
application to run?
a Development tools and languages
b Base class library
c Security Management
d Common Language Runtime
4 Which of the following is not a feature provided by the common language runtime?
Trang 91 What is the maximum length of NVARCHAR data type?
4 Which of the following query retrieves the record of the students who are studying in
a class higher than class 10?
a SELECT * FROM Student WHERE NOT class<=10
b SELECT * FROM Student WHERE class=10
c SELECT * FROM Student WHERE class>=10
d SELECT * FROM Student WHERE NOT class>=10
5 Which of the following query retrieves the names of the cities that start with letter M and whose fourth letter is B?
a SELECT City FROM City_List WHERE City LIKE ‘M_ B_%’
b SELECT City FROM City_List WHERE City LIKE ‘M_ _ B[]’
c SELECT City FROM City_List WHERE City LIKE ‘M_ _ B%’
d SELECT City FROM City_List WHERE City LIKE ‘M% B%’
6 Which SQL Server 2005 service provides data mining solutions that are built on data integrated in the data warehouse?
Trang 10¤NIIT 1.10 Querying, Managing, and Administering Databases Using SQL Server 2005
7 Which type of statement in SQL Server allows you to control the data access in the database?
Trang 11Collaborate Ch
Trang 13In this section, you will learn about:
Functions to customize the result set in SQL Server 2005
Read the following section of Chapter 2 of the book Querying and Managing Data Using SQL Server 2005:
Using Functions to Customize the Result Set
Knowledge Byte
Using Functions to Customize the Result Set
Trang 14¤NIIT 2.4 Querying, Managing, and Administering Databases Using SQL Server 2005
This section contains:
create, with the SP prefix This is because all system stored procedures start with the
SP prefix
performing bulk inserts into your database
the same server, prefix the table with the database name Use the following syntax to refer a table from another database in the same server:
SELECT * from [<database name>].[dbo].[< table name>]
The following tips and tricks will help you use functions in SQL Server 2005:
Use SPACE() function for concatenating values in a query
Use VARCHAR(max) data type with LEFT(), RIGHT(), SUBSTRING() functions because these functions do not support ntext and text data types
Analyze all your query plans by using the SQL Query Analyzer to ensure that they are performing at optimum speed The best things any serious developer can do to improve performance in an application is to learn to use the SQL Query Analyzer Using this tool, you can find where the bottlenecks in your code are and, thereby, increase performance by altering indexes or even re-writing stored procedures
Avoid the use of nullable columns The use of the nullable column consumes an extra byte on each column used While querying data, there is much more overhead with nullable columns While designing a database, you should use an alternative method to allow for a representation of zero data in the column, such as giving “–“ as the default value for a column of char type
From the Expert’s Desk
Tips and Tricks
Best Practices
Trang 15 What is the difference between the DELETE and TRUNCATE commands?
The DELETE command removes the rows from a table based on the condition provided with the WHERE clause The TRUNCATE command removes all the rows from a table and does not give an option to selectively delete records
How can you figure out if a string is completely in uppercase?
You can find if a string is completely in uppercase by using the ASCII string
function
Can you define any length for a VARCHAR data type, such as VARCHAR(10000)?
When the length is specified in declaring a VARCHAR variable or column, the maximum length allowed is 8000 characters If the length is greater than 8000 characters, you have to use the MAX specifier as the length
If there are VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) data types, are there CHAR(MAX), NCHAR(MAX) and BINARY(MAX) data types also?
No, there is no CHAR(MAX), NCHAR(MAX), or BINARY(MAX) data types The main reason why the MAX specifier is not included for these data types is because these data types are fixed-length data types If the MAX specifier is included for these data types, it will be a big waste of disk space as each column will consume 2
GB of memory even if only a short string value is assigned to the column
How can you turn on IDENTITY on an existing column?
To change an existing column as an IDENTITY column, perform the following steps:
a Modify table in object browser
b Change column property to IDENTITY “yes”
c Save the change
FAQs
Trang 16¤NIIT 2.6 Querying, Managing, and Administering Databases Using SQL Server 2005
1 Identify the output of the following command:
Select left(‘SQL Server’,3)
Trang 171 Which join should be used to retrieve records with values satisfying the join
condition in the common column?
4 Which key constraint is used to maintain referential integrity?
a Foreign key constraint
b Primary key constraint
c Unique key constraint
Trang 18¤NIIT 2.8 Querying, Managing, and Administering Databases Using SQL Server 2005
7 What does >ALL mean in a SELECT statement that is using a subquery?
a It means greater than the maximum value in the list
b It means any of the values in the list
c It means greater than the minimum value in the list
d It means lesser than the minimum value in the list
8 Which system database contains all system objects?
a Resource database
b master database
c temdb database
d model database
9 What should be the size of a transaction log file?
a 25-40 percent of the database size
b 25-30 percent of the database size
c 25-35 percent of the database size
d 22-40 percent of the database size
10 Which keyword with the CHECK constraint ensures that the values entered are from
a list of constant expressions?
a BETWEEN
b IN
c ALL
d LIKE
Trang 19Collaborate Ch
Trang 21In this section, you will learn about:
Extensible Markup Language (XML)
Read the following topic in the Manipulating the XML Data section of Chapter 5 of the book Querying and Managing Data Using SQL Server 2005:
Storing XML Data in XML columns
Read the following topic in the section Manipulating the XML Data of Chapter 5 of the book Querying and Managing Data Using SQL Server 2005:
Using XQuery
Knowledge Byte
Creating an Extensible Markup Language (XML) Document
Storing XML Data in XML Columns
Using XQuery
Trang 22¤NIIT 3.4 Querying, Managing, and Administering Databases Using SQL Server 2005
This section contains:
some schema changes are faster than others The fastest schema changes occur when you:
z Add a column with the NULL property
z Add a column with the NULL and DEFAULT properties
z Change the NOT NULL property to NULL
z Add the DEFAULT constraint
z Drop the CHECK or DEFAULT constraint
a database use the following set of commands:
use <database name>
select distinct [Table] = object_name(object_id)
from sys.indexes
where index_id=0
and objectproperty(object_id,'IsUserTable')=1
order by [Table]
orders the data in a table based on a single or composite column The records stored
in a table without a clustered index are not in a specific physical order Whenever you need to query the column or columns used for the clustered index, SQL Server helps you sequentially read the data in a clustered index an extent (8 data pages, or 64K) at a time This makes it easy for the disk subsystem to read the data quickly from disk, especially if there is a lot of data to be retrieved
From the Expert’s Desk
Best Practices
Trang 23The following tips and tricks will help you effectively use DML commands and use indexes in SQL Server 2005:
To change the date and time on the Windows server where SQL Server is installed, use the following script in Query Editor:
USE master
EXEC xp_cmdshell 'echo 06/16/2005 | date'
EXEC xp_cmdshell 'echo 15:01:40 | time'
The first EXEC command changes the date in the SQL Server The second EXEC command changes the time in the SQL Server
To check whether the indexes created on your database are useful or not you can use sys.dm_db_index_usage_stats When an index is created on a table by using the CREATE INDEX statement, the index is not reflected in the index DMV’s When an index is used by a Select, Insert, Update, or Delete statement, the index is reflected in the index DMV and its use is captured by sys.dm_db_index_usage_stats
It returns counts of different types of index operations and the time each type of operation was last performed The greater the count of different types of index
operations for an index, the greater is the usefulness of the index
To insert values from another table along with some literals, you can use the following syntax:
INSERT INTO <table name> [(<col list>)] SELECT <col list>|<literal value> FROM <table name>
To determine if a particular object is a table or a view, you can use the OBJECTPROPERTY metadata function The following example checks if the object
is a view or not:
IF OBJECTPROPERTY( OBJECT_ID( '[dbo].[Customers]' ), 'IsView' ) = 1 PRINT 'Object is a view'
How many maximum columns are allowed with each INSERT statement?
The maximum columns allowed with each INSERT statement is 1024 columns
How many nonclustered indexes can be created on a table?
You can create 249 non-clustered indexes on a table
By default on which key the clustered index is created?
The clustered key is created on the Primary key by default
Tips and Tricks
FAQs
Trang 24¤NIIT 3.6 Querying, Managing, and Administering Databases Using SQL Server 2005
What is the maximum limit of creating partitions?
The maximum limit of creating partitions is 1000
Does SQL Server 2000 have a support for partition tables?
No, SQL Server 2000 does not support partition tables
How is the indexed view updated when any row is inserted, updated or deleted from
a table?
The SQL Server maintains the indexed views same as normal indexes When the data
is updated in a table the indexed view is automatically updated
Why it is recommended to create the first index of a table as CLUSTERED and UNIQUE?
The first index of the table must be UNIQUE to allow easy lookup of records in the view by the key value It must be CLUSTERED because only a clustered index can enforce uniqueness and store the rows at the same time
Trang 251 Which of the following is not true about Untyped data?
a It is a well-formed data
b It is not associated with any schema
c It is not validated by the SQL Server
d It is not stored as well-formed structure by the SQL Server
2 Which of the following is not a statement used with the XQuery language?
Trang 26¤NIIT 3.8 Querying, Managing, and Administering Databases Using SQL Server 2005
1 Which of the following is a not an example of an INSERT statement on Student table with ID and Name columns?
a INSERT Student VALUES (1, ‘Sam’)
b INSERT Student(ID,Name) VALUES(1,’Sam’)
c INSERT Student(Name)VALUES(‘Sam’)
d INSERT Student VALUES(‘Sam’)
2 Consider a table named Emp with columns named empid, empname and dept Which
of the following command will create a new table named ProdEmp from Emp table? The new table should contain records of employees from the Production department
a SELECT * INTO ProdEmp from Emp where dept=’Production’
b SELECT from Emp * INTO ProdEmp where dept=’Production’
c SELECT * INTO Emp from ProdEmp where dept=’Production’
d SELECT * INTO ProdEmp from Emp
3 Which of the following command is not a DML command?
a INSERT
b UPDATE
c ALTER TABLE
d DELETE
4 Which of the following is a correct TRUNCATE statement?
a TRUNCATE TABLE Emp
b TRUNCATE EMP
c TRUNCATE Emp WHERE Rt_Dt<’12/01/2000’
d TRUNCATE TABLE Emp WHERE Rt_Dt<’12/01/2000’
5 What does flag value 3 indicate in an openxml function?
a The flag value indicates retrieving the element values
b The flag value indicates retrieving both the element and attribute values
c The flag value indicates retrieving the default value
d The flag value indicates retrieving the attribute value
Home Assignment
Trang 276 Consider the following table for the column names, data types and constraints for the columns of table Events
Column Name Data Type Constraint
Date_Evnt datetime
Which command will you use to insert a record without the date of event?
a INSERT Events VALUES (‘104’, 'annual day', ‘angel gardens’,
‘12\15\2006’)
b INSERT Events(EventID, EventName, Location) VALUES (‘104’,
'annual day', ‘angel gardens’)
c INSERT Events VALUES (‘104’, 'annual day', ‘angel gardens’)
d INSERT (EventID, EventName, Location) Events VALUES (‘104’, 'annual day', ‘angel gardens’, ‘12\15\2006’)
7 Which statement will change the value in Department field to Accounts where the value of Department filed is Accts in EmpDetail table?
a UPDATE EmpDetails SET Department=’Accounts’ WHERE Department
=’Accts’
b UPDATE EmpDetails SET Department=’Accounts’
c UPDATE EmpDetails SET Department=’Accounts’ FOR Department
d TRUNCATE TABLE Tbl1 WHERE Fld1=’val1’
9 Which command will create a pointer to the internal representation of the XML document?
a EXEC sp_xml_preparedocument @Doc, @XMLDoc
b EXEC sp_xml_preparedocument @Doc OUTPUT, @XMLDoc
c EXEC sp_prepareddocument @Doc OUTPUT, @XMLDoc
d sp_xml_preparedocument @Doc OUTPUT
Trang 28¤NIIT 3.10 Querying, Managing, and Administering Databases Using SQL Server 2005
10 Which mode of the FOR XML clause is used to return query results as nested XML elements?
a RAW
b PATH
c AUTO
d EXPLICIT
Trang 29Collaborate Ch
Trang 31In this section, you will learn about:
Creating partitioned indexes
System-defined stored procedures
Read the following topic in the section Creating and Managing Indexes of Chapter 6 of the book Querying and Managing Data Using SQL Server 2005:
Creating Partitioned Indexes
Read the following topic in the Appendix of the book Querying and Managing Data Using SQL Server 2005:
System-Defined Procedures
Knowledge Byte
Creating Partitioned Indexes
System-Defined Procedures
Trang 324.4 Querying, Managing, and Administering Databases Using SQL Server 2005 ¤NIIT
This section contains:
This is useful in a situation where two users are accessing the same stored procedure
at the same time and the two query plans are stored in the cache It is better to have smaller stored procedure calls than one very large stored procedure because it makes maintaining the code easier
value indicating their status This will help evaluate their success or failure status
creating a view if the records are combined from multiple tables having different number of columns, you should use the UNION ALL operator Ensure that the output of both the SELECT statements involved in the UNION ALL operator has the same number of columns
table, such as inserting columns in a table, keep refreshing the dependent views For example, suppose you are adding a new column to a table that is being referenced by
a view In such a situation, the new column will not automatically be reflected to the view, especially if the view is performing a SELECT * from the table For the new column to be reflected on the view, you have to refresh the definition of the view by using the sp_refreshview system stored procedure
From the Expert’s Desk
Best Practices
Trang 33The following tips and tricks will help you use views, batches, stored procedures, and functions in SQL Server 2005:
Use SET_NOCOUNT_ON at the beginning of SQL batches, stored procedures, and triggers This will increase the performance by reducing network traffic Setting SET_NOCOUNT_ON suppresses the messages regarding how many rows are affected after executing the INSERT, UPDATE, SELECT and DELETE statements
Use the following procedure to find keywords in stored procedures:
CREATE PROCEDURE <proc name> @<var name> VARCHAR(100)
Can you write SQL Server 2005 stored procedures without the knowledge of any SQL statements?
T-The belief that the SQL Server 2005 stored procedures can be written without the knowledge of T-SQL statements is partially true While it is technically possible to create a stored procedure without using T-SQL, it is not possible to access any data without using T-SQL statements
Can a view contain a CASE statement?
Yes, you can use a CASE statement in a view, but you have to create the view by using Query Analyzer and not SQL Server Enterprise Manager There is a limitation
in creating views in Enterprise Manager when the view contains a CASE statement
Tips and Tricks
FAQs
Trang 344.6 Querying, Managing, and Administering Databases Using SQL Server 2005 ¤NIIT
Can you use the FREETEXT predicate in a programming language with a SELECT statement?
Yes, the FREETEXT predicate can be used in a programming language with a SELECT statement in the same way as it is used in SQL Server
Is it must to create a unique index on a table before creating a full-text index on it?
Yes, it is must to create a unique index on a table before creating a full-text index on
it
Can you create more that one full-text index on a table?
Yes, you can create more than one full-text index on table on different columns When you use the different full-text predicates with the SELECT statement, the suitable full-text index is automatically selected
Trang 351 Which system-defined stored procedure is used to rename a view?
a It is used to display information about SQL Server configuration
b It is used to set the configuration of SQL Server 2005
c It is used to enable the CLR integration feature in the database
d It is used to extract the CLR integration information of the database
3 Which edition of SQL Server 2005 allows partitioning?
5 Which task determines the boundary values for creating partitions?
a Creating a partition function
b Creating a partition scheme
c Creating a clustered index
d Creating nonclustered index
Challenge
Trang 364.8 Querying, Managing, and Administering Databases Using SQL Server 2005 ¤NIIT
1 Which of the following is true about renaming a view?
a A view is renamed by using the sp_renameview procedure
b A view can only be renamed by the owner of the database
c A view can be renamed from another database
d A view name must follow the rules for identifiers
2 Michael has created a full-text index on the Author column of the Titles table by using the following command
CREATE FULLTEXT INDEX ON Titles (Author) KEY INDEX Ix.A
Which of the following is an alternative to the given command to create a full-text index?
a Right-click the table in the Object Explorer window Select Full-Text
IndexoDefine Full-Text Index
b Right-click the database in the Object Explorer window Select Full-Text IndexoDefine Full-Text Index
c Select the database in the Object Explorer window Select Full-Text
IndexoDefine Full-Text Index
d Select the table in the Object Explorer window Select Full-Text IndexoDefine Full-Text Index
3 Which population method should be used first on a table after creating a full-text index?
a Change tracking-based population method
b Incremental population method
c Full population method
d Incremental timestamp-based population method
4 Harry has populated a table that is full-text indexed After a month, Harry wants to update the new records from the base table to the full-text indexed table Which population method should Harry use?
a Change tracking-based population method
b Incremental population method
c Full population method
d Incremental timestamp-based population method
Home Assignment
Trang 375 Sam wants to add a column named Incentive in the Employee table Sam also wants
to update the Incentive column of the existing records depending on the grade of the employees H wants to create a batch to perform the task but is facing a problem while creating a batch Identify the problem
a Sam cannot create a batch for the ALTER TABLE statement
b Sam cannot create a batch that alters the table by adding a column and then updates the same column in the table
c Sam cannot create a batch that uses the ALTER TABLE and UPDATE
statements together
d Sam cannot create a batch to add new columns in the table
6 You are using the TRY…CATCH construct to execute a set of statements Which system function returns the name of the stored procedure or trigger in which the error has occurred?
b EXEC PROCEDURE myproc
c EXEC PROC myproc
d EXEC PROCEDURE
9 Consider the following code snippet:
CREATE PROCEDURE myproc @pr1 int, @pr2 char(50) OUTPUT, @pr3 int OUTPUT
Trang 384.10 Querying, Managing, and Administering Databases Using SQL Server 2005 ¤NIIT
Which of the following is a correct explanation of the preceding code snippet?
a The code creates a procedure named myproc with three input parameters
b The code creates a procedure named myproc with one input and two output parameters
c The code creates a procedure named myproc with three variables to store data
d The code creates a procedure named myproc with invalid syntax
10 Which of the following is not a component of UDF declaration?
a Input parameter name and data type
b Options applicable to the input parameter
c Return parameter data type and optional name
d Output parameter name and data type
Trang 39Collaborate Ch