Monday, August 8, 2011

SQL Server Questions Part III

Guys,

Here are some more Questions with Answers.

Q. What is the difference between Delete and Truncate command and is it possible to rollback after Truncate command?

ANS. Delete command removes the rows from a table based on Where condition. Truncate will actually remove all the rows from a table.

Below are some points about TRUNCATE:

  • TRUNCATE is faster and uses fewer system and transaction log resources than DELETE. 
  • TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log.
  • TRUNCATE removes all the rows from a table, but the table structure, its columns, constraints, indexes and so on remains. The counter used by an identity for new rows is reset to the seed for the column.
  • You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
  • TRUNCATE cannot be rolled back unless it is used in TRANSACTION. OR TRUNCATE can be rolled back when used with BEGIN … END TRANSACTION using T-SQL.
  • TRUNCATE is a DDL Command.
  • TRUNCATE resets the identity of the table.

Below are some points about DELETE:

  • DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
  • DELETE does not reset Identity property of the table.
  • DELETE can be used with or without a WHERE clause.
  • DELETE activates Triggers if defined on table.
  • DELETE can be rolled back.
  • DELETE is DML Command.
  • DELETE does not reset the identity of the table.

Q. Why we should give preference to stored procedure?

ANS. A stored procedure is a group of SQL statements that have been created and stored in a database. A procedured can accept input parameters. When the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.

Procedure Cache is the place where Execution Plan of Stored Procedure is stored. An execution plan states the efficient way in which the query(s) is executed. So whenever a normal query is executed its Execution Plan is created but when a Stored Procedure is executed, Execution plan is created and stored in Procedure Cache. Whenever the same procedure is executed and its execution plan exists in Procedure cache then it uses that execution plan rather than creating a new plan.

Q. What is an extent?

ANS. Extent is a basic unit of storage to provide space for tables. Every extent has a number of data pages. As new records are inserted new data, pages are allocated. There are eight data pages in an extent. So as soon as the eight pages are consumed, it allocates a new extent with data pages.

While extent is basic unit storage from a database point of view, page is a unit of allocation within extent.

Q. What is the advantage of SET NOCOUNT ON?

ANS. SET NOCOUNT ON gives a performance boost to action queries by suppressing the "(n row(s) affected) message that results from running a query.

Qualifying an object with it's owner boosts performance because SQL does not have to work out where if there is a user specific version of the same object. It also gives benefits in the caching of execution plans.

The performance boost is due to the few bytes of information that make up the "(1 row(s) affected)" message not being transmitted to the client application.

With this in mind I should consider the following points:

Communication between the database and the client application on a stand-alone machine will be as fast as it is possible to get. If your front end application had it's own clock and you recorded the time from submitting the query to the time when the client finally received the full results I would expect that transmitting results across a network to be slower.

In this experiment we are carrying out a single simple insert statement. If your procedure carries out multiple operations the performance boost will be more pronounced.

For queries that retrieve data the performance boost will be less simply because the size of the "(1 row(s) affected)" message is small compared to the volume of data being returned.

In .NET applications an ExecuteNonQuery command returns the number of records affected by the operation. Set NOCOUNT ON means that the value that this call returns is always zero.

Q. Suppose I have a table that has ID as primary key with IDENTITY. Whenever a new row is inserted in table, Identity will auto incremement the value by 1.

I don't want to insert an auto incremented value but I want to give it my own value. How can I do this?

Ans. We need to use SET IDENTITY_INSERT [TABLE NAME]. This allows explicit values to be inserted into the identity column of a table.

At any time, only one table in a session can have the IDENTITY_INSERT property set to ON. If a table already has this property set to ON, and a SET IDENTITY_INSERT ON statement is issued for another table, SQL Server returns an error message that states SET IDENTITY_INSERT is already ON and reports the table it is set ON for.

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

The setting of SET IDENTITY_INSERT is set at execute or run time and not at parse time.

Example:


SET IDENTITY_INSERT products ON
GO


INSERT INTO products (id, product) VALUES(3, 'garden shovel').
GO


SET IDENTITY_INSERT products OFF
GO

Q. What are IMPLICIT TRANSACTIONS?

ANS. Implicit Transactions are those that requires a COMMIT or ROLLBACK for every transaction.

When ON, SET IMPLICIT_TRANSACTIONS sets the connection into implicit transaction mode. When OFF, it returns the connection to autocommit transaction mode.

For example if we turn it on & update a table, the changes will not be committed until COMMIT command is executed.


Happy Learning

Sudhir

Monday, August 1, 2011

SSIS Questions - Part 1

Guys,
Let's start a series of Q&A's on SSIS also. As these days its essential to learn SSIS or any other BI tool.
I felt SSIS is one of the best tools to start with. Let's see some of the basic questions asked on SSIS.


Q. What is the control flow in SSIS? 
ANS:
As we have MAIN in .Net, same way we have Control Flow in SSIS. 
Containers, Data flow tasks, Administration tasks, Precedence constraints, and Variables are elements of the control flow. 
The control flow is the highest-level of control process. It allows to orchestrate and manage the run-time process activities of data flow and other processes within a package. We can design a control flow by using an Execute Package task to manage the sequence of processing for a set of existing packages in a Master Package concept. This capability allows to combine individual packages into a highly manageable workflow process. Use precedence constraints to set the process rules and to specify sequence within the control flow. An SSIS package consists of a control flow and one or more objects. Data flow and event handler process control components are optional.

Following are some key points of Control Flow:

  • Process is the key: precedence constraints control the project flow based on task completion, success or failure.
  • Task 1 needs to complete before task 2 can begin.
  • Smallest unit of the control flow is a task.
  • Control flow does not move data from task to task.
  • Tasks are run in series if connected with precedence or in parallel.
  • Package control flow is made up of containers and tasks connected with precedence constraints to control package 


Q. what is a data flow in SSIS?

ANS.

The Data Flow task encapsulates the data flow engine that moves data between sources and destinations, and lets the user transform, clean, and modify data as it is moved. Addition of a Data Flow task to a package, control flow makes it possible for the package to extract, transform, and load data.

A data flow consists of at least one data flow component, but it is typically a set of connected data flow components: sources that extract data; transformations that modify, route, or summarize data; and destinations that load data. Components are connected in the data flow by paths. Each path specifies the two components that are the start and the end of the path.

At run time, the Data Flow task builds an execution plan from the data flow, and the data flow engine executes the plan. You can create a Data Flow task that has no data flow, but the task executes only if it includes at least one data flow.

A package can include multiple Data Flow tasks, and complex packages frequently do. For example, if a package requires that data flows be run in a specified sequence, or that other tasks be performed between the data flows, you must use a separate Data Flow task for each data flow.

The Data Flow task also manages error flows. At run time, row-level errors may occur when data flow components convert data, perform a lookup, or evaluate expressions. For example, a data column with a string value cannot be converted to an integer, or an expression tries to divide by zero. Both operations cause errors, and the rows that contain the errors can be processed separately using an error flow.

There are many types of transformations as the data moves from the data source to the description. Here are some of the transformations:

Copy Column - This transformation copies the data in a column and creates a new column with it.
Script Component - This uses a VB script to transform the data somehow. You can use programmatic means to access the data, and set this script up as a data source, destination, or a transformation. When you open up the script component, there is a button stated as Design Script, which invokes a Visual Studio Editor where you can code the script with intellisense support.
Sort - This transformation sorts the data based on one or more columns setup to sort in a specified order.
Pivot and Unpivot - New to SQL Server 2005 is the way to pivot/unpivot data rather easily and they are supported as transformations. Pivoting data means you can make the columns of the result set based on a distinct result from the data.
Merge/Union All – Merging allows you to veer two inputs into one output. You can specify the input/output parameters that the transformation will map to. The Merge transformation is a little more restrictive than the Union All transformation.
Conditional Split – Conditional Split works the opposite way; based on values within the data, you can setup statements to split the data if a condition matches. For instance, you can split one result based on the expression “ListPrice > 100” and any data that matches that result is returned via a specific data flow path.
OLE DB Command – This transformation executes a SQL statement for every row in the input source.
Lookup – This transformation looks up the value of a field in a lookup data source/table.
Derived Column - A way to add an additional column in the dataset.
Aggregate - This allow to group data.
Fuzzy Logic - This allows to perform text manpulation like upper case, lower case operations on string data.
etc

Tuesday, July 5, 2011

SQL Server Questions Part II

Guys,

Today we will see some more generic questions on SQL Server.

Here are more questions:


Q. How can you ensure that a table named TableB with a field named Fld1 will only have those values in the Fld1 field that are also in the table named TableA with a field named Fld1?

Ans: Use referential integrity / Foreign Key Constraint

Q. How can you reset Identity key value of a table?

Ans: Truncate Table will reset the Identity value of table.

Q. What can be used to ensure that a field in a table only accepts a certain range of values?

Ans: We can use various constraints that can be used to achieve this.

There are various constraints available in SQL Server.

Primary Key Constraint => to uniquely identify a row without using NULL

Foreign Key Constraint => to maintain referential integrity between 1 or more tables

Unique Key Constraint => to uniquely identify a row

CHECK Constraint => the value entered is validated and if it fails condition then don't allow entry of data

Default Constraint => If we don't supply any value for field then set value of field with specified value

Null Constraint => Whether field can accept NULL value or not.

Q. Our company recently introduced a policy where all names of objects must follow naming convention. For ex. Table must start with tbl_, procedure should start with prc_ etc. How can I ensure all new objects must adher to these policies and if not followed object should not be created?

Ans: 1 way to use DDL triggers. From 2008 onwards we can also refer to Policy Based Management to ensure this.

Q. Is it possible to drop multiple objects using single DROP statement?

Ans:
Drop Table a,b,c
Drop proc a,b,c

Q. If you have a stored procedure, you want to just check the syntax of the same rather than executing it, what will u do?

Ans: Press CONTROL + F5 to check for its syntax. Or click on button next to EXECUTE button.

Q. Which event (CHECK constraint, Foreign Key, Rule, Trigger, Primary Key check) will be performed last for an integrity check?

Ans: Trigger because everything is executed before data is inserted in the table & as soon as data is entered in Table, trigger is fired.

Q. When a new parameter is added to an SP, what steps to take to ensure existing code in an application does not break?

ANS: Give a default value to the newly added parameter. This will ensure that all existing code will not fail.

Q. When we drop a variable length column using ALTER TABLE DROP COLUMN statement, the space used by the column is not automatically claimed. What will u do to claim the space?

Ans: DBCC CLEANTABLE (database_name, table_name)

Q. I have a table Employee with following definition:


Employee (
EmpID int Not Null Identity (1,1),
EmpName varchar(100) default 'test',
Age int default 2)

What query you will write to insert default values in EMPLOYEE table?

Ans: Insert into Employee Default Values

Q.How to retrieve a single table from database backup?

Ans: It is not possible to directly restore 1 table from backup. Only option is to restore the database somewhere else & then load data of required table and transfer to destination.

Q. How do you flip rows to columns and vice-versa?

Ans: We can use PIVOT, UnPivot to flip rows to columns & vice-versa.

Q. What is WITH ENCRYPTION clause and where it is used?

Ans: This will encrypt the definition of object and it will not be visible whenever we use sp_helptext. This can be done with View, Stored Procedure, Function etc

Q. What will happen if I write following statement:
Select getdate()
go 10

Ans: Select Getdate() is executed 10 times because GO 10 acts as a loop.

Q. What is the purpose of the USE command?

Ans: The USE command helps select any available database, so that every query is executed on selected database else default database is used.

Do let me know if you have any comments or more questions.
 
Thanks
 
Sudhir

Friday, July 1, 2011

Visual Studio 2010 and .NET Framework 4 Training Kit

Guys,


Visual Studio 2010 and .NET Framework 4 Training Kit includes presentations, hands-on labs, and demos. This content is designed to help you learn how to utilize the Visual Studio 2010 features and a variety of framework technologies including:
  • C# 4
  • Visual Basic 10
  • F#
  • Parallel Extensions
  • Windows Communication Foundation
  • Windows Workflow
  • Windows Presentation Foundation
  • Silverlight 4
  • ASP.NET 4
  • Windows 7
  • Entity Framework
  • ADO.NET Data Services
  • Managed Extensibility Framework
  • Application Lifecycle Management
  • Windows Azure
This version of the Training Kit works with Visual Studio 2010 and .NET Framework 4.


Download and launch the self-extracting package. The Training Kit will uncompress to the selected folder and launch a HTML browser for the content.


Click here to download the kit.


Happy Learning


Sudhir