Sunday, 12 May 2013

Difference between Stored Procedure and Function

Difference between Stored Procedure and 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 allows select as well as DML(INSERT/UPDATE/DELETE) statements in it whereas function allows 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 cannot be utilized in a select statement whereas function can be embedded in a select statement.

Differences between stored procedures and triggers

Differences between storedprocedures and triggers 

1. When you create a trigger you have to identify event and action of your trigger but when you create s.p you don't identify event and action 

2.Trigger is run automatically if the event is occured but s.p don't run automatically but you have to run it manually 

3. Within a trigger you can call specific s.p but within a sp you cannot call atrigger 

4.Trigger execute implicitly whereas store procedure execute via procedure call from another block. 

5.We can call a stored procedure from front end (.asp files, .aspx files, .ascx files etc.) but we can't call a trigger from these files. 

6. Stored procedure can take the input parameters, but we can't pass the parameters as an input to a trigger. 

What are different types of caching in ASP.Net? Caching in asp.net


There are three main types of Caching:
  1. Page Output caching : Caching complete page
  2. Fragment caching: Caching a portion of a page
  3. Data Caching: Caching data

Wednesday, 3 April 2013

[SOLVED] Remove Special Characters from the Textbox using JavaScript



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>[SOLVED]Remove Special Characters from the Textbox using JavaScript</title>
<script language="javascript" type="text/javascript">
function RemoveSpecialCharTest(txtNameTest) {
if (txtNameTest.value != '' && txtNameTest.value.match(/^[\w ]+$/) == null) {
txtNameTest.value = txtNameTest.value.replace(/[\W]/g, '');
}
}
</script>
</head>
<body>
<div>
<b>Enter Text:</b><input id="txtNameTest"  type="text" onkeyup="javascript:RemoveSpecialCharTest(this)" />
</div>
</body>
</html>

Friday, 29 March 2013

self joins examples in sql


How To Use Self Join In Sql Server


Self Join in SQL Server 2000/2005 helps in retrieving the records having some relation or similarity with other records in the same database table. A common example of employees table can do more clearly about the self join in sql. Self join in sql means joining the single table to itself. It creates the partial view of the single table and retrieves the related records. You can use aliases for the same table to set a self join between the single table and retrieve the records satisfying the condition in where clause.
For self join in sql you can try the following example:

Create table employees:
emp_idemp_nameemp_manager_id
1JohnNull
2Tom1
3Smith1
4Albert2
5David2
6Murphy5
7Petra5

Now to get the names of managers from the above single table you can use sub queries or simply the self join.

Self Join SQL Query to get the names of manager and employees:
select e1.emp_name 'manager',e2.emp_name 'employee'
from employees e1 join employees e2
on e1.emp_id=e2.emp_manager_id

Result:
manageremployee
JohnTom
JohnSmith
TomAlbert
TomDavid
DavidMurphy
DavidPetra

Views in SQL Server


View

A view is a virtual table that consists of columns from one or more tables. Though it is similar to a table, it is stored in the database. It is a query stored as an object. Hence, a view is an object that derives its data from one or more tables. These tables are referred to as base or underlying tables.
Once you have defined a view, you can reference it like any other table in a database.
A view serves as a security mechanism. This ensures that users are able to retrieve and modify only the data seen by them. Users cannot see or access the remaining data in the underlying tables. A view also serves as a mechanism to simplify query execution. Complex queries can be stored in the form as a view, and data from the view can be extracted using simple queries.

Example

Consider the Publishers table below. If you want users to see only two columns in the table, you can create a view called vwPublishers that will refer to the Publishers table and the two columns required. You can grant Permissions to users to use the view and revoke Permissions from the base Publishers table. This way, users will be able to view only the two columns referred to by the view. They will not be able to query on the Publishers table.
Publishers
Publd
PubName
City
State
Country
0736
New Moon Books
Boston
MA
USA
0877
Binnet & Hardly
Washington
DC
USA
1389
Algodata Infosystems
Berkeley
CA
USA
1622
Five Lakes Publishing
Chicago
IL
USA
VW Publishers
Publd
PubName
0736
New Moon Books
0877
Binnet & Hardly
1389
Algodata Infosystems
1622
Five Lakes Publishing
Views ensure the security of data by restricting access to the following data:
  • Specific rows of the tables.
  • Specific columns of the tables.
  • Specific rows and columns of the tables.
  • Rows fetched by using joins.
  • Statistical summary of data in a given tables.
  • Subsets of another view or a subset of views and tables.
Some common examples of views are:
  • A subset of rows or columns of a base table.
  • A union of two or more tables.
  • A join of two or more tables.
  • A statistical summary of base tables.
  • A subset of another view, or some combination of views and base table.


Creating Views

A view can be created by using the CREATE VIEW statement.

Syntax

CREATE VIEW view_name
[(column_name[,column_name]….)]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]
Where:
view_name specifies the name of the view and must follow the rules for identifiers.
column_name specifies the name of the column to be used in view. If the column_name option is not specified, then the view is created with the same columns as specified in the select_statement.
WITH ENCRYPTION encrypts the text for the view in the syscomments table.
AS specifies the actions that will be performed by the view.
select_statement specifies the SELECT Statement that defines a view. The view may use the data contained in other views and tables.
WITH CHECK OPTION forces the data modification statements to fulfill the criteria given in the SELECT statement defining the view. It also ensures that the data is visible after the modifications are made permanent.
The restrictions imposed on views are as follows:
  • A view can be created only in the current database.
  • The name of a view must follow the rules for identifiers and must not be the same as that of the base table.
  • A view can be created only if there is a SELECT permission on its base table.
  • A SELECT INTO statement cannot be used in view declaration statement.
  • A trigger or an index cannot be defined on a view.
  • The CREATE VIEW statement cannot be combined with other SQL statements in a single batch.

Example

CREATE VIEW vwCustomer
AS
SELECT CustomerId, Company Name, Phone
FROM Customers
Creates a view called vwCustomer. Note that the view is a query stored as an object. The data is derived from the columns of the base table Customers.
You use the view by querying the view like a table.
SELECT *FROM vwCUSTOMER
The output of the SELECT statement is:
CustomerId
Company Name
Phone
ALFKI
Alfreds Futterkiste
030-0074321
ANTON
Antonio Moreno Taqueria
(5)555-3932
(91 rows affected)

[SOLVED] triggers in sql server 2008 with simple example


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

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

Basically, triggers are classified into two main types:-

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

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

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

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

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

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

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

Now, create the audit table as:-
 Collapse | Copy Code
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
(a) AFTRE INSERT Trigger

This trigger is fired after an INSERT on the table. Let’s create the trigger as:-

CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

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

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

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

 insert into Employee_Test values('Chris',1500);

Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the Employee_Test_Audit as:-

6   Chris  1500.00   Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700
(b) AFTER UPDATE Trigger

This trigger is fired after an update on the table. Let’s create the trigger as:-

CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]
FOR UPDATE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;

if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';

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

PRINT 'AFTER UPDATE Trigger fired.'
GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the logical table inserted. We can obtain the updated value of a field from the update(column_name) function. In our trigger, we have used, if update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Let’s update a record column and see what happens.

 update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:-
 Collapse | Copy Code
6  Chris  1550.00  Updated Record -- After Update Trigger.  2008-04-26 12:38:11.843
(c) AFTER DELETE Trigger

This trigger is fired after a delete on the table. Let’s create the trigger as:-

CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test]
AFTER DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);

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

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

PRINT 'AFTER DELETE TRIGGER fired.'
GO
In this trigger, the deleted record’s data is picked from the logical deleted table and inserted into the audit table.
Let’s fire a delete on the main table.
A record has been inserted into the audit table as:-

 6  Chris 1550.00  Deleted -- After Delete Trigger.  2008-04-26 12:52:13.867
All the triggers can be enabled/disabled on the table using the statement

ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL
Specific Triggers can be enabled or disabled as :-

ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete

This disables the After Delete Trigger named trgAfterDelete on the specified table.
(ii) Instead Of Triggers

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

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

(a) Let’s create an Instead Of Delete Trigger as:-

CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]
INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;

select @emp_id=d.Emp_ID from deleted d;
select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;

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

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

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

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