Comparing DCOM,Remoting and Web Services


What is .NET Remoting?



.NET Remoting is an enabler for application communication. It is a generic system for different applications to use to communicate with one another. .NET objects are exposed to remote processes, thus allowing interprocess communication. The applications can be located on the same computer, different computers on the same network, or even computers across separate networks.

.NET Remoting versus Distributed COM



In the past interprocess communication between applications was handled through Distributed COM, or DCOM. DCOM works well and the performance is adequate when applications exist on computers of similar type on the same network. However, DCOM has its drawbacks in the Internet connected world. DCOM relies on a proprietary binary protocol that not all object models support, which hinders interoperability across platforms. In addition, have you tried to get DCOM to work through a firewall? DCOM wants to communicate over a range of ports that are typically blocked by firewalls. There are a ways to get it to work, but they either decrease the effectiveness of the firewall (why bother to even have the firewall if you open up a ton of ports on it), or require you to get a firewall that allows support for binary traffic over port 80.
.NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used.

.NET Remoting versus Web Services



Unless you have been living in a cave, or are way behind in your reading, you have probably read something about Web services. When you read the description of .NET Remoting it may remind you a lot of what you're read about Web services. That is because Web services fall under the umbrella of .NET Remoting, but have a simplified programming model and are intended for a wide target audience.
Web services involve allowing applications to exchange messages in a way that is platform, object model, and programming language independent. Web services are stateless and know nothing about the client that is making the request. The clients communicate by transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or SOAP. (Want to get some funny looks in the hallway? Stand around in the hallway near the marketing department with your colleagues and discuss the benefits of using SOAP).

The following list outlines some of the major differences between .NET Remoting and Web services that will help you to decide when to use one or the other:

· ASP.NET based Web services can only be accessed over HTTP. .NET Remoting can be used across any protocol.

· Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can correlate multiple calls from the same client and support callbacks.

· Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.

· Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET, or another framework that supports .NET Remoting, which means a homogeneous environment.

.NET Remoting Or Web Services?


Overview

Traditionally, distributed application design called for the use of component technologies such as DCOM or CORBA. Although these component technologies work very well within an intranet environment, using them over the Internet often presented two serious problems:
  1. Current component technologies do not inter-operate. While they all dealt with components and objects, they differed over lifecycle management, constructor details, degree of support for inheritance and so on.
  2. Current component technologies focus on RPC-style communication. This led to tightly coupled systems built around the invocation of object methods.
Browser-based web applications are loosely coupled and are remarkably inter-operable.  They communicate using HTTP to exchange MIME-typed data in a wide range of formats. Web Services adapt the traditional web programming mode for use from all sorts of applications, not just from a browser. Web Services exchange SOAP message using HTTP and other Internet Protocols. And because Web Services rely on industry standards like HTTP, SOAP, and XML to expose application functionality, they are independent of programming language, platform and device. The only requirement for a Web Service to communicate with a client is to agree on the format of the SOAP messages being produced and consumed, as defined in the Web Service's contract definition, commonly known as WSDL.
.NET Remoting provides an infrastructure for distributed objects. It exposes the full-object semantics of .NET to processes using plumbing that is very flexible and extensible. Compared to Web Services which provide a very simple programming model based on passing messages, the .NET Remoting offers much more complex functionality including passing objects around (by-value or by-reference), callbacks, and multiple object invocation and lifecycle management.
In order to use .NET Remoting, the client must be aware of all the above details. In short, the client needs to be built with .NET or with a framework that supports .NET. Not that even .NET Remoting supports SOAP, this does not change the client requirements. If a remoting endpoint exposes .NET object semantics, via SOAP or not, the client must understand them.
The fact that the .NET Framework allows you to easily build Web Services or .NET Remoting applications has caused confusion. Which technology do you use? To really answer this question, you have to understand how both technologies work.

Serialization & Metadata

All distributed communication plumbing, .NET Remoting or Web Services, eventually does two things:
  • Marshal instances of programmatic data types into messages that can be sent across the network via data packets. This is usually accomplished via some serialization of marshalling engine.
  • Provide a description of what those messages look like. This is usually accomplished through some form of metadata. In the case of COM/DCOM, the serialization engine was the Type Library Marshaler, and the metadata was provided by the type library.
The key difference between ASP.NET Web Services and .NET Remoting is how they serialize data into messages, and the format they choose for metadata. Serialization and metadata for Web Services and .NET Remoting are discussed below.

ASP.NET Web Services: XmlSerializer and XSD

As the title suggests, for Web Services, XmlSerializer is the 'serialization engine' and XSD is the metadata. ASP.NET Web Services rely on theSystem.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime. For metadata, ASP.NET Web Services generate WSDL and XSD definitions that describe that their messages contain.
The reliance of ASP.NET Web Services on WSDL and XSD makes their metadata portable because they express data structures in a way that other Web Services on other platforms and with different programming languages can understand. Note however, that XmlSerializer will only marshal things that can be described by XSD -XmlSerializer will not marshal object graphs and has limited support for container types.
Support for interoperability is augmented by a rich set of custom attributes that allow you to annotate your data types to control the way in which the XmlSerializermarshals them. As a result, you have a fine-grained control over the shape of the XML being generated when an object is serialized.

.NET Remoting: IFormatter and the CLR.

As the title suggests, for .NET Remoting, IFormatter is the 'serialization engine' and the Common Language Runtime (CLR) is the metadata. .NET Remoting depends on the pluggable implementations of the IFormatter interface to marshal data to and from messages. The .NET Framework offers two built-in formatters:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter andSystem.Runtime.Serialization.Formatters.Soap.SoapFormatter. As the names suggest, the BinaryFormatter and the SoapFormatter marshal data types in binary and SOAP formats, respectively. Note that irrespective of the data format, .NET Remoting can send data over either HTTP or TCP channels.
As for metadata, the .NET Runtime relies on the CLR assemblies which contain all the relevant information about the data types they implement, and expose via reflection. The reliance on the assemblies for metadata makes it very easy to preserve the full runtime type-system fidelity. As a result, when the .NET Remoting marshals data, it includes all of a class's public and private members, handles object graphs correctly, and supports all container types (ArrayListHashTable, etc.) However, the reliance on the runtime metadata also limits the reach of a .NET Remoting system - the client must also be able to understand .NET constructs in order to be able to communicate with a .NET end point.

.NET Remoting and ASP.NET Web Services

.NET Remoting supports two channels, one for raw TCP and another for HTTP. And as noted in the previous section, .NET Remoting also has a built-in SOAP formatter (in addition to the binary one) . So, can .NET Remoting be used to build Web Services?
The standard Web Service technology stack relies not only on SOAP messages, but also on WSDL and XSD-based description of those SOAP messages. .NET Remoting plumbing can actually generate WSDL that describe messages consumed and produced by endpoints, but there are a couple of issues including the fact that the generated WSDL files will include extensions that are .NET Remoting-specific. For example, if a .NET Remoting endpoint (i.e., a remote function) returns a DataSet, then the generated WSDL for this method will also contain a reference to DataSet. For some Web Services that do not find an XSD-schema definition for a DataSet, this WSDL will be useless.
So the answer to whether you can use .NET Remoting to build Web Services is yes and no. You can build Web Services with .NET Remoting but whether anybody who is not using the .NET Remoting will be able to use them will depend if you are able to describe your end point to bare data types and semantics. And if you want inter-operability with other Web Service toolkits, you will need to restrict parameters to the simple built-in types and your own data types (don't use .NET Framework types), and avoid client-activated objects and events. In short, if you care about reach, you need to restrict yourself to the same set of functionality that ASP.NET Web Services use. Better yet, why not use ASP.NET Web Services?

Distributed Application Design

ASP.NET Web Services favor the XML Schema type system, and provide a simple programming model with broad cross-platform reach.NET Runtime favors the runtime type system, and provides a more complex programming model with a limited reachThis essential difference is the primary factor in determining which technology to use.
However, there are a wide range of other design factors, including transport protocol, host processes, security, performance, state management and support for transactions as well. These concepts are discussed below.

Transport Protocols & Host Processes

Although the SOAP specification does not mandate the use of HTTP as the transfer protocol, a client can access Web Services implemented in ASP.NET only using HTTP as the transport protocol. HTTP is the only transport protocol that ASP.NET supports. The services are invoked via IIS and execute in the ASP.NET worker process -aspnet_wp.exe.
.NET Remoting on the other hand, allows you to host remote objects in any type of application including Windows Forms, Windows Services, Console applications, or even IIS. And as previously noted, .NET Remoting supports two transport channels - HTTP and TCP.  The following summarizes these points:
TechnologyTransport ProtocolsHost Processes
ASP.NET Web ServicesHTTP onlyIIS only (aspnet_wp.exe)
.NET RemotingHTTP and TCPIIS, Windows Forms, Windows Services, and console apps.
Note that the .NET Remoting plumbing does not include a DCOM-style Service Control Manager (SCM) to start remote servers. If you expose remote objects from some process, you must ensure that that process is running before it can server any remote objects. You also have to ensure that they are thread-safe - i.e., thread A cannot create an object after thread B has started to shut down the process. If you expose remote objects from ASP.NET (i.e., remote objects are deployed in IIS), you can take advantage of the fact that the ASP.NET worker process, aspnet_wp.exe is both auto-starting and thread safe. Deploying objects in IIS is also an excellent way to secure a cross-process .NET Remoting call.
Both ASP.NET and .NET Remoting are extensible architectures. You can filter inbound and outbound messages, control aspects of type marshalling, and metadata generation. 

Security

Because ASP.NET Web Services rely on HTTP, they integrate well with the standard internet security architecture. ASP.NET uses the security features of IIS to provided strong support for standard HTTP authentication, authorization such as Basic, digest, digital certificates, and even MS Passport. However, even though these standard transport-level techniques to secure Web Services are quite effective, they only go so far. In complex scenarios involving multiple Web Services in different trust domain, you will need to use ad-hoc solutions. Work is currently in-progress on a set of security  specification that build on the extensibility of SOAP messages to offer message-level security capabilities.
In the general case, .NET Remoting does not secure cross-process calls. However, a .NET Remoting endpoint deployed in IIS can use the security features of IIS quite easily, including the use of SSL for secure communication across the wire. However, note that if you are using a TCP or HTTP channel in a process outside IIS, then you will need to implement your own authorization and authentication mechanisms. The following table summarizes these points:
TechnologySecurity
ASP.NET Web ServicesUses the security features of IIS by default
.NET RemotingCross-process calls are not secured. Will use the security features of IIS only if deployed in IIS.

State Management

The ASP.NET Web Services model assumes a stateless service architecture by default. It does not inherently relate multiple calls from the same user. Each time a client makes a call to a Web Service page, a new object is created to service the request. The object is destroyed after the method call is complete. To maintain state across calls, you can either use the Application and Session objects, or you can implement your own custom solution. 
.NET Remoting supports a wide range of state management options and may or may not correlate multiple calls from the same user depending on what type of object you choose. For example, Server-Activated Objects (SAO) do not correlate calls from the same user: Singleton objects share state for all users, and SingleCall Objects are stateless. Client-Activated Objects (CAO) however, do correlate calls from the same user and they maintain state per client. The following table summarizes these points:
TechnologyState Management
ASP.NET Web ServicesStateless by default. State can be managed using standard ASP.NET objects or a custom solution
.NET RemotingDifferent management options depending on the type of the remote object.

Performance

In terms of raw performance, the .NET Remoting provides the fastest communication when using the TCP channel with the binary formatter. Tests have shown that ASP.NET Web Services outperform .NET Remoting for endpoints that used the SOAP formatter with either the HTTP or TCP channel.

Choosing an Architecture

You will need to consider all of the issues discussed here before you start designing a distributed application built on .NET. Here are some general assumptions you can make that will simplify the process of choosing between ASP.NET Web Services and .NET Remoting:
  • By default, use ASP.NET Web Services. They are simpler to implement and use, and offer the broadest reach to clients.
  • Consider .NET Remoting if you need a more traditional distributed object model with full CLR type fidelity, don't need interoperability with other platforms, and have control over client and server configurations.
  • If you choose .NET Remoting, prefer the HTTP channel registered with IIS and ASP.NET. Otherwise, you will have to build your own process lifecycle management and security infrastructure.
  • Given that .NET Remoting requires .NET client, it makes sense to use the binary formatter instead.
  • Use Enterprise Services when you need declarative transactions.

SQL Interview Quations


Check out the article Q100139 from Microsoft knowledge base and of course, there's much more information available in the net. It'll be a good idea to get a hold of any RDBMS fundamentals text book, especially the one by C. J. Date. Most of the times, it will be okay if you can explain till third normal form.

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.

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.

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.

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.

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). Until 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.

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.

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.

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.

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.

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.

What's the maximum size of a row?

8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations

Hopefully you have experience setting up cluster servers. But if you don't, at least be familiar with the way clustering works and the two clusterning configurations Active/Active and Active/Passive. SQL Server books online has enough information on this topic and there is a good white paper available on Microsoft site.

Explain the architecture of SQL Server

This is a very important question and you better be able to answer it if consider yourself a DBA. SQL Server books online is the best place to read about SQL Server architecture. Read up the chapter dedicated to SQL Server Architecture.

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.

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.

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for more information.

What are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What changed between the previous version of SQL Server and the current version?

This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "What's New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.

What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults.

Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY

For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

Whar 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.

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

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.

Download the white paper on performance tuning SQL Server from Microsoft web site. Don't forget to check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing an SQL Server?

Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, database and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc.

Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server security best practices

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.

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.

Explain CREATE DATABASE syntax

Many of us are used to craeting databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB. But what if you have to create a database with two filegroups, one on drive C and the
other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? That's why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books
online for more information.

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.

As a part of your job, what are the DBCC commands that you commonly use for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information.

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

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, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERT scripts to generate data.

Explian 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.

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

See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc.

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.

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.

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] ]

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".

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

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.

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().

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.

Also check out books online for 'inserted table', 'deleted table' and COLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.


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. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join.

CREATE TABLE emp
(
empid int,
mgrid int,
empname char(10)
)

INSERT emp SELECT 1,2,'Vyas'
INSERT emp SELECT 2,3,'Mohan'
INSERT emp SELECT 3,NULL,'Shobha'
INSERT emp SELECT 4,2,'Shridhar'
INSERT emp SELECT 5,2,'Sourabh'

SELECT t1.empname [Employee], t2.empname [Manager]
FROM emp t1, emp t2
WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]
FROM emp t1
LEFT OUTER JOIN
emp t2
ON
t1.mgrid = t2.empid

SSC 2011 RESULTS and MArks

common job interview questions with answers for every interviewer

Tell me something about yourself.

This is the vital question of the interview. Before answering this question you must understand the purpose behind it. The answer to this question reflects what you think about yourself.

The answer should be in such a way that it should not be like you are reading your CV all over again. It can be something like -
Sir , as you already know my name is XXXXx. Tell about your birth place, schooling details…..till college. Discuss the time from your birth till now…….There is no need to mention the percentage of marks you scored in the school. You can mention the percentage of marks you scored in college, if it is good.

In the end finish it with a question, for e.g., Is there any thing else you would like to know about me, sir?

Tell me something about your parents.

My father’s name is XXXXXX. Discuss his occupation along with his contribution to society and role played by him in society.

About your mother same as above if she is working.

If she is a house wife then never undermine her contribution by referring to her as a simple house wife. You should portray her as a house maker. Along with this, mention that she is doing her job since so many years consistently without any leave and any appreciation.

If you want to change any thing in your life, what will you change?

I am very much happy and satisfied with my life, this is the gift of god. But then also, if ever in life knowingly or unknowingly I have ever hurt my elders (parents, teachers), I just want to change that like it never happened and say sorry to them.

What is your weakness or what are you afraid of?

Most appropriate answer would be something like – Sir, I can make a presentation in front of hundreds of people but whenever it came to sing a song in the class, I really shivered and I couldn’t sing even a single line. Your weakness should be presented in such a manner that it doesn’t seem to be your weakness.

What package you are looking for?

For freshers:
You are very lucky that you are sitting in an interview……you can’t be demanding. Your answer should be, sir as per company policy whatever package would be offered I’ll accept that. But this is a very casual answer.
Your answer should be something like: “Sir, as you know I am a fresher and the only thing I can expect at this point of time is that I should get a job in a prestigious company like yours. Of course every one works for money I would be expecting something which is sufficient to make my living in a city and I should be able to support my family a bit.

Do you have a girl friend/Wife?

Always speak the truth in your interview, never tell lies. Your views about her should not be orthodox and you should always be supporting and encouraging towards her.

What is your Vision?

The answer for this question is to be decided by you. Before you start answering, you should understand the meaning of “vision”. Vision is a long term task/goal or long life commitment. Now this commitment can be with yourself, towards your society, wife, parents etc. e.g. I want to open an orphanage after finishing all family responsibilities.

What is the mission of your life?

This is same as vision but the only difference is that mission is for short terms. Like when you were in class XII your mission was to get admission in a good Engineering College. It keeps changing with time.

Where do you see yourself after 2-3 years from now?

The answer for this question varies from company to company and it depends on the hierarchy of the company. Your answer should be something like: Sir, initially I would be learning and knowing my work and company. In a year or after 1 year I expect from myself to be an expert in solving the issues on L1 level. And after that I would like to get a certification on the technology I am working. So within 2-3 yrs I expect myself to be a proficient engineer on L2 level.

What are your hobbies?

This is a very tricky question, I repeat very tricky question. You should mention your hobbies in which you have deep knowledge. Like cricket or playing cricket, by mentioning cricket you have given a wide scope to the interviewer as he can ask any thing from cricket infact he can ask any year also. But by mentioning playing cricket you have reduced the scope. Another e.g. is Music and Listening Music. Mentioning reading as your hobby is very risky because if you have read some books and the interviewer has also read it then he can ask a lot of questions related to it. You should be very cautious about it.

What kind of a person are you - Introvert/Extrovert?

Being totally introvert or extrovert is not right. You should be having a mixed behavior and behave as per the requirement of the situation. You can say something like- Sir, I behave according to the place and situation. Eg. Introvert personally and extrovert professionally.

Do you believe in competition or team work?

According to famous phrase “necessity is the mother of invention”. If there is no competition then there will not be any growth, the growth can be professional or personal. For any project or any work, team work is most important because a single person cannot do anything alone.

Competition and team work both are important.

If your manger has given you a task and your manager’s manger is saying not to do that work, what you will do? You will obey your manager or his manager?

I will obey my manager, as I believe that if my manager has assigned me a work he must have discussed it with his manager. I am his resource and my role is to obey him.

In a catastrophic situation like fire what you will do?

No heroic an answer is expected from you. They want to see how you would behave in such a situation. You can say something like – First, I would ensure my safety and then I will inform the fire department of company and city. If I am in a position of helping someone then I would definitely do that.

If you get a better package than here what will you do accept that offer or reject that?

This question means a lot. HR people want that the hired person should serve the company for longer period. You can say something like: Sir, as you know I am a fresher and if I switch the jobs very quickly then it will be a question mark on my stability, which will affect my career. Above all, I have to learn and increase my technical knowledge as well. Money comes with knowledge. So, I am here to learn and provide my best to the company.

Andhrapradesh SSC Results With marks

SSC Results

..........................................................................


SSC Results With Marks

SSC 2011 REsults

andhrapradesh ssc 2011 results

http://www.examresults.net/ssc/


................................................................................................

http://results.andhraeducation.net/

....................................................

http://www.manabadi.co.in/SSssc 2011 resultsCResults2011.htm

.................................................................................



www.indiaresults.com

Triggers -- Sql Server

INTRODUCTION

TRIGGERS IN SQL SERVER

BACKGROUND

This article gives a brief introduction about Triggers in Sql Server 2000/2005.

What is a Trigger

A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of data. It is a database object which is bound to a table and is executed automatically. You can’t explicitly invoke triggers. The only way to do this is by performing the required action no the table that they are assigned to.

Types Of Triggers

There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and hybrids that come from mixing and matching the events and timings that fire them.

Basically, triggers are classified into two main types:-

(i) After Triggers (For Triggers)
(ii) Instead Of Triggers

(i) After Triggers

These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:

(a) AFTER INSERT Trigger.
(b) AFTER UPDATE Trigger.
(c) AFTER DELETE Trigger.

Let’s create After triggers. First of all, let’s create a table and insert some sample data. Then, on this table, I will be attaching several triggers.

Collapse
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)

INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);

I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this audit table is to record the changes in the main table. This can be thought of as a generic audit trigger.

Now, create the audit table as:-
Collapse
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)

(a) AFTRE INSERT Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:-
Collapse
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test] 
FOR INSERT
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 set @audit_action='Inserted Record -- After Insert Trigger.';

 insert into Employee_Test_Audit
           (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER INSERT trigger fired.'
GO
The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table name on which the trigger is to be attached. The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the same.
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values into the Audit table.
To see the newly created trigger in action, lets insert a row into the main table as :
Collapse
insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:-
Collapse
6   Chris  1500.00   Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700

(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:-
Collapse
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test] 
FOR UPDATE
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=i.Emp_ID from inserted i; 
 select @empname=i.Emp_Name from inserted i; 
 select @empsal=i.Emp_Sal from inserted i; 
 
 if update(Emp_Name)
  set @audit_action='Updated Record -- After Update Trigger.';
 if update(Emp_Sal)
  set @audit_action='Updated Record -- After Update Trigger.';

 insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER UPDATE Trigger fired.'
GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the logical table inserted. We can obtain the updated value of a field from the update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.
Collapse
update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:-
Collapse
6  Chris  1550.00  Updated Record -- After Update Trigger.   2008-04-26 12:38:11.843 

(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:-
Collapse
CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test] 
AFTER DELETE
AS
 declare @empid int;
 declare @empname varchar(100);
 declare @empsal decimal(10,2);
 declare @audit_action varchar(100);

 select @empid=d.Emp_ID from deleted d; 
 select @empname=d.Emp_Name from deleted d; 
 select @empsal=d.Emp_Sal from deleted d; 
 set @audit_action='Deleted -- After Delete Trigger.';

 insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
 values(@empid,@empname,@empsal,@audit_action,getdate());

 PRINT 'AFTER DELETE TRIGGER fired.'
GO
In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table.
Let’s fire a delete on the main table.
A record has been inserted into the audit table as:-
Collapse
6  Chris 1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867 
All the triggers can be enabled/disabled on the table using the statement
Collapse
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL 
Specific Triggers can be enabled or disabled as :-
Collapse
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table.

(ii) Instead Of Triggers

These can be used as an interceptor for anything that anyonr tried to do on our table or view. If you define an Instead Of trigger on a table for the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:-

(a) INSTEAD OF INSERT Trigger.
(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.

(a) Let’s create an Instead Of Delete Trigger as:-
Collapse
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test] 
INSTEAD OF DELETE
AS
 declare @emp_id int;
 declare @emp_name varchar(100);
 declare @emp_sal int;
 
 select @emp_id=d.Emp_ID from deleted d;
 select @emp_name=d.Emp_Name from deleted d;
 select @emp_sal=d.Emp_Sal from deleted d;

 BEGIN
  if(@emp_sal>1200)
  begin
   RAISERROR('Cannot delete where salary > 1200',16,1);
   ROLLBACK;
  end
  else
  begin
   delete from Employee_Test where Emp_ID=@emp_id;
   COMMIT;
   insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
   values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
   PRINT 'Record Deleted -- Instead Of Delete Trigger.'
  end
 END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger will rollback the transaction, otherwise the transaction will be committed.
Now, let’s try to delete a record with the Emp_Sal >1200 as:-

Collapse
delete from Employee_Test where Emp_ID=4
This will print an error message as defined in the RAISE ERROR statement as:-

Collapse
Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200 

And this record will not be deleted.
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.

CONCLUSION

In this article, I took a brief introduction of triggers, explained the various kinds of triggers – After Triggers and Instead Of Triggers along with their variants and explained how each of them works. I hope you will get a clear understanding about the Triggers in Sql Server and their usage.