ASP.NET Session State Management Using SQL Server

Web applications are by nature stateless. Statelessness is both an advantage and a disadvantage. When resources are not being consumed by maintaining connections and state, scalability is tremendously improved. But the lack of state reduces functionality severely. Ecommerce applications require state to be maintained as the user navigates from page to page. ASP.NET’s Session object makes it easy for developers to maintain state in a Web application. State can be maintained in-process, in a session state server, or in SQL Server.
           In-process state management is the ASP.NET default, and it offers the fastest response time, but does not work in a Web farm. Consequently, it is not practical in high capacity Web applications requiring the load to be spread over multiple servers. A dedicated session state server is shared by all servers in a Web farm, so it provides scalability of the Session objects across all Web servers. It cannot store state persistently. If a dedicated session state server goes down for any reason, all session state data is lost. SQL Server is another alternative for storing session state for all of the servers in a Web farm. Since SQL Server is a database, there is a popular misconception that ASP.NET session state maintained in SQL Server is stored persistently. By default, it is not. If the SQL Server is stopped, the session state data is lost. By making a few simple changes, state can be stored persistently. It is important to understand that persistent is not the same thing as permanent. ASP.NET places a time limit (timeout in web.config) on how long a session’s state is maintained. If the SQL Server is configured to store state persistently and it is down for longer than the ASP.NET session timeout interval, the session state data is lost.

Configuring ASP.NET Session State Management

             Use the sessionState section of the web.config file to configure an ASP.NET Web application to use a SQL Server for session state management. The session state timeout interval is specified by using the timeout parameter.

        By default ASP .NET uses cookies to identify which requests
        belong to a particular session.
        If cookies are not available, a session can be tracked by
        adding a session identifier to the URL.
        To disable cookies, set sessionState cookieless=”true”.

   _ mode=”SQLServer”
   _ stateConnectionString=”tcpip=″
   _ sqlConnectionString=”data source=; integrated security=true”
   _ cookieless=”false”
   _ timeout=”20″

               Configure the SQL Server to store Session objects by running a script to create the ASPState database. Version 1.0 of the .NET Framework provides a state database configuration script in %SYSTEMROOT%\Microsoft.NET\Framework\v1.0.3705\InstallSqlState.sql. If you open the file, you will see a statement to create a database called ASPState. This probably adds to the confusion about state being persistent. The ASPState database contains stored procedures that create tables in tempdb. The tables in tempdb are where session state is actually stored. Thus, when the SQL Server is shutdown, all session state is lost. This raises an important question: If the SQL Server is never shutdown, will tempdb eventually become 100 percent full and run out of space? Recall that ASP.NET connections automatically time out and their resources are freed up after the timeout duration is exceeded. The InstallSqlState.sql script creates a job called ASPState_Job_DeleteExpiredSessions to delete expired sessions from tempdb. Recall that ASP.NET does not keep session resources alive indefinitely. To support this feature when a SQL Server is used to maintain state, the SQL Server Agent must be running so that the expired session deletion job runs as needed. By default, the job is scheduled to run every minute. It deletes session state rows with an Expires value less than the current time. The account under which the SQL Server Agent runs must have the privilege to execute the DeleteExpiredSessions stored procedure.
          ASPState database scripts come in pairs. InstallSqlState.sql creates the database and supporting objects. UninstallSqlState.sql drops the database and all supporting objects (e.g., the job to delete expired sessions). You cannot drop a database if it is in use, so if the UninstallSqlState.sql script fails with this error message:
Server: Msg 3702, Level 16, State 4, Line 4
Cannot drop the database ‘ASPState’ because it is currently in use.
Microsoft Knowledge Base article 311209 says to stop the Web server service to overcome this error. An “uninstallation” failure can still occur even if the Web server service is stopped. Additionally, you might not want to stop the Web server service because that will cause all Web applications on the server to stop. Instead, use the SQL Server Enterprise Manager. Find the processes accessing the ASPState database and delete them. If users are still accessing the application and causing new processes to be created faster than you can delete them, go to the IIS console and select the Properties for the Web application. On the Directory tab, click the Remove button. This will prevent access to the Web application and allow you to kill any remaining processes accessing the ASPState database. Once the processes are gone, uninstallation should completely successfully. Be sure to go back to the IIS console and click the Create button to restore the Web application to normal working order if you previously clicked the Remove button.
Version 1.0 of the .NET Framework does not provide a script for creating an ASPState database that maintains state persistently. However, Microsoft Knowledge Base article 311209 does provide a link for downloading InstallPersistentSqlState.sql and UninstallPersistentSqlState.sql. The InstallPersistentSqlState.sql script causes the session state data to be stored in permanent tables in ASPState instead of temporary tables in tempdb.
       Version 1.1 of the .NET Framework provides both InstallPersistentSqlState.sql and InstallSqlState.sql. The Framework Version 1.1 scripts are found in the %SYSTEMROOT%\Microsoft.NET\Framework\v1.1.4322 folder. Although the 1.0 and 1.1 versions of InstallPersistentSqlState.sql accomplish the same thing, they are different. For SQL Server 2000 and above, the 1.1 version creates the ASPState stored procedures using GETUTCDATE instead of GETDATE. The 1.0 version always uses GETDATE. You can use the Framework version 1.1 script to create a database for an application using the Framework version 1.0.
        If you specify integrated security in the web.config file, you will have to create a server login for the ASPNET user and then make the login a user in the ASPState database. You will also have to grant permissions to the ASPNET user to use database objects. If you do not store state persistently, the ASPNET user must be granted permissions to use state management objects in tempdb. The prudent approach is to grant no more permissions than are absolutely necessary. Here are the permissions I granted after executing the Version 1.0 InstallSqlState.sql script:
USE masterGOEXECUTE sp_grantlogin [DBAZINE\ASPNET]GO USE ASPState GO EXECUTE sp_grantdbaccess [DBAZINE\ASPNET] GRANT EXECUTE on TempGetAppId to [DBAZINE\ASPNET] GRANT EXECUTE on TempGetStateItemExclusive to [DBAZINE\ASPNET] GRANT EXECUTE on TempInsertStateItemShort to [DBAZINE\ASPNET] GO USE tempdb — remove this if using persistent state GO — remove this if using persistent state EXECUTE sp_grantdbaccess [DBAZINE\ASPNET] — remove this if persistent state GRANT SELECT on ASPStateTempApplications to [DBAZINE\ASPNET] GRANT INSERT on ASPStateTempApplications to [DBAZINE\ASPNET] GRANT SELECT on ASPStateTempSessions to [DBAZINE\ASPNET] GRANT INSERT on ASPStateTempSessions to [DBAZINE\ASPNET] GRANT UPDATE on ASPStateTempSessions to [DBAZINE\ASPNET] GO
      If you use the InstallPersistentSqlState.sql, remove the three lines as indicated above.
Consider the grants shown above as a starting point for creating your own script appropriate for your environment.


       ASP.NET offers two simple solutions to session state management in a Web farm. Only SQL Server offers persistent state management. A dedicated session state server does not offer persistent state management, but does not require the creation of a database (one more thing for the DBA to administer). The value of persistent state has to be weighed carefully. Maintaining session state persistently is useful only if the SQL Server can be brought back up within the session state timeout specified in the web.config. For those situations where using a SQL Server as a state server makes sense, ASP.NET makes it easy.
Referenced from this article.

Session.SessionID is not unique

I have seen many forums in which users are asking that Session.SessionID is not unique. You also have seen forums saying that “I am getting different value for SessionID on every page or in each post back.” Yes they are correct !!!! “This is not possible. How can it be?”, I know this is your reaction. We have read in all the books and seen practically that SessionID is unique, until user logs off or close the browser. This is also correct. Now you will say then why am I writing the story?

             Here is the actual fundamentals that I have observe practically. The session changes in each request (either post back or redirecting from one page to another page) until user has not insert any value in Session collection. This means server treats each request from new session if user has not entered any value in session. You can check this practically!!!

    Create a web application with two pages Default.aspx and Default2.aspx. Add one button and two lables on Default.aspx page. On page load of Default.aspx in if(!Page.IsPostBack) set any one lable’s text to Session.SessionID. Now in click event of button set second lable’s text to Session.SessionID. You can see that every time when post back occurs you have new value of SessionID. Amazing !!!!!!! You can check by redirecting to Default2.aspx page and print SessionID.

     Now, on Default.aspx page in if(!Page.IsPostBack) set Session["test"] = “1″ or set any name value collection. Once you do this run the page. Click on button any number of time and you see that now SessionID is unique.

   Really Amazing!!!!

Select Database Schema Name with their Owner Name

SELECT s.[name], s.[schema_id], aa.CATALOG_NAME, aa.SCHEMA_OWNER
  FROM sys.schemas s

List all Error Codes with description

Recently, I was facing some problem to check the proper error code in my procedure.
Thanks to Sql Server 2005. It gives a great user friendly Schema & System table names.
So This is the query by which we can see all the Error Codes,

SELECT s.[error], s.severity, s.dlevel, s.[description], s.msglangid
FROM sys.sysmessages s

Now, I can use Try-Catch block in sq l server 2005 & can raise appropriate Error also depending upon the Error Code.

Select all Stored Procedures with their parameters

SELECT s.[name], s2.[name], s2.type, s2.length, s2.colorder, s3.[name]
FROM sysobjects s
LEFT JOIN syscolumns s2 ON =
LEFT JOIN systypes s3 ON s3.[xusertype] = s2.xusertype
WHERE s.[type] = 'P' AND s.category = 0
ORDER BY s.[name], s2.colorder

Get Current User – Get Logged In User in sql server 2005

To get current user run following script in Query Editor
SYSTEM_USER will return current user. From Book On-Line – SYSTEM_USER returns the name of the currently executing context. If the EXECUTE AS statement has been used to switch context, SYSTEM_USER returns the name of the impersonated context.

Alternatively we can also use:

Find Tables With Foreign Key Constraint in Database

Constraint_Name = C.CONSTRAINT_NAME
---- optional:
WHERE PK.TABLE_NAME IN ('one_thing', 'another')
WHERE FK.TABLE_NAME IN ('one_thing', 'another')

show the parameters for a function or stored procedure


List Schema Name and Table Name for Database

SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
AS SchemaTable
FROM sys.tables

Execute permissions to db_executor Role

Giving users access to only stored procedure execute permissions is a common issue. It is a good security practice. In 2005, we can grant excecute permissions at the database level instead of having to do it on each and every stored procedure, which was a pain. So now people do this:
CREATE ROLE db_executor
GRANT EXECUTE TO db_executor

But I would definitely say that granting at the database level is not a best practice. You can just as easily grant at the schema level, and have better control.
GRANT EXECUTE on schema::dbo TO db_executor

Difference between Varchar & Nvarchar in Sqlserver

Varchar means Variable-length Character string.
Nvarchar will store Unicode characters.Both will be used all most for the same purpose but with little difference.
Varchar will store the 8-bit data in database where as Nvarchar will be stored as 16-bit data in Database.
In Sql server 2005

The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters.
This in turn limits the maximum size of a VARCHAR to 8,000 bytes.
Varchar (MAX) and Nvarchar (MAX). Varchar (MAX) can hold max of 2,147,483,648 characters and NVARCHAR (MAX) can hold 1,073,741,823 characters. We use Varchar instead of TEXT and NTEXT which cannot be used to passed as variables in a stored procedure where as Varchar (MAX) or Nvarchar (MAX) cannot have such restriction.

If you're in the process of migrating an existing data design for SQL Server 2005, it might make sense to migrate some TEXT / NTEXT fields to VARCHAR (MAX) / NVARCHAR (MAX) types when appropriate.

If you need Unicode support for a given data type, either now or soon enough, go with NVARCHAR. If you're sticking with 8-bit data for design or storage reasons, go with VARCHAR. Note that you can always migrate from VARCHAR to NVARCHAR at the cost of some room -- but you can't go the other way 'round. Also, because NVARCHAR involves fetching that much more data, it may prove to be slower depending on how many table pages must be retrieved for any given operation.

UNICODE can handle languages that are difficult to impossible with single-byte
character sets such as ASCII. If you must support many languages UNICODE is a very clean way to do it.

Create Table dynamically in sql server

I'd like to create a stored procedure that takes the name of table as a parameter, and then creates that table, if it doesn't exist, according to a schema stored somewhere.

Is that possible-- Can I store a schema and use is as a template to create tables from? Or must I hard-code the CREATE TABLE and its scheme in the stored procedure itself?

The idea here is to be able to change the schema without changing the stored procedure (separation of concerns), because I'm probably going to expand the procedure to do more.

This is as far as I got without knowing whether to just hard-code the schema for the table in the sproc, or whether I can store and pull that schema somehow.

@tableName as nvarchar(128)
IF OBJECT_ID(@tableName,'U') IS NULL
CREATE TABLE @tableName ????????

Find Current User Information

SELECT spid, uid=rtrim(loginame), Program_name=rtrim(Program_name),
dbname=db_name(dbid), status=rtrim(status) FROM master.dbo.sysprocesses
WHERE loginame = 'UserName';

You can also use sp_who command to see all users associated with current database.

Retrieve and Upload data From ExcelWorkbook

I got this link is very helpful when you want to upload data in bulk from the excel workbook

or you have to retrieve the data from the excel workbook.;en-us;316934#12

Difference between Web Services and Remoting?

Both Remoting and Web Services are ways of communication between applications.

Remoting - In remoting, the applications involved in the communication process may be located on the same computer, different computers in a same or different network. In remoting, both applications know about each other. A proxy of an application object is created on the other application.

Web Services - Communication between applications using web services is platform independent and programming independent. The application that consumes the web service, simply accesses it, without needing to know how this web service has actually been implemented & created.

Here are some of the major differences:
* ASP.NET Web Services may be accessed using HTTP only. Remoting objects may be accessed over any protocol like TCP, SMTP, HTTP
* Web Service are Stateless, whereas Remoting has support for both stateless and with-state environment, which is achieved using Singleton and Singlecall activation
* ASP.NET provides good support to create Web Services. They are easy to deploy. In comparison, Remoting is little complex.
* Web services may be considered very reliable, due to the fact that they are hosted on IIS. In remoting, if IIS is'nt used, then methods like plumbing have to be used to ensure the application reliability.
* In .NET, when we create an application that consumes a web service, the web service may or may not be built using .NET. But while implementing Remoting in .NET, both the applications must be built in .NET.
* Using web services, only a limited number of types may be serialized (XML). Using Remoting, objects like SOAP objects, Binary objects & XML Objects may be serialized.

Different Language class file in app_code

Question : Can we keep different language class file in app_code directory at the same time?Answer : Yes we can keep the different language class file in the App_Code directory but when we try to keep the different language file in the directory it raise an error like :
Error :
'App_Code/Class2.vb' and 'App_Code/Class1.cs' use a different language, which is not allowed since they need to be compiled together.
To resolve this problem, we keep the different language class file in the different folder and we have to set the codeSubDirectories in the web.config file under the compilation tag like this

<compilation debug="true">
<add directoryname="CsCode">
<add directoryname="VbCode">

Convert the Rows value into CSV format

From this query you can convert row value into comma separated valuse

CREATE TABLE #tblTblValues (id int)
insert into #tblTblValues values (10)
insert into #tblTblValues values (20)
insert into #tblTblValues values (30)
insert into #tblTblValues values (40)
insert into #tblTblValues values (50)
insert into #tblTblValues values (60)
insert into #tblTblValues values (70)

DECLARE @Value varchar(2000)
SELECT @Value = COALESCE(@Value + ', ', '') + CAST(id AS varchar) FROM #tblTblValues

10, 20, 30, 40, 50, 60, 70

Debug the Stored Procedure OR Functions in SQL?

Do you know how to debug the stored procedure OR functions in SQL?

Here the way you can debug you stored procedure and function.

Steps to debug the stored procedure/ function :

Step 1 : Create a web project/windows project according to your preference
Step 2 : Connect to your database server through server Explores (See below screenshot)
Step 3 : Expand your stored procedure/Function
Step 4 : open the procedure/ function and set breakpoint
Step 5 : Now Right click on the stored procedure / function you want to debug
Step 6 : Click on Step into stored procedure/ function
Step 7 : Set default parameter values

Now it will take to you break point.
See the screen shot below

Access Different interface method with same Name implemented in a class

We use interface and multiple interface inherit it into class, then we implement the methods of interface as it is necessary
but what will happen if two interface have the same mentods with same signature and inherited in the same class?
Now questions arises from here are :
Q1) Both the methods will be implementable which is with the same name and signature?
Q2) If methods are implementable then how it is possible?
Q3) If it is possible then can we access both the methods?
Q3) If it is possible then what is the way to access these methods publically?

The answer of all the above question is below:
1) Yes both the methods with same name and signature is implementable.
2) we have to implement interface explicitely preceding with iterface name.
3) Yes it is possible to access the methods.
4) Yes we can

Difference between an Index and a Primary Key

There seams to be some confusion between what a Primary Key is, and what an Index is and how they are used.

The Primary Key is a logical object. By that I mean that is simply defines a set of properties on one column or a set of columns to require that the columns which make up the primary key are unique and that none of them are null. Because they are unique and not null, these values (or value if your primary key is a single column) can then be used to identify a single row in the table every time. In most if not all database platforms the Primary Key will have an index created on it.

An index on the other hand doesn’t define uniqueness. An index is used to more quickly find rows in the table based on the values which are part of the index. When you create an index within the database, you are creating a physical object which is being saved to disk. Using a table which holds employees as an example:

CREATE TABLE dbo.Employee (
LastName VARCHAR(50),
FirstName VARCHAR(50),
DepartmentId INT,
TermReason INT

The EmployeeId is the Primary Key for our table as that is what we will use to uniquely identify an employee. If we were to search the table based on the last name the database would need to read the entire table from the disk into memory so that we can find the few employees that have the correct last name. Now if we create an index on the LastName column when we run the same query, the database only needs to load the index from the disk into memory, which will be much quicker, and instead of scanning through the entire table looking for matches, because the values in the index are already sorted the database engine can go to the correct location within the index and find the matching records very quickly.

SQL SERVER – Delete Duplicate Records – Rows

SQL SERVER – Delete Duplicate Records – Rows « Journey to SQL Authority with Pinal Dave: "Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

Difference between OSQL and Query Analyzer

Both are same for functioning but there is a little difference OSQL is command line tool which execute query and display the result same a Query Analyzer do but Query Analyzer is graphical.OSQL have not ability like Query Analyzer to analyze queries and show statistics on speed of execution .And other useful thing about OSQL is that its helps in scheduling which is done in Query Analyzer with the help of JOB.

Rules and Constraints in Sql Server

Rules and Constraints are similar in functionality but there is a An little diffrence between them.Rules are used for backward compatibility . One the most exclusive diffrence is that we an bind rules to a datatypes whereas constraints are bound only to columns.So we can create our own datatype with the help of Rules and get the input according to that.

Raiseerror in Sql server

Stored procedures report errors to client applications via the RAISERROR command. RAISERROR doesn’t change the flow of a procedure; it merely displays an error message, sets the @@ERROR automatic variable, and optionally writes the message to the SQL Server error log and the NT application event log.

Recursive Stored Procedure

Can a stored procedure call itself or recursive stored procedure? How many level SP nesting possible?

Yes. Because Transact-SQL supports recursion, you can write stored procedures that call themselves. Recursion can be defined as a method of problem solving wherein the solution is arrived at by repetitively applying it to subsets of the problem. A common application of recursive logic is to perform numeric computations that lend themselves to repetitive evaluation by the same processing steps. Stored procedures are nested when one stored procedure calls another or executes managed code by referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code references up to 32 levels.

What is SQL server agent

SQL Server agent plays an important role in the day-to-day tasks of a database administrator (DBA). It is often overlooked as one of the main tools for SQL Server management. Its purpose is to ease the implementation of tasks for the DBA, with its full-function scheduling engine, which allows you to schedule your own jobs and scripts.

Find Sql Server version & Operation System

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel')

User defined functions

User-Defined Functions allow to define its own T-SQL functions that can accept 0 or more parameters and return a single scalar data value or a table data type.

What kind of User-Defined Functions can be created?
There are three types of User-Defined functions in SQL Server 2000 and they are Scalar, Inline Table-Valued and Multi-statement Table-valued.

Scalar User-Defined Function :
A Scalar user-defined function returns one of the scalar data types. Text, ntext, image and timestamp data types are not supported. These are the type of user-defined functions that most developers are used to in other programming languages. You pass in 0 to many parameters and you get a return value.

Inline Table-Value User-Defined Function :
An Inline Table-Value user-defined function returns a table data type and is an exceptional alternative to a view as the user-defined function can pass parameters into a T-SQL select command and in essence provide us with a parameterized, non-updateable view of the underlying tables.

Multi-statement Table-Value User-Defined Function :
A Multi-Statement Table-Value user-defined function returns a table and is also an exceptional alternative to a view as the function can support multiple T-SQL statements to build the final result where the view is limited to a single SELECT statement. Also, the ability to pass parameters into a T-SQL select command or a group of them gives us the capability to in essence create a parameterized, non-updateable view of the data in the underlying tables. Within the create function command you must define the table structure that is being returned. After creating this type of user-defined function, It can be used in the FROM clause of a T-SQL command unlike the behavior found when using a stored procedure which can also return record sets.

Sub Query in sql server

Sub-queries are often referred to as sub-selects, as they allow a SELECT statement to be executed arbitrarily within the body of another SQL statement. A sub-query is executed by enclosing it in a set of parentheses. Sub-queries are generally used to return a single row as an atomic value, though they may be used to compare values against multiple rows with the IN keyword.

A subquery is a SELECT statement that is nested within another T-SQL statement. A subquery SELECT statement if executed independently of the T-SQL statement, in which it is nested, will return a result set. Meaning a subquery SELECT statement can standalone and is not depended on the statement in which it is nested. A subquery SELECT statement can return any number of values, and can be found in, the column list of a SELECT statement, a FROM, GROUP BY, HAVING, and/or ORDER BY clauses of a T-SQL statement. A Subquery can also be used as a parameter to a function call. Basically a subquery can be used anywhere an expression can be used.

Properties of Sub-Query :
A subquery must be enclosed in the parenthesis.
A subquery must be put in the right hand of the comparison operator, and
A subquery cannot contain a ORDER-BY clause.
A query can contain more than one sub-queries.

What are types of sub-queries?
Single-row subquery, where the subquery returns only one row.
Multiple-row subquery, where the subquery returns multiple rows,.and
Multiple column subquery, where the subquery returns multiple columns.

Difference between a HAVING CLAUSE and a WHERE CLAUSE

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. HAVING criteria is applied after the the grouping of rows has occurred.


This command is basically used when a large processing of data has occurred. If a large amount of deletions any modification or Bulk Copy into the tables has occurred, it has to update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly.

Difference between DELETE & TRUNCATE commands?

Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

TRUNCATE is faster and uses fewer system and transaction log resources than DELETE.
TRUNCATE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log.
TRUNCATE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint.
Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE can not be Rolled back using logs.
TRUNCATE is DDL Command.
TRUNCATE Resets identity of the table.

DELETE removes rows one at a time and records an entry in the transaction log for each deleted row.
If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.
DELETE Can be used with or without a WHERE clause
DELETE Activates Triggers.
DELETE Can be Rolled back using logs.
DELETE is DML Command.
DELETE does not reset identity of the table.

What is Collation?

Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width.

Different type of Collation Sensitivity?

Case sensitivity
A and a, B and b, etc.

Accent sensitivity
a and á, o and ó, etc.

Kana Sensitivity
When Japanese kana characters Hiragana and Katakana are treated differently, it is called Kana sensitive.

Width sensitivity
When a single-byte character (half-width) and the same character when represented as a double-byte character (full-width) are treated differently then it is width sensitive.

What is a Linked Server?

Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. With a linked server, you can create very clean, easy to follow, SQL statements that allow remote data to be retrieved, joined and combined with local data.

Storped Procedure sp_addlinkedserver, sp_addlinkedsrvlogin will be used add new Linked Server.

What is the use of DBCC commands?

DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks.
E.g. DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.

DBCC CHECKALLOC - To check that all pages in a db are correctly allocated.
DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

What is View?

A simple view can be thought of as a subset of a table. It can be used for retrieving data, as well as updating or deleting rows. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database. The data accessed through a view is actually constructed using standard T-SQL select command and can come from one to many different base tables or even other views.

What is Trigger?

A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs. Triggers are stored in and managed by the DBMS.Triggers are used to maintain the referential integrity of data by changing the data in a systematic fashion. A trigger cannot be called or executed; the DBMS automatically fires the trigger as a result of a data modification to the associated table. Triggers can be viewed as similar to stored procedures in that both consist of procedural logic that is stored at the database level. Stored procedures, however, are not event-drive and are not attached to a specific table as triggers are. Stored procedures are explicitly executed by invoking a CALL to the procedure while triggers are implicitly executed. In addition, triggers can also execute stored procedures.
Nested Trigger: A trigger can also contain INSERT, UPDATE and DELETE logic within itself, so when the trigger is fired because of data modification it can also cause another data modification, thereby firing another trigger. A trigger that contains data modification logic within itself is called a nested trigger.

What is Stored Procedure?

A stored procedure is a named group of SQL statements that have been previously created and stored in the server database. Stored procedures accept input parameters so that a single procedure can be used over the network by several clients using different input data. And when the procedure is modified, all clients automatically get the new version. Stored procedures reduce network traffic and improve performance. Stored procedures can be used to help ensure the integrity of the database.
e.g. sp_helpdb, sp_renamedb, sp_depends etc.

What is normalization?

Database normalization is a data design and organization process applied to data structures based on rules that help build relational databases. In relational database design, the process of organizing data to minimize redundancy. Normalization usually involves dividing a database into two or more tables and defining relationships between the tables. The objective is to isolate data so that additions, deletions, and modifications of a field can be made in just one table and then propagated through the rest of the database via the defined relationships.

What is RDBMS?

Relational Data Base Management Systems (RDBMS) are database management systems that maintain data records and indices in tables. Relationships may be created and maintained across and among the data and tables. In a relational database, relationships between data items are expressed by means of tables. Interdependencies among these tables are expressed by data values rather than by pointers. This allows a high degree of data independence. An RDBMS has the capability to recombine the data items from different files, providing powerful tools for data usage.

Index in Sql server

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.

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.

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

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'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 key creates a nonclustered index by default.
Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

List all tabels in database


2. SELECT name FROM dbo.sysobjects WHERE xtype = 'U'

Find duplicate columns in a Table

Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

DELETE FROM MyTable WHERE ID NOT IN ( SELECT MAX(ID) FROM MyTable GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

It could be explosive, see chart inside!

Looks like S_M_A A is severing through short sellers at the .09 spot and is
adjusted to lift off past 0.15 this next few days! Let's bulldoze these short
sellers off the barrier and we should all secure a great ROI on S_M_A A!

Trade Date: Wed, October 10
OTCBB: SMA Alliance
Ticker Symbol: S_M_A A
Latest Price: 0.12
Target Price: $.20

Yesterday S_M_A A divulged notice of a satellite office in Florida as well as
a contract with Lexus (BMW and Mercedes coming in Q4) to probably use
trademarked S_M_A A software at their dealers all over the continent!

How to configure xp_cmdshell

There are a lot of situations when we have to send the Emails from Sql Server.
But before sending Emails from Sql Server, we have to Enable this feature because by default this feature is disbled.

To enable this feature we have to fire the below command.

sp_configure 'xp_cmdshell', '1'

After executing this command you will see the following message.

"Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install."

Now we have to Run the following query.


Press F5 to run this command.
After executing this command you will see the following message.

"Command(s) completed successfully."

Now your SQl Server database is ready to send Emails.

Anuj Rathi