You are on page 1of 33

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

1. Difference B/W OLEDB and ODBC connection ? Ans. ODBC is Open Data Base Connectivity, which is a connection method to data sources and other things. It requires that you set up a data source, or what's called a DSN using an SQL driver or other driver if connecting to other database types. Most database systems support ODBC. ODBC-it is designed for connecting to relational databases. However, OLE DB can access relational databases as well as nonrelational databases . There is data in your mail servers, directory services, spreadsheets, and text files. OLE DB allows SQL Server to link to these nonrelational database systems. For instance, if you want to query, through SQL Server, the Active Directory on the domain controller, you couldn't do this with ODBC, because it's not a relational database. However, you could use an OLE DB provider to accomplish that. 2. Difference B/W DBMS and RDBMS ? Ans: DBMS: 1)In dbms no relationship concept mean relationship is between two files. 2)It supports Single User only mean only one user can access data at a time. 3)It treats Data as Files internally 4)It supports 3 rules of E.F.CODD out off 12 rules 5)It requires low Software and Hardware Requirements. 6)FoxPro, IMS are Examples 7) DBMS does not support client/server Architecture RDBMS: 1)It is used to establish the relationship concept between two database objects, i.e, tables 2)It supports multiple users mean multi user can access data simultaneously. 3)It treats data as Tables internally 4)It supports minimum 6 rules of E.F.CODD 5)It requires High software and hardware requirements. 6)SQL-Server, Oracle are examples. 7) RDBMS supports client/server Architecture. 3. CODD 12 rules ? Ans : Rule 0: The system must qualify as relational, as a database, and as a management system. For a system to qualify as a relational database management system (RDBMS), that system must use its relational facilities (exclusively) to manage the database. Rule 1: The information rule: All information in the database is to be represented in one and only one way, namely by values in column positions within rows of tables. Rule 2: The guaranteed access rule: All data must be accessible. This rule is essentially a restatement of the fundamental requirement for primary keys. It says that every individual scalar value in the database must be logically addressable by specifying the name of the containing table, the name of the containing column and the primary key value of the containing row.

Coding, A Rhythmic Literary Job


Rule 3: Systematic treatment of null values:

http://www.dotnet-tricks.com

The DBMS must allow each field to remain null (or empty). Specifically, it must support a representation of "missing information and inapplicable information" that is systematic, distinct from all regular values (for example, "distinct from zero or any other number", in the case of numeric values), and independent of data type. It is also implied that such representations must be manipulated by the DBMS in a systematic way. Rule 4: Active online catalog based on the relational model: The system must support an online, inline, relational catalog that is accessible to authorized users by means of their regular query language. That is, users must be able to access the database's structure (catalog) using the same query language that they use to access the database's data. Rule 5: The comprehensive data sublanguage rule: The system must support at least one relational language that 1. Has a linear syntax 2. Can be used both interactively and within application programs, 3. Supports data definition operations (including view definitions), data manipulation operations (update as well as retrieval), security and integrity constraints, and transaction management operations (begin, commit, and rollback). Rule 6: The view updating rule: All views that are theoretically updatable must be updatable by the system. Rule 7: High-level insert, update, and delete: The system must support set-at-a-time insert, update, and delete operators. This means that data can be retrieved from a relational database in sets constructed of data from multiple rows and/or multiple tables. This rule states that insert, update, and delete operations should be supported for any retrievable set rather than just for a single row in a single table. Rule 8: Physical data independence: Changes to the physical level (how the data is stored, whether in arrays or linked lists etc.) must not require a change to an application based on the structure. Rule 9: Logical data independence: Changes to the logical level (tables, columns, rows, and so on) must not require a change to an application based on the structure. Logical data independence is more difficult to achieve than physical data independence. Rule 10: Integrity independence: Integrity constraints must be specified separately from application programs and stored in the catalog. It must be possible to change such constraints as and when appropriate without unnecessarily affecting existing applications.

Coding, A Rhythmic Literary Job


Rule 11: Distribution independence:

http://www.dotnet-tricks.com

The distribution of portions of the database to various locations should be invisible to users of the database. Existing applications should continue to operate successfully : 1. when a distributed version of the DBMS is first introduced; and 2. when existing distributed data are redistributed around the system. Rule 12: The nonsubversion rule: If the system provides a low-level (record-at-a-time) interface, then that interface cannot be used to subvert the system, for example, bypassing a relational security or integrity constraint. 4. Difference between datareader and dataset? Ans : Data reader 1. It is a read only and forward only data. 2. U can access one table at time. 3. It can't persist the data. 4. It is comes under connected architecture. 5. One of the most advantage is it is much faster than data adapter Data set: 1. It is defined with multiple tables. 2. It can persist the data. 3. It is a relational data cache hosted in application domain during execution. 4. It is a disconnected architecture. 5. It can't defined with out data adapter. 5. Difference between datareader and datadapter? Ans. DataReader 1.Works in Connected Mode 2.Forward Only Read Only 3. we cant insert, update, delete data using data reader. 4. It is fast than dataadapter. 5. It cant persist data. 6. Additionally, it's not possible to sort, filter, or manipulate the data while using a DataReader, since it is read-only and forward-only DataAdapter

1. It is a bridge b/w dataset and database. 2. Works in Disconnected Mode. 3. Both Side Movements Read/Write

4. we can insert, update, delete data using dataAdapter.

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

6. What is the difference between GridView, DataList, ListView, Repeater, DetailsView, FormView? DataGrid : -1.We can edit data. -2.It is performance very slow compare to Repeater and DataList. -3.We can display the data either rowwise or columnwise, through Repeat Columns and repeat direction property -4.Better to use list reports with Select, SORT, EDIT , Update, Delete and Cancel option Repeater: (1) display database records. It cannot edit/insert records (2) entirely template driven DataList: (1) display database records(can edit?) (2) entirely template driven. DataList is very similar to Repeater except that DataList's default behavior is rending the content using a table. However, you can override the default behavior. GridView: (1) Display/edit/delete/Insert records in database (2)In built Sorting, paging ListView: (1) template driven (2) can add data to database (3) can edit, page through, sort database data (4) ListView is the only control implementing IPageableItemContainer interface, so it is the only one which can use DataPager control. ListView is the most flexible List control in all. I can safely use ListView in place of GridView. DetailsView: (1) Display/edit/delete/Insert records in database (2) Render a table for a single record. always render each field in a seperate table row. (3) use in combination with gridview or dropdownlist. FormView: Exactly like DetailsView except that FormView is entirely template driven. 7. What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0 Answer Ans: 1.In data grid insertion,pageing, updateing, deleteing are implementing by coding. 2.In Gridview automatically genaretes the insertion, pageing ,updateing deleting without user writing the code. 3.In data grid no image templete column whereas Gridview have image templete column. However, some of these pitfalls of the DataGrid control have been addressed with ASP.NET 2.0 and after. 8. Diffrenec between datalist and repeater ? Ans. We can consider a combination of repeater and datgrid. Hence we can edit data in it. It doesnot have paging and sorting capability.

Coding, A Rhythmic Literary Job


9. . Diffrenec between dataview and dataset ? Ans ADO.NET DataSet:

http://www.dotnet-tricks.com

It is XML-based. It is an in-memory cache of data that is not backed by a file or data storeit is disconnected. It is independent of a data store and cannot communicate with one by itself. It can store data in multiple tables from multiple data stores that can be related through foreign key relationships. It stores multiple versions of the data for each column and for each row in each table. It can be serialized with full fidelity to XML for transport between tiers of a distributed application even when those tiers reside on separate physical machines. a DataSet can be populated by a data adapter by calling the data adapter's Fill method.

DataView : DataView object is a view of a particular DataTable within a DataSet that can expose the data in a particular sort order or can filter the data. It doesn't create copies of the rows, but is dynamic in that all changes to the underlying DataTable are immediately reflected in the DataView. A DataView is different from a relational database view in several respects. First, a DataView always contains the entire set of columns present in the DataTable it references, whereas a relational view is often used to expose a subset of the columns from a table or to add additional computed and aggregated columns. Second, a DataView always refers to a single DataTable and therefore can't be used to display data from multiple tables as is frequently done in a relational view. You can create a new DataView from an existing DataTable by passing a DataTable to the DataView's constructor like this: dvwDataView = New DataView( dtblDataTable ) Alternatively, you can create a new DataView by calling the DefaultView() method of the DataTable class like this:

dvwDataView = dtblDataTable.DefaultView() Which method you use to create a DataView is entirely a matter of preference

ADVANCED NOTE : Technically, you can bind only a DataView, not a DataSet or DataTable, to a control. Thestatement

Coding, A Rhythmic Literary Job


dgrdDataGrid.DataSource = dstDataSet is actually shorthand for

http://www.dotnet-tricks.com

dgrdDataGrid.DataSource = dstDataSet.Tables( 0 ).DefaultView() There is no disadvantage to using the shorthand syntax; it works just as well. View (Dara relation view) : A view ia a logical representation of another table or combination of tables. A view derives its data from the tables on which it is based. These tables are called base tables. Base tables might in turn be actual tables or might be views themselves. All operations performed on a view actually affect the base table of the view. You can use views in almost the same way as tables.You can query, update,insert into and delete from views, just as you can standard tables. Views can provide a different representation of the data that resides within other tables and views. Views are very powerful because they allow you to tailor the presentation of data to different types of users. > A view is a database object > It is a virtual table whose contents are taken from other tables through the execution of a query.The changes in the table are automitacally reflected in the view. > A view is created witha the CREATE VIEW command > A view is queried just like querying a table. > A user cannot distinguish between a table and a view > Any updation of rows in tha table will automatically reflected in the view > As a VIEW does not store any data the redundancyproblem does not araise. > Critical data in the base table is safeguarded as access to such data can be controlled using VIEW EX. CREATE VIEW dbo.emp_view as SELECT ename,empno,deptno from empUnderstanding NULL Be sure not to see NULL as equivalent to 0 (in numerical columns), or an empty string (in the case of string columns). Both 0 and an empty string are values; NULL defines the lack of a value Advantage of view .: 1. Provide security. When you don't want a user to see all of the data in a table, you can use a view to let the user see only specific columns. Thus, someone working in the personnel department can see the employee name and address information through a view, while the salary or hourly pay can remain hidden by being excluded from the view 2. . Simplify data structures. You can present the database as a "personalized" set of tables. Suppose, for example, that you have separate employee and payroll tables. You can use a view to display employee names and pay figures in a single virtual table for the company's managers.

3. Views are commonly used to: 1. Filter rows from the table. 2. Protect sensitive data from unwanted users. 3. Decrease database complexity. 4. Abstract various physical databases into a single logical database.

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

Notes: 1. Views cannot be indexed 2. Defaults, rules and triggers cannot be associated with views. 3. The query defining the view cannot include Order by, Compute or compute by or into keyword. Distributed Partitioned Views: Partitioned views can be used to distribute database processing across a group of servers.

NULL and Default Values Ive often heard people say that when we set a default value for a column, it doesnt matter whether or not we set it to accept NULLs. Many people seem to believe that columns with default values wont store NULL.Thats incorrect. You can modify a record after it was created, and change any field that will allow it to NULL. Your columns ability to store NULL is important for the integrity of your data, and it should reflect the purpose of that data. A default value does make things easier when we create new rows, but its not as vital as is correctly allowing (or disallowing) NULL in columns. Primary Keys and the IDENTITY Property Using the IDENTITY property for a column doesnt mean we can avoid specifying a primary key. Its true that the IDENTITY property always generates unique values, but it doesnt necessarily enforce them. For example, say we have a table with a number of columns, one of which has the IDENTITY property set. This table contains three records that are likely to contain the automatically generated values 1, 2, and 3 in the IDENTITY column. Provided the INDENTITY_INSERT property for this table is enabled (by default its disabled, but its quite easy to enable), its quite simple to insert another record with the value 2. The IDENTITY column will continue to generate unique values (4, 5, 6, and so on), but it doesnt guarantee the column remains unique. Foreign Key : Unlike primary key columns, a foreign key column can contain NULL, and almost always contains repeating values.

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

Q10.Can a single DataSet be populated using both a data adapter and explicit code? Yes. Different tables in a DataSet can be populated in different ways. For example, one table could be populated from a data adapter connected to SQL Server, another to a data adapter connected to Oracle, and a third through explicit code that creates new rows manually. This feature is what allows the DataSet to store heterogeneous data. Q11.How do you combine the contents of two DataSet objects? You can combine the data in multiple DataSet objects using the Merge method of the DataSet object that will act as the final repository. Keep in mind that errors might result if the schema of the tables differs or if constraints are violated, and that changes in the original DataSet will be overridden by default. If the two DataSet objects contain different tables, they can simply be merged into a single DataSet that contains both tables.

Q12.How does a data adapter know which rows have changes? A data adapter, or for that matter your code, can inspect the RowState property of the DataRow object to determine the current state of the row. Row states include Added, Deleted, Modified, and Unchanged. Q13.What is the relationship between row states, row versions, and a DataView? A DataView, through its RowStateFilter property, can be used to view a collection of rows from a DataTable that have a particular combination of RowState and version. For example, the RowFilter can be set to the ModifiedOriginal value from the DataRowViewState

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

enumeration to show the Original values from rows with a row state of Modified. The DataView can then be bound to a control for display. What are the types of SQL Statement? 1. Data Definition Language :CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT 2. Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT 3. Transactional Control : COMMIT & ROLLBACK 4. Session Control: ALTERSESSION & SET ROLE System Control ALTER SYSTEM What Is Connection Pooling? In brief, connection pooling allows applications to reuse an existing database connection from a pool of already established connections, instead of having to repeatedly re-establish new connections to that same database. Establishing database connections is fairly expensive if you compare that aspect to the overall work that will be handled with a database connection in the first place. Each .NET data provider, such as the SQL Server .NET data provider and the OLE DB .NET data provider, has a connection-pooling capability embedded in it.

Types of joins in Sql ?


We have three types of Joins in sql. They are 1. Inner join 2. Outer join 3. Cross join 1. Inner join: Inner join is the default type of join, it will producesses the result set, which contains matched rows only. Syntax: select * from table1<innerjoin>table2 Here noneed of specifying innerjoin. Simply we can specify Join also. Syntax: select * from table1<join>table2 2. Outer join: Outer join produces the results, which contains matched rows and unmatched rows. Outer join is further classified as three types.They are 1.left outer join 2.right outer join 3.full outer join. a.Left outer join: Left outer join producesses the results, which contains all the rows from left table and matched rows from right table. Syntax: select * from table1<leftouterjoin>table2

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

b.Right outer join: Right outer join producesses the resultset, which contains all the rows from right table and matched rows from left table. Syntax:select * from table1<right outer join>table2 c.Full outer join: Full outer join producesses the resultset, which contains all the rows from left table and all the rows from right table. Syntax:select * from table1<fullouterjoin>table2 3.Cross join: A join without having any condition is known as cross join, in cross join every row in first table is joins with every row in second table. Cross join is nothing but cortizion product. Syntax: select * from table1<cross join>table2 Self join: A join joins withitself is called self join working with self joins we use alias tables.

What Stored Procedure means ?


A Stored procedure is a database object that contains one or more SQL statements. We can retrieve, insert, update, delete data using stored procedure. They are complied and stored on the database sever. You can even call a stored procedure from within itself. This technique is called a recursive call in programming. To execute a stored procedure you can use EXEC statement. CREATE PROC spGetShashi AS SELECT * FROM SHASHI Advantage of stored procedures : 1. Manage, control and validate data 2.Large queries can be avoided 3. Reduces network traffic since they need not be recompiled. What is Trigger? A trigger is a Database object just like a stored procedure or we can say it is a special kind of Stored procedure which fires after (/before) a specified language event executes. More specifically, it is for the object which is attached to a Table or View or Database schemas for tracking the operations on them. The main difference between a trigger and a stored procedure is that the former is attached to a table or view and is fired only when an INSERT, UPDATE, and/or DELETE occurs, while a stored procedure executes at any time when it is called. Types of Triggers There are some added types in SQL Server 2005 for triggering actions: 1. DML Triggers AFTER Triggers

Coding, A Rhythmic Literary Job


2. 3. INSTEAD OF Triggers

http://www.dotnet-tricks.com

DDL Triggers CLR Triggers

DML Triggers These triggers are fired when a Data Manipulation Language (DML) event takes place. These are attached to a Table or View and are fired only when an INSERT, UPDATE and/or DELETE event occurs. The trigger and the statement that fires it are treated as a single transaction. Using this we can cascade changes in related tables, can do check operations for satisfying some rules and can get noticed through firing Mails. We can even execute multiple triggering actions by creating multiple Triggers of same action type on a table. We have to specify the modification action(s) at the Table level that fires the trigger when it is created. AFTER Triggers As the name specifies, AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. This is the only option available in earlier versions on Microsoft SQL Server. AFTER triggers can be specified on tables only. Here is a sample trigger creation statement on the Users table. Listing 1 (AFTER Trigger example) ------ Creating a DML trigger in T-SQL ------SET NOCOUNT ON CREATE TABLE UserTable (User_ID int IDENTITY, User_Name varchar(30), Type varchar(10)) go CREATE TRIGGER tr_User_INSERT ON UserTable FOR INSERT AS PRINT GETDATE() Go INSERT UserTable (User_Name, Type) VALUES ('James', 'ADMIN') ------ Result --------------Apr 30 2007 7:04AM INSTEAD OF Triggers INSTEAD OF triggers are executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates a view can support. DDL Triggers DDL triggers are new to SQL Server 2005. This type of triggers, like regular triggers, fire stored procedures in response to an event. They fire in response to a variety of Data Definition Language (DDL) events. These events are specified by the T-SQL statements that are start with the keywords CREATE, ALTER, and DROP. Certain stored procedures that perform DDL-like

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

operations can also fire this. These are used for administrative tasks like auditing and regulating database operations. CLR Triggers A CLR triggers can be any of the above, e.g. can be a DDL or DML one or can also be an AFTER or INSTEAD OF trigger. Here we need to execute one or more methods written in managed codes that are members of an assembly created in the .Net framework. Again, that assembly must be deployed in SQL Server 2005 using CREATE assembly statement. The Microsoft.SqlServer.Server Namespace contains the required classes and enumerations for this objective. Steps for Creating CLR Trigger The following are required steps for creating a CLR-Trigger of DML (After trigger) type for Insert action. This database Object is executed as the result of a user action against a table i.e. for an INSERT statement. Creating a .NET class of triggering action Making assembly(.DLL) from that Class Enabling CLR environment in that database. Registering the assembly in SQL Server Creating CLR Trigger using that assembly

1. Creating a .NET class Here we can use any managed language that is supported by .Net Framework such as C++, C#, VB, J#, JScript or XAML, etc. As I am with VB, this managed code is in Visual Basic. Let us discuss the objective of this entity. According to the above example of "tr_User_INSERT" trigger, we have the UserTable for holding the user details. There is a field "Type" which explains the user role (ADMIN, End User, Register User etc.). Our objective is to check the role of the inserted User for ADMIN type and then do the action as we set. Open the notepad, copy the following codes and save it as MyFirstAssembly.vb. Listing 2 (.NET Class of Trigger type) Imports System.Data Imports System.Data.SqlClient Imports Microsoft.SqlServer.Server Partial Public Class MyFirstClrTrigger <Microsoft.SqlServer.Server.SqlTrigger(Name = "checkUserRole", Target = "UserTable", Event = "FOR INSERT")> _ Public Shared Sub checkUserRole() Dim triggContext As SqlTriggerContext = SqlContext.TriggerContext()

Coding, A Rhythmic Literary Job


Dim userType As String = String.Empty

http://www.dotnet-tricks.com

If triggContext.TriggerAction = TriggerAction.Insert Then Using connection As New SqlConnection("context connection=true") connection.Open() Dim sqlComm As New SqlCommand Dim sqlPipe As SqlPipe = SqlContext.Pipe() sqlComm.Connection = connection sqlComm.CommandText = "SELECT Type from INSERTED" userType = sqlComm.ExecuteScalar.ToString() If userType.ToUpper = "ADMIN" Then sqlPipe.Send("Hello !!! You have the Admin role.") sqlPipe.Send("We can use e-mail codes here to inform.") End If End Using End If End Sub End Class Let us go into the codes. There are two major Namespaces used, System.Data.SqlClient and Microsoft.SqlServer.Server. Microsoft.SqlServer.Server provides the SqlTriggerAttribute Class, which is used to mark a method definition in an assembly as a trigger in SQL Server. The Sqltrigger attribute requires some parameters to set the created trigger properties, such as Name - the name of the Trigger, Target - the table or view to which the trigger applies (in case of DML type) and Event - the event to fire the trigger for (e.g. FOR INSERT, DELETE and/or UPDATE or INSTEAD OF etc.). Again, that method must be a Static (Shared in VB) one; here checkUserRole() is the target method. The SqlTriggerContext class provides the required triggering properties of the Trigger for doing action. TriggerAction property of this Class is the global enumeration TriggerAction type of Microsoft.SqlServer.Server namespace which indicates what action fired the Trigger. Here we use the INSERTED table, which is automatically created and managed by SQL Server 2005. This is used to set the conditions of DML trigger action. There is also another called DELETED, used in case of delete action. The CLR triggers can access the Inserted or Deleted tables through SqlCommand object using context connection. 2. Making assembly (.DLL) Now we have created the MyFirstAssembly.vb file with MyFirstClrTrigger class, so we need to compile the class to create an assembly. Here I use the VB compiler "vbc.exe," found in .Net Framework library. Use the following DOS command for creating assembly. Listing 3 (compile the .VB file) C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>vbc /t:library /out:F:\CLR_Trigger_Test\CLR_Assembly\MyFirstAssembly F:\CLR_Trigger_Test\MyFirstClrTrigger.vb

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

This command creates a DLL called MyFirstAssembly.dll at out path F:\CLR_Trigger_Test\CLR_Assembly\. 3. Enabling CLR environment By default, the CLR functionality is trued off in SQL Server; so we need to enable it. Use the following T-SQL codes to enable the CLR functionality. Listing 4 (enable CLR action) ------ Enabling CLR action in database ------sp_configure 'clr enabled', 1 Go RECONFIGURE with Override Go 4. Registering the assembly Our next step is to create an assembly in the Database, based on the compiled DLL (MyFirstAssembly.dll). The following T-SQL codes are useful regarding this objective. Listing 5 (registering assembly) ------ Registering an Assembly ------Create Assembly UserAssembly From 'F:\CLR_Trigger_Test\CLR_Assembly\MyFirstAssembly.dll' With Permission_Set=Safe Go 5. Creating CLR Trigger Now we will create an extended Trigger using CREATE Trigger statement of T-SQL. There is a new clause named EXTERNAL NAME in SQL Server 2005, which allows us to reference a method of the Registered assembly. By doing so we set the triggering action of our Trigger using that managed code method of the assembly. Listing 6 (creating a Trigger) ------ Creating a DML trigger in CLR ------Create Trigger tr_User_CheckRole on UserTable For INSERT AS External Name UserAssembly.MyFirstClrTrigger.checkUserRole Go Here we use the checkUserRole() shared method of our MyFirstClrTrigger class of the registered assembly UserAssembly. Checking the triggering action Finally, we need to check our Trigger. Let us test the trigger using the same INSERT Statement that we used before.

Coding, A Rhythmic Literary Job


Listing 7 (Insert into UserTable)

http://www.dotnet-tricks.com

----- Checking the DB objects.---------------INSERT UserTable (User_Name, Type) VALUES ('James', 'ADMIN') Go ----- Output Message ----May 2 2007 8:54AM Hello !!! You have the Admin role. We can use e-mail codes here to inform. The output is the result of two triggering actions; one is of T-SQL type and another one is of CLR type. Both are attached to the UserTable for the same type of action (i.e. after Insert statement). The following image is the output result window of SQL Server Management studio. Figure 1: (Output result window)

Difference Between StoredProcedure and UserDefinedFunctions 1. Procedure can return 0 or n values whereas functions can return a single value which is mandatory.

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

2. Procedure can have input and output parameter whereas functions can have only input type of parameters. 3.Procedure can be used for select command as well as for DML commands(Insert,Delete,Update) and DDL Commands (Create,Drop) while functions can be used for only select commands. 4. Functions can be called from Procedure while Procedure can not be called from Functions. 5 . Exceptions can be handled by try-catch block in Procedure whereas try-catch block can not be used in functions. 6 .We can go for transaction management in procedure whereas we can't go in function. 7. Functions are normally used for computations where as procedures are normally used for executing business logic. 8. Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values 9.Stored procedure is precompiled execution plan where as functions are not. 10. A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller. 11.You can call stored procedure directly from other programing language (like dot net) but Functions have to be used in Query's 12.We can write commit statements in procedures but can not write in Functions. Difference between delete and truncate command TRUNCATE 1. We can not use WHERE Condition in the TRUNCATE statement. 2. 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. 3. 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. 4. TRUNCATE can not be Rolled back. 5. TRUNCATE is DDL Command. 6. TRUNCATE Resets identity of the table. 7. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the de-allocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. 8. TRUNCATE does not allow filtered deletion. It commits after deleting the entire table i.e., can not be rolled back. Database triggers do not fire on TRUNCATE. DELETE 1. DELETE Can be used with or without a WHERE clause 2. DELETE Activates Triggers. 3. DELETE Can be Rolled back. 4. DELETE is DML Command. 5. DELETE does not reset identity of the table. 6.DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. 7.DELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE. If you want to remove table definition and its data, use the DROP TABLE statement.

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

Difference Between Drop, Truncate and Delete Command ? DROP : Drops the table records and structure from the DB schema. Nothing else is leftout. Can't rollback. Truncate: Clears the records from the table but the table structure still remains. Can't roll back. Clears all records from the table because we can not use where clause in truncate command.It is fast because it delete all rows at a time not onr by one.and will make only one entry in log file for deleting all the row, THAT ALSO WE CAN ROLL BACK. it will reset Identity value of the identity column Delete: deletes the rows based on the query or will delete all the rows if no "where" clause is given. Can roll back i.e deleted records can restored. it will not reset identity value of identity column.This operation is slow as compared to drop and truncate command because it makes a entry for every deleted row into the transaction log file and all deleted records can be rolled back after deletion. in delete it will make one entry for each row to be deleted. while truncate will make only one entry for all the rows. in delete it will free all the datapages by deleting the contents of the data pages. while in truncate it will delete the pointer to those datapages for all deleted rows What is the Subquery? Subquery is a query whose return values are used in filtering conditions of the main query. 6. What is correlated sub-query? Correlated subquery is a subquery which has reference to the main query. A correlated subquery is a nested select that refers to a column from the outer select. In some cases they can rank among the poorest performing SQL statements imaginable because the inner result set must be constructed for every single row that is a candidate for inclusion in the outer result set. If both the inner and outer result sets are large the amount of processing required can be huge. 7. Explain Connect by Prior? Retrieving rows in hierarchical order. Example: select empno, ename from emp; Explain UNION, MINUS, UNION ALL, INTERSECT? Each SQL statement within the query for Intersect, Minus, Union, Union ALL must have the same number of fields in the result sets with similar data types. UNION : The UNION query allows you to combine the result sets of 2 or more "select" queries. It removes duplicate rows between the various "select" statements. UNION ALL : The UNION ALL query allows you to combine the result sets of 2 or more "select" queries. It returns all rows (even if the row exists in more than one of the "select" statements). INTERSECT : The INTERSECT query allows you to return the results of 2 or more "select" queries. However, it only returns the rows selected by all queries. If a record exists in one query and not in the other, it will be omitted from the INTERSECT

Coding, A Rhythmic Literary Job


results. MINUS : The MINUS query returns all rows in the first query that are not returned in the second query.

http://www.dotnet-tricks.com

What is a database Link? Database Link is a named path through which a remote database can be accessed. An object stored in the local database that identifies a remote database, a communication path to the remote database, and optionally, a username and password for it. Once defined, a database link can be used to perform queries on tables in the remote database 10. What are the advantages of VIEW? 1) To protect some of the columns of a table from other users. 2) To hide complexity of a query. 3) To hide complexity of calculations. 11. Can a view be updated/inserted/deleted? If Yes under what conditions? A View can be updated/deleted/inserted if it has only one base table. If the view is based on columns from one or more tables then insert, update and delete is not possible. 12. What are Triggers? Triggers allow us to execute a batch of SQL code when an insert, update or delete command is executed against a specific table. Triggers are "attached" to a single table and allow us to setup our database in such a way that whenever a record is added, updated, or deleted from a table, then SQL server will automatically execute a batch of SQL code after that table modification takes place. Syntax: CREATE TRIGGER trigger_name ON { table | view } [ WITH ENCRYPTION ] { { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS [ { IF UPDATE ( column ) [ { AND | OR } UPDATE ( column ) ] [ ...n ] | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask ) { comparison_operator } column_bitmask [ ...n ] }] sql_statement [ ...n ] } } FOR INSERT: When SQL server processes this "INSERT" command, it creates a new virtual table, which contains all of the fields in the "INSERT" command. This table is named "Inserted", and is passed to the actual trigger. The table is named "Inserted" because it contains all of the newly added fields and values from our "INSERT" command. FOR DELETE: If we created a trigger that was activated when we deleted a record from the "authors table (using the "FOR DELETE" syntax), then the virtual table would contain all of the fields and values from the deleted record(s), and would be

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

named "Deleted". FOR UPDATE: Likewise, if we created a trigger for when an authors details were updated (using the "FOR UPDATE" syntax), then both the "Inserted" and "Deleted" virtual tables would be created and available from within the trigger. The "Deleted" table would contain all of the fields and values for the row(s) before they were updated, and the "Inserted" table would contain the new row(s) with the updated fields and values. When dealing with triggers, you must understand how they actually operate on the data contained within their virtual tables. Lets say that we run an "UPDATE" command on the "authors" table, which has a trigger attached to it. The "UPDATE" command might affect more than one row. When this is the case, the "UPDATE" trigger is called for each row that was affected by the update command. So, at any one time, each trigger only deals with one row. 13. Instead of Triggers: In previous versions of SQL Server, triggers were sections of code that were attached to tables and executed automatically after pre-defined updates took place on a specified table. These of course still exist in SQL Server 2000. Instead of triggers are attached to a table in a similar way, but the code inside them is executed in place of the original updating statement. Take this simple example: create table test1 (descr varchar(32)) go insert test1 select 'Quick demo of' union select 'instead of triggers' | go create trigger tr_test1_io on test1 instead of update as BEGIN select descr as 'Inserted Columns' from inserted select descr as 'Deleted Columns' from deleted select descr as 'Table test1' from test1 END -- trigger def go update test1 set descr = NULL go drop table test1 Note that the trigger still has access to the Inserted and Deleted tables, which work in the same way as old-style triggers. What is different is the contents the test1 table as displayed from within the trigger: For old-style triggers the contents of the test1 table would more closely match the contents of the Inserted table because the trigger fires after the update, but here the data selected from test1 is unchanged because no update is actually taking place (remember--the trigger happens instead of the update) 14. Multiple Triggers You cannot create more than one "Instead Of" trigger on a table or view for each operation (Insert, Update or Delete) but you can have "(instead Of" triggers mixing with the old style of triggers. If you do, then the following rules apply. 1) The "Instead Of" triggers fire first 2) If there is no update to the original target table defined in the "Instead of" trigger, subsequent triggers on that table will not fire 3) If the "Instead Of" trigger does update the original target table, then other triggers defined on that table will fire as appropriate 4) If the "Instead Of" trigger converts the update operation type (for example

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

converting an Update into Delete and Insert operations) then the triggers that relate to the operation defined inside the "Instead of" trigger will fire. 15. Can you use a commit statement within a database trigger? Yes. I tried using commit and Rollback in Instead of Triggers and it worked fine. 16. What is a server Side SQL Cursor? Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. What is Index? 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 a check constraint? A check constraint allows you to specify a condition on each row in a table. Note: 1) Check constraint can NOT be defined on a VIEW. 2) The check constraint defined on a table must refer to only columns in that table. It can not refer to columns in other tables. 3) A check constraint can NOT include a SUBQUERY. 4) A check constraint can be defined in either a CREATE TABLE statement or an ALTER TABLE statement. The syntax for creating a check constraint using a CREATE TABLE statement is: CREATE TABLE table_name (column1 datatype null/not null, column2 datatype null/not null, ... CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]); The DISABLE keyword is optional. If you create a check constraint using the DISABLE keyword, the constraint will be created, but the condition will not be enforced. Example: CREATE TABLE suppliers (supplier_id numeric(4), supplier_name varchar2(50), CONSTRAINT check_supplier_id CHECK (supplier_id BETWEEN 100 and 9999) );

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

34. How do we Add, Drop, Enable and Disable a check Constraint? ADD Check Constraint: The syntax for creating a check constraint in an ALTER TABLE statement is: ALTER TABLE table_name add CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]; The DISABLE keyword is optional. If you create a check constraint using the DISABLE keyword, the constraint will be created, but the condition will not be enforced. DROP Check Constraint: The syntax for dropping a check constraint is: ALTER TABLE table_name drop CONSTRAINT constraint_name; ENABLE Check Constraint: The syntax for enabling a check constraint is: ALTER TABLE table_name enable CONSTRAINT constraint_name; DISABLE Check Constraint: The syntax for disabling a check constraint is: ALTER TABLE table_name disable CONSTRAINT constraint_name; Difference Between Stored Procedure and Userdefined Function ? 1>Procedure can return zero or n values whereas function can return one value which is mandatory. 2>Procedures can have input,output parameters for it whereas functions can have only input parameters. 3>Procedure allow select as well as DML statement in it whereas function allow only select statement in it. 4>Functions can be called from procedure whereas procedures cannot be called from function. 5>Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function. 6>We can go for transaction management in procedure whereas we can't go in function. 7>Procedures can not be utilized in a select statement whereas function can be embedded in a select statement. 8> Function return type could be scalar or table or table values(SQL Server). Stored

procedure returns always integer value by default zero. 9>Stored Procedure is pre compiled execution plan Functions are not precompiled. 10> Function do not return the images, text. Stored Procedure returns all. 11>Functions are used for computations. Procedures can be used for performing business logic. 12> Functions MUST return a value. Procedures need not be. 13> UDF can be used in the SQL Statements anywhere in the WHERE/HAVING/SELECT section Stored procedures cannot be.
Normalization : It the procee to organize, manage the data into tables. There are two goals of the normalization process: eliminate redundant data (for example, storing the same data in more than one table) and make data dependency(how tables are related). In practical applications,

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF. Fifth normal form is very rarely seen. First normal form (1NF) sets the very basic rules for an organized database: - Eliminate duplicative columns from the same table. - Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key). Second normal form (2NF) further addresses the concept of removing duplicative data: - Remove subsets of data that apply to multiple rows of a table and place them in separate tables. - Create relationships between these new tables and their predecessors through the use of foreign keys. Third normal form (3NF) goes one large step further: - Remove columns that are not dependent upon the primary key. Finally, fourth normal form (4NF) has one requirement: - A relation is in 4NF if it has no multi-valued dependencies. Rules of Data Normalization Eliminate Repeating Groups - Make a separate table for each set of related attributes, and give each table a primary key. Eliminate Redundant Data - If an attribute depends on only part of a multi-valued key, remove it to a separate table. Eliminate Columns Not Dependent On Key - If attributes do not contribute to a description of the key, remove them to a separate table. Isolate Independent Multiple Relationships - No table may contain two or more 1:n or n:m relationships that are not directly related. Isolate Semantically Related Multiple Relationships - There may be practical constrains on information that justify separating logically related many-to-many relationships. Optimal Normal Form - a model limited to only simple (elemental) facts, as expressed in ORM. Domain-Key Normal Form - a model free from all modification anomalies.

A small example: Name mah iham Company AAA BBB DATA Company_Address Street1 strret2 Table1 CompanyAddress Street1 urlA AAA.com AAA.com urlB BBB.com BBB.com

After First Normal Form Id Name 1 mah Company AAA Host AAA.com

Coding, A Rhythmic Literary Job 1 2 2 mah iham iham AAA BBB BBB Street1 strret2 strret2

http://www.dotnet-tricks.com

BBB.com AAA.com BBB.com

After Second Normal Form Id 1 2 P_Id 1 2 3 4 Name mah iham Company AAA BBB F_Id 1 1 2 2 Table2 CompanyAddress Street1 strret2 Table3 Host AAA.com BBB.com AAA.com BBB.com Table4 Id 1 2 PF_Id 1 2 H_Id 1 2 3 4 Name mah iham Company AAA BBB F_Id 1 1 2 2 RF_Id 1 2 Table5 CompanyAddress Street1 strret2 Table6 Host AAA.com BBB.com AAA.com BBB.com Table7 Id 1 2 PF_Id 1 2 H_Id 1 Name mah iham Company AAA BBB RF_Id 1 2 Table8 CompanyAddress Street1 strret2 Table9 Host AAA.com

After Third Normal Form

Finally Data Relationships

Coding, A Rhythmic Literary Job 2 HID 1 2 3 4 FH_Id 1 1 2 BBB.com Table10

http://www.dotnet-tricks.com

F_ID 1 2 1

Some of the major benefits include the following : 1.Greater overall database organization 2.Reduction of redundant data 3.Data consistency within the database 4.A much more flexible database design 5.A better handle on database security Denormalistion : 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. Denormalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access

Coding, A Rhythmic Literary Job


Handling Removable database: Handling

http://www.dotnet-tricks.com

Removable database in SQL Server

The main purpose of the removable database is you can create a database for read-only purposes that can be distributed through removable media such as CD-ROM. Creating Removable data base Syntax : Sp_create_removable databasename, Syslogical, sysphysical, syssize, loglogical, logphysical, logsize, datalogical,dataphysical, datasize sp_create_removable sales, salessys, 'c:\sales\data\salessys.dat',3, saleslog,'c:\sales\data\saleslog.dat',6, salesdata,'c:\sales\data\salesdata.dat',20 This database needs three type of files. One file that contains the system tables One file that contains the transaction log One or more files that contain the data tables Checking Database cration After that creates a removable database you can check that with the sp_certify_removable stored procedure. you can use the sp_certify_removable system stored procedure to make sure the database is configured correctly for distribution on removable media. Sp_certify_removable databasename auto This keyword auto is used to handing error automatically. This check is only for checking the users and user permissions, you can add group manually and grand permission for the groups. If you run sp_certify_removable without the auto value and it returns information about any of the following conditions The system administrator is not the database owner. Any user-created users exist. The system administrator does not own all objects in the database. Nondefault permissions have been granted. Removing Removable database Syntax: Sp_dbremove databasname By using this comment you can remove the removable databse, Instead

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

of that you can you drop database syntax also. Installing the removable data base Use sp_dbinstall to install a removable media database. This allow you to create or administer users and permissions and else.
Constraints : Constraints are database objects that restrict the data that a user or application program can enter into the columns of a table. There are seven types of constraints: 1. assertions, 2. domains 3. check constraints, 4. foreign key constraints, 5. primary key constraints, 6. required data, and 7. uniqueness constraints. Each type of constraint plays a different roll in maintaining database integrity: Assertions. Allow you to maintain the integrity of a relationship among data values that cross multiple tables within a database. Suppose, for example, that you have a marketing room with four teams of sales representatives, and each of the sales representatives has a quota for the number of sales he or she is to make on a daily basis. If your marketing manager has a daily quota, you would use an assertion to ensure that the ROOM_QUOTA column in the marketing manager record (row) of the MANAGER table did not exceed the sum of the values in the REP_QUOTA column in the PHONE_REP table Domains. Ensure that users and applications enter only valid values into table columns. Every column in a table has a certain set of values that are legal for that column. For example, if the MONTHLY_SALARY column in a PAYROLL table must always have values between $0.00 and $100,000.00, you can apply a domain constraint to tell the DBMS to prevent values outside of that range from being entered into the database. (Of course, high-stress jobs, such as SQL DBA, will require that the upper limit of the MONTHLY_SALARY domain be higher.) Check constraints. In addition to being used to define domains and assertions, this constraint can be applied directly to table columns in CREATE TABLE or ALTER TABLE statements. Whether a check constraint is given a name (using the CREATE DOMAIN or CREATE ASSERTION statement) or is added directly to a table definition, it performs the same function. Foreign key constraints. Are used to maintain referential integrity within the database by making sure that the parent record is not removed if there are still child records. Conversely, the FOREIGN KEY constraint also makes sure that you do not add a child record (row) to a table if there is no corresponding parent. Suppose, for example, that you had two tables, STUDENT and GRADES. You would apply the FOREIGN KEY constraint to one of the columns (such as STUDENT_NUMBER) in the child (GRADES) table to tell the DBMS that the value inserted in that column must also be present in the PRIMARY KEY column in one of the rows in the parent (STUDENT) table. Thus, if STUDENT_ID were the PRIMARY KEY in the (parent) STUDENT table, the DBMS would allow the insertion of a row into the GRADES table only if the student record (row) had a STUDENT_NUMBER equal to one of the STUDENT_IDs in the STUDENT table. Conversely, the DBMS would prevent the deletion of any student record (row) from the STUDENT table if one or more grades records (rows) had a STUDENT_NUMBER equal to the

Coding, A Rhythmic Literary Job


STUDENT_ID in the row to be deleted.

http://www.dotnet-tricks.com

Primary key constraints. Maintain entity integrity by specifying that at least one column in a table must have a unique value in each and every row of the table. Having a column with a different value in every row of the table prevents two rows of the table from being identical, thereby satisfying Codd's Rule #2 ("The Guaranteed Access Rule," discussed in Tip 6, "Understanding Codd's 12-Rule Relational Database Definition"). If you have a STUDENT table, for example, you would want one and only one row in the table to list the attributes (columns) for any one student. As such, you would apply the PRIMARY KEY constraint to the STUDENT_ID column of the STUDENT table in order to ensure that no two students were given the same student ID number. Required data. Some columns in a table must contain data in order for the row to successfully describe a physical or logical entity. For example, suppose you had a GRADES table that contained a STUDENT_ID column. Each and every row in the table must have a value in the STUDENT_ID column in order for that grade record (row) to make senseafter all, a grade in a class is meaningless unless it is associated with the specific student (identified by the STUDENT_ID) that earned it. Uniqueness constraints. While each table can have only one PRIMARY KEY, there are times when you may want to specify that more than one column in a table should have a unique value in each row. You can apply the UNIQUE constraint Using the UNIQUE Column Constraint to Prevent Duplicate Values in a Column") to a table column to ensure that only one row in the table will have a certain value in that column. Suppose, for example, that you have a TEACHERS table and want to have only one teacher available for each subject offered at the school. If the table's PRIMARY KEY constraint were already applied to the TEACHER_ID column, you could apply the UNIQUE constraint to the SUBJECT column to tell the DBMS not to allow the insertion of a row where the value in the SUBJECT column matched the value in the SUBJECT column of a row already in the table. The DBMS stores a description of each constraint in its system tables when the constraint is normally specified as part of a table definition (CHECK, FOREIGN KEY, PRIMARY KEY, NOT NULL [required data], UNIQUE), or by using the CREATE statement (ASSERTION, DOMAIN). All constraints are database objects that either limit the values that you can put into a table's columns or limit the rows (combination of column values) that you can add to a table Schema : schema is a container that holds a set of tables, the metadata that describes the data (columns) in those tables, the domains and constraints that limit what data can be put into a table's columns, the keys (primary and foreign) that limit the rows that can be added to and removed from a table, and the security that defines who is allowed to do what to objects in the schema. Cursor : Cursor is a database object used by applications to manipulate data in a set on a rowby-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. In order to work with a cursor we need to perform some steps in the following order: Declare cursor Open cursor Fetch row from the cursor Process fetched row Close cursor Deallocate cursor Types of cursors: 1)Static 2)Dynamic 3)Forward-only

Coding, A Rhythmic Literary Job


4)Keyset-driven.

http://www.dotnet-tricks.com

Disadvantages of cursors: 1) 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). 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. 2) It hampers performance and costly too. ACID Properties : ACID means Atomicity, Consistency, Isolation, and Durability. It is to ensure the integrity of the Database. It allows safe transaction for the critical money transfers. It will complete the transaction otherwise it will revoke all the changes. ACID properties are important concept for Database. Atomicity: For each transaction if any one fails then entire transaction fails. In simple words everything should be atomic. For example For a money transfer it should be debited from one account and it should be credited to another account. If one fails then it should be debited or credited. Consistency: Consistency should be checked for the Database to check for the valid entries. If some entries are wrong and it is not valid then entire transaction will be revoked and nothing will get affected. Consistency will check for the Valid and check for the DB rules also. For example: The amount should be a valid number. It should not have special chars other than Dot Isolation: If many transactions occurred at the same time then it should not overlap or it should not affect other transaction. Each should be isolated. For Example: If A is transferring money to B and B is transferring money C. and C is transferring money to A. it should not affect until one transaction is completed. Durability:

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

It will check for the committed values. Whether the values are correctly stored For Example: If some amount is debited and credited to another account. It should match each other.

How to get the different date time formats : 101 U.S. mm/dd/yyyy 102 ANSI yy.mm.dd 103 British/French dd/mm/yy 104 German dd.mm.yy 105 Italian dd-mm-yy 106 (1) - dd mon yy 107 (1) - Mon dd, yy 108 - hh:mm:ss 9 or 109 (1, 2) mon dd yyyy hh:mi:ss:mmmAM (or PM) 110 USA mm-dd-yy 111 JAPAN yy/mm/dd 112 ISO yymmdd 113 (1, 2)Europe dd mon yyyy hh:mm:ss:mmm(24h) 114 - hh:mi:ss:mmm(24h) 120 (2) ODBC canonical yyyy-mm-dd hh:mi:ss(24h) 121 (2) ODBC canonical yyyy-mm-dd hh:mi:ss.mmm(24h) 126 (4) ISO8601 yyyy-mm-ddThh:mm:ss.mmm (no spaces) 127(6) ISO8601 with time zone. yyyy-mm-ddThh:mm:ss.mmmZ - 130 (1, 2) Hijri (5) dd mon yyyy hh:mi:ss:mmmAM - 131 (2) Hijri (5) dd/mm/yy hh:mi:ss:mmmAM Functions in Sql : 1.Built-inFunctions 2.User Defined functions Built-inFunctions: Built-in functions are system defined functions .There are many Built-in Functions in Ms Access and Sql server There are mainly two types of Built-in Functions i. Aggregate function ii. Scalar function i.Aggregate function:It operates against a collection of values but returns a single value Ex:Sum,Count,Max,Min etc. ii.Scalar function:Scalar functions operate against a single value, and return a single value based on the input value Ex:UCASE,LCASE,Mid User Defined function: A user-defined function can be an external, sourced, or SQL scalar function. An external function is defined to the database with a reference to a load module that is executed when the function is invoked. A sourced function is defined to the database with a reference to a built-in function or another user-defined function. Sourced functions are useful for supporting the use of built-in aggregate and scalar functions for distinct types. The definition of an SQL function includes a RETURN statement.

Coding, A Rhythmic Literary Job Types of data files:

http://www.dotnet-tricks.com

Primary data files The primary data file is the starting point of the database and points to the other files in the database. Every database has one primary data file. The recommended file name extension for primary data files is .mdf. Secondary data files Secondary data files comprise all of the data files other than the primary data file. Some databases may not have any secondary data files, while others have multiple secondary data files. The recommended file name extension for secondary data files is .ndf. Log files Log files hold all of the log information used to recover the database. There must be at least one log file for each database, although there can be more than one. The recommended file name extension for log files is .ldf. SQL Server 2000 does not enforce the .mdf, .ndf, and .ldf file name extensions, but these extensions are recommended to help identify the use of the file.
In SQL Server 2000, the locations of all the files in a database are recorded in both the master database and the primary file for the database. Most of the time the database engine uses the file location information from the master database. For some operations, however, the database engine uses the file location information from the primary file to initialize the file location entries in the master database. SQL Server data and log files can be placed on either FAT or NTFS file systems, but cannot be placed on compressed file system. Transaction Log Architecture Every Microsoft SQL Server 2000 database has a transaction log that records all transactions and the database modifications made by each transaction. This record of transactions and their modifications supports three operations: Recovery of individual transactions If an application issues a ROLLBACK statement, or if SQL Server detects an error such as the loss of communication with a client, the log records are used to roll back the modifications made by an incomplete transaction. Recovery of all incomplete transactions when SQL Server is started . If a server running SQL Server fails, the databases may be left in a state where some modifications were never written from the buffer cache to the data files, and there may be some modifications from incomplete transactions in the data files. When a copy of SQL Server is started, it runs a recovery of each database. Every modification recorded in the log which may not have been written to the data files is rolled forward. Every incomplete transaction found in the transaction log is then rolled back to ensure the integrity of the database is preserved. Rolling a restored database forward to the point of failure After the loss of a database, as is possible if a hard drive fails on a server that does not have RAID drives, you can restore the database to the point of failure. You first restore the last full or

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

differential database backup, and then restore the sequence of transaction log backups to the point of failure. As you restore each log backup, SQL Server reapplies all the modifications recorded in the log to roll forward all the transactions. When the last log backup is restored, SQL Server then uses the log information to roll back all transactions that were not complete at that point. Some Global Variable :

@@servername Returns the name of the local server running Example: Select @@servername @@servicename Returns the name of the registry key under which Microsoft SQL Server is running. @@SERVICENAME returns MSSQLServer if the current instance is the default instance; this function returns the instance name if the current instance is a named instance. Example:Select @@servicename @@language Returns the name of the language currently in use. Example:Select @@language @@langid Returns the local language identifier (ID) of the language currently in use. Example:Select @@langid @@connections Returns the number of connections, or attempted connections, since Microsoft SQL Server was last started Example:Select @@connections @@max_connections Returns the maximum number of simultaneous user connections allowed on a Microsoft SQL Server. The number returned is not necessarily the number currently configured. Example:Select @@max_connections @@spid Returns the server process identifier (ID) of the current user process. Example: SELECT @@SPID AS 'ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name' @@Pack_Sent Returns the number of output packets written to the network by Microsoft SQL Server since last started. Example: SELECT @@Pack_Sent @@Pack_received

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

Returns the number of input packets read from the network by Microsoft SQL Server since last started. Example: SELECT @@Pack_received @@Packet_Errors Returns the number of network packet errors that have occurred on Microsoft SQL Server connections since SQL Server was last started. Example: SELECT @@Packet_Errors @@total_read Returns the number of disk reads (not cache reads) by Microsoft SQL Server since last started. Example: SELECT @@total_read @@total_write Returns the number of disk writes by Microsoft SQL Server since last started. Example: SELECT @@total_write @@total_errors Returns the number of disk read/write errors encountered by Microsoft SQL Server since last started. Example: SELECT @@total_errors @@cpu_busy Returns the time in milliseconds (based on the resolution of the system timer) that the CPU has spent working since Microsoft SQL Server was last started. Example: SELECT @@cpu_busy @@io_busy Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has spent performing input and output operations since it was last started. Example:SELECT @@io_busy @@idle Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has been idle since last started. Example: SELECT @@idle
Difference Between Varcahr and nvarchar : varchar uses 8 bits per character. nvarchar is UNICODE, a double-byte character set, requiring 16 bits to store each character. 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.

What is the Difference between UNION and UNION ALL?

Coding, A Rhythmic Literary Job

http://www.dotnet-tricks.com

Ans. Union selects distinct values while Union All selects all the values irrespective of its frequency In the particular table from two different tables.

You might also like