Sunday, January 3, 2010

Dotnet Interview Questions

Interview Questions on Dot Net Framework
1. What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.
2. What is CTS?
Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution.
3. What is CLS?
The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features. These rules and the specification are documented in the ECMA proposed standard document, "Partition I Architecture"
4. What is CLI?
The CLI is a set of specifications for a runtime environment, including a common type system, base class library, and a machine-independent intermediate code known as the Common Intermediate Language (CIL). (Source: Wikipedia.)
5. Explain Namespace.
Namespaces are logical groupings of names used within a program. There may be multiple namespaces in a single application code, grouped based on the identifiers� use. The name of any given identifier must appear only once in its namespace.
6. Explain Assembly and Manifest.
An assembly is a collection of one or more files and one of them (DLL or EXE) contains a special metadata called Assembly Manifest. The manifest is stored as binary data and contains details like versioning requirements for the assembly, the author, security permissions, and list of files forming the assembly. An assembly is created whenever a DLL is built. The manifest can be viewed programmatically by making use of classes from the System.Reflection namespace. The tool Intermediate Language Disassembler (ILDASM) can be used for this purpose. It can be launched from the command prompt or via Start> Run.
7. What is Shadow Copy?
In order to replace a COM component on a live web server, it was necessary to stop the entire website, copy the new files and then restart the website. This is not feasible for the web servers that need to be always running. .NET components are different. They can be overwritten at any time using a mechanism called Shadow Copy. It prevents the Portable Executable (PE) files like DLLs and EXEs from being locked. Whenever new versions of the PEs are released, they are automatically detected by the CLR and the changed components will be automatically loaded. They will be used to process all new requests not currently executing, while the older version still runs the currently executing requests. By bleeding out the older version, the update is completed.
8. What is DLL Hell?
DLL hell is the problem that occurs when an installation of a newer application might break or hinder other applications as newer DLLs are copied into the system and the older applications do not support or are not compatible with them. .NET overcomes this problem by supporting multiple versions of an assembly at any given time. This is also called side-by-side component versioning.

9. Explain Web Services.
Web services are programmable business logic components that provide access to functionality through the Internet. Standard protocols like HTTP can be used to access them. Web services are based on the Simple Object Access Protocol (SOAP), which is an application of XML. Web services are given the .asmx extension.
10. Explain Windows Forms.
Windows Forms is employed for developing Windows GUI applications. It is a class library that gives developers access to Windows Common Controls with rich functionality. It is a common GUI library for all the languages supported by the .NET Framework.

11. Define Boxing and UnBoxing
C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.
12. Define Value Types and Reference Types
Value Types Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType. Reference TypesReference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.
13. What are Service Oriented Architectures (SOA)?
SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications. Web services are one of the technologies that help make SOAs possible. As a concept, SOA has been around since the 1980s, but many early IT technologies failed to achieve the goal of linking different types of applications and systems. By making early investments with .NET, Microsoft has helped provide the building blocks that today are putting many enterprise customers on the path to successfully implementing SOAs. With SOAs, companies can benefit from the unimpeded flow of information that is the hallmark of connected systems.
14. What are Web Services Enhancements for Microsoft .NET (WSE)?
WSE is an add-on to Microsoft Visual Studio .NET and the Microsoft .NET Framework that helps developers build greater security features into Web services using the latest Web services protocol specifications and standards. With WSE 2.0 developers can create security-enhanced connected systems that help improve business processes within�and beyond�corporate trust boundaries and create new revenue-generating opportunities.
15. What is a Smart Client?
Smart clients are client applications that consume Web services and reside on user hardware such as desktop PCs, laptops, Pocket PCs, and Smartphones. They are easily deployed and managed and provide an adaptive, responsive, and rich interactive experience by taking advantage of the computing resources on the device and intelligently connecting to distributed data sources.
16. What is .NET Passport?
.NET Passport is a Web-based service that is designed to make signing in to Web sites fast and easy. Passport enables participating sites to authenticate a user with a single set of sign-in credentials, alleviating the need for users to remember numerous passwords and user names.
17. Does C# support multiple inheritance? No, use interfaces instead
18. What�s the implicit name of the parameter that gets passed into the class� set method?
Value, and its datatype depends on whatever variable we�re changing
19. What�s the top .NET class that everything is derived from?
System.Object.
20. How�s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
21. What is strong name?
A name that consists of an assembly's identity its simple text name, version number, and culture information (if provided ) strengthened by a public key and a digital signature generated over the assembly.
22. What is Application Domain?
The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages.

23. What is serialization in .NET? What are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another. XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.
24. What�s an interface class?
It�s an abstract class with public abstract methods all of which must be implemented in the inherited classes
25. What is the transport protocol you use to call a Web service
SOAP is the preferred protocol

26. What are Satellite Assemblies?
Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed.
27. What is Global Assembly Cache (GAC) and what is the purpose of it?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.
28. What is Reflection in .NET?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.

29. What is the managed and unmanaged code in .net?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services
30. What are the access-specifiers available in c#? Private, Protected, Public, Internal, Protected Internal.
31. Difference between OLEDB Provider and SqlClient ?
SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.
32. Differences between dataset.clone and dataset.copy?
Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints.Does not copy any data . Copy - Copies both the structure and data for this DataSet.
33. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice? WebService will support only DataSet.
34. What is Remoting?
The process of communication between different operating system processes, regardless of whether they are on the same computer. The .NET remoting system is an architecture designed to simplify communication between objects living in different application domains, whether on the same computer or not, and between different contexts, whether in the same application domain or not.

35. What�s the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
36. What�s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
37. What�s the implicit name of the parameter that gets passed into the class� set method?
Value, and its datatype depends on whatever variable we�re changing.
38. How do you inherit from a class in C#?
Place a colon and then the name of the base class. Notice that it�s double colon in C++.
39. Does C# support multiple inheritance?
No, use interfaces instead.
40. When you inherit a protected class-level variable, who is it available to?
Classes in the same namespace.
41. Are private class-level variables inherited?
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
42. Describe the accessibility modifier protected internal.
It�s available to derived classes and classes within the same Assembly (and naturally from the base class it�s declared in).
43. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?
Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there�s no implementation in it.
44. How�s method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
45. What does the keyword virtual mean in the method definition?
The method can be over-ridden.
46. Can you declare the override method static while the original method is non-static?
No, you can�t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

47. Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

48. Can you prevent your class from being inherited and becoming a base class for some other classes?
Yes, that�s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It�s the same concept as final class in Java.
49. Can you allow class to be inherited, but prevent the method from being over-ridden?
Yes, just leave the class public and make the method sealed.
50. What�s an abstract class?
A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it�s a blueprint for a class without any implementation.
Explain the access specifiers public, private, protected, friend, internal, default
The main purpose of using access specifiers is to provide security to the applications. The availability (scope) of the member objects of a class may be controlled using access specifies.
Public
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods
Private
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
Friend/internal
Friend & internal mean the same. Friend is used in vb.net. Internal is used in c#.
Friends can be accessed by all classes within an assembly but not from outside the assembly.
Protected
Protected variables can be used within the class as well as the classes that inherites this class.
Protected friend/protected internal
The protected friend can be accessed by members of the assembly or the inheriting class, and of course, within the class itself.
Default
A default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as shared/static or private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability,so use this option sparingly.

Interview Questions on DotNet Framework Part 2
1. What�s an interface class?
It�s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
2. Why can�t you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it�s public by default.
3. Can you inherit multiple interfaces? Yes
4. What�s the difference between an interface and abstract class?
In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
5. How can you overload a method?
Different parameter data types, different number of parameters, different order of parameters.
6. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
7. What�s the difference between System.String and System.StringBuilder classes?
System.String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
8. What�s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it�s being operated on, a new instance is created.
9. Can you store multiple data types in System.Array?
If the Array is System.Object Type then the answer is Yes else No.
10. What�s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.
11. How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
12. What�s the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
13. What�s class SortedList underneath? A sorted HashTable.
14. Will finally block get executed if the exception had not occurred? Yes.
15. What�s the C# equivalent of C++ catch (�), which was a catch-all statement for any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
16. Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
17. What�s a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
18. What�s a multicast delegate? It�s a delegate that points to and eventually fires off several methods.
19. How�s the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
20. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
21. What namespaces are necessary to create a localized application?
System.Globalization, System.Resources.
22. What�s the difference between // comments, /* */ comments and /// comments?
Single-line, multi-line and XML documentation comments.
23. How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with a /doc switch.
24. What�s the difference between and XML documentation tag?
Single line code example and multiple-line code example.
25. Is XML case-sensitive? Yes, so and are different elements.
26. What debugging tools come with the .NET SDK?
CorDBG � command-line debugger, and DbgCLR � graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
27. What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
28. What�s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
29. Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
30. Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.
31. How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.
32. What are three test cases you should go through in unit testing?
Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
33. Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
34. Explain the three services model (three-tier application).
Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
35. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it�s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

36. What�s the role of the DataReader class in ADO.NET connections?
It returns a read-only dataset from the data source when the command is executed.
38. What does Dispose method do with the connection object?
Deletes it from the memory.
39. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.

40. Can you write a class without specifying namespace? Which namespace does it belong to by default??
Yes, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn�t want global namespace.
Interview Questions on Dotnet Window Application
1. You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What�s the problem?
One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.
2. How can you save the desired properties of Windows Forms application?
config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
3. So how do you retrieve the customized properties of a .NET application from XML .config file?
Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
4. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio?
The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.
5. What�s the difference between WindowsDefaultLocation and Windows Default Bounds?
WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
6. What�s the difference between Move and LocationChanged? Resize and SizeChanged?
Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.
7. How would you create a non-rectangular window, let�s say an ellipse?
Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
8. How do you create a separator in the Menu Designer?
A hyphen �-� would do it. Also, an ampersand '&' would underline the next letter.
9. How�s anchoring different from docking?
Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

Interview Questions on Dotnet Remoting and Distributed Computing
1. What�s a Windows process?
It�s an application that�s running and had been allocated memory.
2. What�s typical about a Windows process in regards to memory allocation?
Each process is allocated its own block of available RAM space, no process can access another process� code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
3. Why do you call it a process? What�s different between process and application in .NET, not common computer usage, terminology?
A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
4. What distributed process frameworks outside .NET do you know?
Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
5. What are possible implementations of distributed applications in .NET?
.NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.

6. When would you use .NET Remoting and when Web services?
Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
7. What�s a proxy of the server object in .NET Remoting?
It�s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
8. What are remotable objects in .NET Remoting?
Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
9. What are channels in .NET Remoting?
Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A c

Interview Questions on Microsoft SQL Server Part - 1
1. What�s the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn�t allow NULLs, but unique key allows one NULL only.
2. Write a SQL Query to find first Week Day of month?
SELECT DATENAME(dw, DATEADD(dd, - DATEPART(dd, GETDATE()) + 1, GETDATE())) AS FirstDay
3. How to find 6th highest salary from Employee table
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 6 salary FROM employee ORDER BY salary DESC) a ORDER BY salary

4. What is a join and List different types of joins.
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
5. How can I enforce to use particular index?
You can use index hint (index=index_name) after the table name. SELECT au_lname FROM authors (index=aunmind)
6. What is sorting and what is the difference between sorting and clustered indexes?
The ORDER BY clause sorts query results by one or more columns up to 8,060 bytes. This will happen by the time when we retrieve data from database. Clustered indexes physically sorting data, while inserting/updating the table.
7. What are the differences between UNION and JOINS?
A join selects columns from 2 or more tables. A union selects rows.
8. What is the Referential Integrity?
Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value
9. What is the row size in SQL Server 2000?
8060 bytes.
10. How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. eg: Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec 17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation Enterprise Edition on Windows NT 5.0 (Build 2195: Service Pack 3)
11. What is the purpose of UPDATE STATISTICS?
Updates information about the distribution of key values for one or more statistics groups (collections) in the specified table or view.

12. What is the use of SCOPE_IDENTITY() function?
Returns the most recently created identity value for the tables in the current execution scope.
13. What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, detaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
14. How do you transfer data from text file to database (other than DTS)?
Using the BCP (Bulk Copy Program) utility.
15. What's the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.
16. What is a deadlock?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.
17. What is a LiveLock?
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
18. How to restart SQL Server in single user mode?
From Startup Options :- Go to SQL Server Properties by right-clicking on the Server name in the Enterprise manager. Under the 'General' tab, click on 'Startup Parameters'. Enter a value of -m in the Parameter.
19. Does SQL Server 2000 clustering support load balancing?
SQL Server 2000 clustering does not provide load balancing; it provides failover support. To achieve load balancing, you need software that balances the load between clusters, not between servers within a cluster.
20. What is DTC?
The Microsoft Distributed Transaction Coordinator (MS DTC) is a transaction manager that allows client applications to include several different sources of data in one transaction. MS DTC coordinates committing the distributed transaction across all the servers enlisted in the transaction.
21. What is DTS?
Microsoft� SQL Server� 2000 Data Transformation Services (DTS) is a set of graphical tools and programmable objects that lets you extract, transform, and consolidate data from disparate sources into single or multiple destinations.

22. What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them.
23. What are the constraints ?
Table Constraints define rules regarding the values allowed in columns and are the standard mechanism for enforcing integrity. SQL Server 2000 supports five classes of constraints. NOT NULL , CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY.

24. What is Transaction?
A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction.

25. What is Isolation Level?
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. A lower isolation level increases concurrency, but at the expense of data correctness. Conversely, a higher isolation level ensures that data is correct, but can affect concurrency negatively. The isolation level required by an application determines the locking behavior SQL Server uses. SQL-92 defines the following isolation levels, all of which are supported by SQL
Server:
Read uncommitted (the lowest level where transactions are isolated only enough to ensure that physically corrupt data is not read).
Read committed (SQL Server default level).
Repeatable read.
Serializable (the highest level, where transactions are completely isolated from one another).
26. What is denormalization and when would you go for it?
As the name indicates, denormalization is the reverse process of normalization. It's the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced.
27. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
It will be a good idea to read up a database designing fundamentals text book.
28. What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.
29. What are user defined datatypes and when you should go for them?
User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables.
See sp_addtype, sp_droptype in books online.
30. What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
31. Define candidate key, alternate key, composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
32. What are defaults? Is there a column to which a default can't be bound?
A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns can't have defaults bound to them. See CREATE DEFUALT in books online.
33. What is a transaction and what are ACID properties?
A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. For more information and explanation of these properties, see SQL Server books online or any RDBMS fundamentals text book.
34. Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level.
35. CREATE INDEX myIndex ON myTable(myColumn)
What type of Index will get created after executing the above statement?
Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise.

36. What is lock escalation?
Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards it's dynamically managed by SQL Server.
37. What�s the difference between DELETE TABLE and TRUNCATE TABLE commands?
DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.
38. 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"

39. 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 craete 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 it's 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 t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used.
40. What is RAID and what are different types of RAID configurations?
RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory board's homepage
Interview Questions on Microsoft SQL Server Part - 2
1. What are the steps you will take to improve performance of a poor performing query?
This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But 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.
Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer.
2. What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one user's process.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base.
3. What is blocking and how would you troubleshoot it?
Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first.
Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions.

4. How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode?
SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal confuguration mode. Check out SQL Server books online for more parameters and their explanations.

5. What are statistics, under what circumstances they go out of date, how do you update them?
Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query.
Some situations under which you should update statistics:
1) If there is significant change in the key values in the index
2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated
3) Database is upgraded from a previous version
Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats
6. What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available. Some of the options are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.
7. Explain different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan?
Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup.
8. What is database replicaion? What are the different types of replication you can set up in SQL Server?
Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios: Snapshot replication ,Transactional replication (with immediate updating subscribers, with queued updating subscribers) ,Merge replication
9. How to determine the service pack currently installed on SQL Server?
The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.
10. What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row prcessing 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.
11. Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression]
[HAVING search_condition] [ORDER BY order_expression [ASC | DESC] ]
12. What is a join and explain different types of joins.
Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table.
Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.
For more information see pages from books online titled: "Join Fundamentals" and "Using Joins".
13. Can you have a nested transaction?
Yes

14. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL?
An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server.
Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see 'My code library' section of this site.
15. 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().
16. 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.
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.
Implementing Triggers in SQL Server 2000

Triggers are special types of Stored Procedures that are defined to execute automatically in place of or after data modifications. They can be executed automatically on the INSERT, DELETE and UPDATE triggering actions.
There are two different types of triggers in Microsoft SQL Server 2000. They are INSTEAD OF triggers and AFTER triggers. These triggers differ from each other in terms of their purpose and when they are fired.


17. What is a self join? Explain it with an example.
Self join is just like any other join, except that two instances of the same table will be joined in the query.
18. 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.
19. What is the T-SQL equivalent of IIF (immediate if/ternary operator) function of other programming languages?
CASE is the equivalent of IIF function. See SQL Server Books Online for more information. Here's a quick example: CREATE TABLE People ( [ID] int PRIMARY KEY, [Name] varchar(25) NOT NULL, Sex bit NULL ) INSERT INTO People ([ID],[Name], Sex) VALUES (1,'John Dykes', 1) INSERT INTO People ([ID],[Name], Sex) VALUES (2,'Deborah Crook', 0) INSERT INTO People ([ID],[Name], Sex) VALUES (3,'P S Subramanyam', NULL) SELECT [ID], [Name], CASE Sex WHEN 1 THEN 'Male' WHEN 0 THEN 'Female' ELSE 'Not specified' END AS Sex FROM People
20. 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 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

21. 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)
22. 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?
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'
23. 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 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 SelectTable @Table sysname AS EXEC ('SELECT * FROM ' + @Table)
GO
EXEC SelectTable 'MyTable'
24. 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.
25. How to join tables from different databases?
You just have to qualify the table names in your SELECT queries with database name, followed by table owner name. In the following example, Table1 from pubs database and Table2 from northwind database are being joined on the column i. Both tables are owned by dbo.
SELECT a.i, a.j FROM pubs.dbo.Table1 a INNER JOIN northwind.dbo.Table2 b ON a.i = b.i
26. How to join tables from different servers?
To be able to join tables between two SQL Servers, first you have to link them. After the linked servers are setup, you just have to prefix your tables names with server name, database name, table owner name in your SELECT queries. The following example links SERVER_01 to SERVER_02. Execute the following commands in SERVER_02:
EXEC sp_addlinkedserver SERVER_01
GO
/* 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

27. How to convert timestamp data to date data (datetime datatype)?
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.