Skip to main content

Posts

Showing posts from 2009

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

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

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.

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

To get current user run following script in Query Editor SELECT SYSTEM_USER 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: SELECT SUSER_SNAME()

Find Tables With Foreign Key Constraint in Database

SELECT K_Table = FK.TABLE_NAME, FK_Column = CU.COLUMN_NAME, PK_Table = PK.TABLE_NAME, PK_Column = PT.COLUMN_NAME, Constraint_Name = C.CONSTRAINT_NAME FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME INNER JOIN ( SELECT i1.TABLE_NAME, i2.COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1 INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY' ) PT ON PT.TABLE_NAME = PK.TABLE_NAME ---- optional: ORDER BY 1,2,3,4 WHERE PK.TABLE_NAME='something' WHERE FK.TABLE_NAME='something' WHERE PK.TABLE_NAME IN ('one_thing', 'another') WHERE FK.TABLE_NAME IN ('one_thing', 'another')

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

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. CREATE PROCEDURE GenerateTable @tableName as nvarchar(128) AS BEGIN IF OBJECT_ID(@tableName,'U') IS NULL CREATE TABLE @tableName ???????? ENDIF END GO

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.

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

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"> <codesubdirectories> <add directoryname="CsCode"> <add directoryname="VbCode"> </codesubdirectories> </compilation>

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 SELECT @Value OutPut 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 ( EmployeeId INT PRIMARY KEY, LastName VARCHAR(50), FirstNa...

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.

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

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

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.

UPDATE_STATISTICS command

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 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 DELETE removes rows one at a time and records an...

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

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

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.

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.

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. RECONFIGURE 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. Regards, Anuj Rathi