Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Showing posts with label Sql Server. Show all posts
Showing posts with label Sql Server. Show all posts

Saturday, 11 February 2017

What Are Triggers In SQL Server

Triggers

Triggers, automatically executed or fired when some changes occurs in database like UPDATE, DELETE and INSERT. Triggers are used for security of the data, so that data remain unchanged until we change it. We can say they are the special kind of stored procedure.

General Method of Writing Triggers


CREATE TRIGGER TRIGGERNAME
     ON TABLENAME
     AFTER EVENT
     AS BEGIN
     'YOUR LOGIC GOES HERE'
        END

The CREATE TRIGGER statement is used to create the trigger and ON specifies the table on which trigger will be attached. AFTER EVENT specifies that this is After Trigger.

Types of Triggers


There two types of triggers
  1. After Triggers
  2. Instead Of Triggers

1. After Triggers

These triggers run after an insert, update or delete. Let’s try to understand with the help of an example.
Create a table employee and insert some dummy records in it.
--CREATING TABLE EMPLOYEES
CREATE TABLE EMPLOYEES
(
ID INT IDENTITY PRIMARY KEY,
NAME VARCHAR(20),
);

INSERT INTO EMPLOYEES VALUES ('SYMOND')
INSERT INTO EMPLOYEES VALUES ('MICHAEL')
INSERT INTO EMPLOYEES VALUES ('GREGG')
INSERT INTO EMPLOYEES VALUES ('JOHN')

At this point I am going to create another table “Audit_Employees” in which we are going to record the changes that will happen in the main table.

--CREATING TABLE AUDIT EMPLOYEES
CREATE TABLE AUDIT_EMPLOYEES
(
ID INT,
NAME VARCHAR(20),
[ACTION] VARCHAR(100),
[DATE] DATE
)
Now it’s time to create an after Insert Triggers so here we go.

After Insert Trigger


--CREATING INSERT TRIGGERS
CREATE TRIGGER AFTERINSERT
       ON EMPLOYEES
              AFTER INSERT
AS BEGIN
              DECLARE @ID INT
              DECLARE @NAME VARCHAR(20)
              DECLARE @A VARCHAR(30)

              SELECT @ID=I.ID FROM INSERTED I /* INSERTED IS AUTOMATICALLY CREATED TABLE.ONLY USED IN TRIGGERS.CAN’T USED OUTSIDE THE TRIGGERS */
              SELECT @NAME=I.NAME FROM INSERTED I

              SET @A='INSERT TRIGGER IS FIRED'

              INSERT INTO AUDIT_EMPLOYEES VALUES (@ID, @NAME, @A, GETDATE())
      
       PRINT 'INSERT TRIGGER IS FIRED'
END

INSERTED is a logical table that is automatically created and is only used in triggers and not outside of them.

2. Instead Of Triggers

These triggers are used as an interceptor for anything that anyone tried to do on your table or view. For example if you define and Instead Of Trigger on your Employee table and anyone tries to delete record from employee table the record will not get deleted. Let’s understand with the help of an example.

CREATE TRIGGER INSTEAD_OF_DELETE ON [EMPLOYEES]
INSTEAD OF DELETE
AS
BEGIN
       DECLARE @ID INT;
       DECLARE @NAME VARCHAR(100);
      
      
       SELECT @ID=D.EMP_ID FROM DELETED D;
       SELECT @NAME=D.EMP_NAME FROM DELETED D; 

       BEGIN
              IF(@NAME = 'JOHN')
              BEGIN
                     RAISERROR('CANNOT DELETE WHERE NAME  = JOHN',16,1);
                     ROLLBACK;
              END
              ELSE
              BEGIN
                     DELETE FROM [EMPLOYEES] WHERE EMP_ID=@EMP_ID;
                     COMMIT;
                     INSERT INTO AUDIT_EMPLOYEES(ID,NAME,[ACTION],[DATE])
                     VALUES(@ID,@NAME,'DELETED -- INSTEAD OF DELETE TRIGGER.',GETDATE());

                     PRINT 'RECORD DELETED -- INSTEAD OF DELETE TRIGGER.'
              END
       END

END

This trigger will prevent the deletion of records from the table where Name = 'John'. If user will try to delete such a record where name is john the Instead Of Trigger will rollback the transaction. 

Tuesday, 5 January 2016

Error While Importing Excel(2007) "The 'Microsoft.ACE.OLEDB.12.0' Provider is not Registered on the Local Machine"

Yesterday I was in database team with my friend to import an excel file of 3 million records in a table. While importing we got any error message “The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine”. Here I just want to tell you that we have to do this activity every month and from past 6 months we were doing it successfully until yesterday when we ran into an error “The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine”.

We were in a hurry so we tried another system to import our file but same error come in front of us and in short span we tried three systems but no success. At last I have researched about this error and got to know that we need to install “2007 Office System Driver: Data Connectivity Components”. So I have installed it from this Microsoft link: Click Here on one of our system and then tried importing the excel file into database table and that's it. Yahooooo it was successful. We've spent a lot of time that is why i have decided to write this post so if anyone ran into this problem will solve it by himself after five minutes of searching on Google.

Hope this article will solve your problem and save your time.

Friday, 10 May 2013

How To Find Execution Time Of Stored Procedure | Sql Server

In this tutorial I am going to tell you how we can find the execution time of stored procedure in Sql server.

First Method: -

  DECLARE @FIRST DATETIME
  DECLARE @SECOND DATETIME
  
  SET @FIRST = GETDATE()

-- Execute your stored procedure here. i.e exec name of your SP

  EXEC STORED PROCEDURE 

  SET @SECOND = GETDATE()

  SELECT DATEDIFF(SECOND,@FIRST,@SECOND)  AS TOTAL_TIME

Second Method: -
You can use this method as well to find execution time and it will return you timing of all single queries inside your stored procedure. So if you have bunch of queries inside then it might be not very convenient.

 
 SET STATISTICS TIME ON
-- Execute your stored procedure here. i.e exec name of your SP
 EXEC STORED PROCEDURE 
 SET STATISTICS TIME OFF

Third Method: -

  DECLARE @T DATETIME
  SET @T = CURRENT_TIMESTAMP
  -- Execute your stored procedure here. i.e exec name of your SP
  EXEC STORED PROCEDURE 
  SELECT DATEDIFF(SECOND,@T,CURRENT_TIMESTAMP) AS TOTAL_TIME

If you want to measure execution time in milliseconds then it is also simple
    
   DECLARE @T DATETIME
   SET @T = CURRENT_TIMESTAMP
   -- Execute your stored procedure here. i.e exec name of your SP
   EXEC STORED PROCEDURE 
   SELECT DATEDIFF(MILLISECOND,@T,CURRENT_TIMESTAMP) AS TOTAL_TIME

Monday, 22 April 2013

Difference Between Local And Global Temporary Tables

In this tutorial we will learn about local and global temporary tables in MicroSoft Sql Server. Temporary table are very handy when you need to process data or perform calculation using same selection. They are also very useful when you need data temporarily because when client session disconnet they vanishes away. There are two type of temporary tables and below are the details of each type.

Local Temporary Table:-


To create local temporary table we use below statement.

                        create table # temp

Now this table is only visible to connection(same query window) that creates it.And it will be deleted when the connection(query window) will be closed. local temporary tables cannot be shared between multiple users.All temp tables are stored in tempdb database.

Global Temporary Table:-


To create Global temporary table we use below statement.

                        create table ## temp

Now this table is available to all connections and not cleared until unless the last connection is closed. These tables can be shared to multiple users as well and they are also stored in tempdb database.

Tuesday, 16 April 2013

Concatenate Multiple Rows Value Into Single String Text | Sql Server

In this tutorial, we will learn how to concatenate the multiple rows for a single column value into a single string text SQL server.  I am using the Northwind database table “Customers” and the column name is “ContactName”. And here is the query


    SELECT CONTACTNAME  FROM CUSTOMERS

    DECLARE @STR NVARCHAR(MAX)
    SELECT @STR = COALESCE(@STR + ',','') + C.CONTACTNAME FROM CUSTOMERS C
    PRINT @STR
    SELECT @STR AS [STR OUTPUT]

Result:-
          
               

COALESCE() A built-in function of SQL server is used in the query which returns a first non-null expression.

To learn more about COALESCE() function click here.

Sunday, 14 April 2013

Find Second Highest Value In A Column In Table | SQL Server

In this tutorial you will learn a query to find second highest value of column in a table. I am using Northwind database table “Order” for this tutorial.

First have a look at the query to find the first highest value of the column. I have used max() built in function of MS SQL server to find the highest value of the column.

-- First Highest Value

select max(orderid) as HighestValue from orders

Now I am going to write a query for second highest value of column “orderid” which is very easy.

-- Second Highest Value

select max(orderid) as SecondHighestValue from orders where orderid not in (select max(orderid) as HighestValue from orders)

I just use the first query as subquery and find the highest value after that I use not in to find the second highest value. Here is another query to find the second highest value of a column.

-- Second Highest Value 
SELECT orderid as SecondHighestValue FROM orders WHERE orderid =( SELECT MAX(orderid) FROM orders WHERE orderid<(SELECT max(orderid) FROM orders))

                                                    Hope it will be helpful for you.

Saturday, 6 April 2013

Create Database in SQL Server

As a database learner or In your first database lab class you may be asked to create database and tables in SQL Server. Here I am going to tell you the method of creating your first database and table in SQL Server.

Create Database

Open your SQL Server Management Studio(SSMS) and Press ctrl + n to open new query window. Type below query in your query window and execute it to create your first database.

Query Syntax :

 
  	create database <your_database_name>
 

Example :

 
	create database DEMODB

Create Table

To create your first table in above mentioned database "DEMODB" first you need to select the database you created with above sql query. After that you can make table with the help of create table command.

Query Syntax :


    use <database_name>
    
    create table <your_table_name>
    ( 
    your_column_name1 data_type,
    your_column_name2 data_type,
    your_column_name2 data_type
    )
 

Example :

 
  
  create table customer
  (
  customer_id bigint, 
  customer_name varchar(100),
  customer_dob datetime
  )
  

  

Tuesday, 15 January 2013

Could not load file or assembly microsoft.sqlserver.management.sdk.sfc

Today when I tried to connect my application(which is in visual studio 2010) with SQL server 2005 as a database. I've got the following error in my application due to which I was unable to proceed further.

Error/Exception:-

Often you have seen this "Could not load file or assembly" kind of error and In my case, it was "‘Microsoft.SqlServer.Management.Sdk.Sfc, Version=X.x.x.x,(In my case it was 10.0.0.0 version) Culture=neutral, PublicKeyToken=89845dcd8080cc91′ or one of its dependencies. The system cannot find the file specified."  error and it is due to some of the missing file i.e. possibly dll or any other file

Solution:

After a bit of researching, I've got the solution that is a pretty simple one because we just need to install three files, and boom it will work. You can download these files from the Microsoft website.

  1. Microsoft SQL Server System CLR Types
  2. Microsoft SQL Server 2008 Management Objects
  3. Microsoft SQL Server 2008 Native Client.

After installing the above three files try to connect your application with the SQL server database and if still, you get the same error message then don't worry and close your application then start it again and you will be able to connect it.

Here are the related links from where I got the solution to this problem and I thought to share it.

http://chiragrdarji.wordpress.com/2009/05/14/could-not-load-file-or-assembly-microsoft-sqlserver-management-sdk-sfc/
http://technologyteams.blogspot.com/2010/05/unable-to-add-data-connection-could-not.html

Hope this post will help you in solving your problem.

Thursday, 13 September 2012

ALTER Statements in SQL Server

Today we will learn about the SQL alter statements and look into scenarios in which we can use them and how.So here we go


To create table use the following.

    CREATE TABLE [dbo].[person](

      [PERSON_ID] [varchar](20) NOT NULL,

      [PERSON_NAME] [varchar](15) NULL,

      [PERSON_ADDRESS] [varchar](20) NULL,

      [Department] [varchar](20) NULL
)


To change the table name and column name, use the following:

 1.                    -- To change table name

 sp_rename 'person_table','person'

 2.                    -- To change column name

 sp_rename 'person.designation','Department','column' 

 

To alter tables use the following queries:

3.                    -- To Add a column

 alter table person

 add Designation varchar(20)

4.                    -- To Drop a column

 alter table person

 drop column designation 

5.                    -- To change data type of column

 alter table person

 alter column person_id int 

6.                   -- To Add primary key constraint

 alter table person

 add constraint pk_person_id primary key(person_id)

7.                    -- To Drop primary key constraint

 alter table person

 drop constraint pk_person_id

8.                    -- To Add foreign key constraint

 alter table person

 add constraint fk_person_id foreign key(person_id) references department(person_id)

9.                    -- To Drop foreign key constraint

 alter table person

drop constraint fk_person_id