Showing posts with label SQL 2008. Show all posts
Showing posts with label SQL 2008. Show all posts

Monday, 16 December 2013

Marge statement at SQL 2005

Introduction


As all we now that the MARGE statement is a special feature of MS SQL 2008 only.  But by programmatically we can create it in MS SQL Server 2005.
In this article I am trying to manage the MARGE statement at MS SQL 2005. Here I am not describing the MARGE statement. I just use it as an Example.


IF OBJECT_ID (N'dbo.Tbl_BookInventory', N'U') IS NOT NULL
   BEGIN
          DROP TABLE dbo.Tbl_BookInventory;
   END
GO  
-- Creating the Target Table
CREATE TABLE dbo.Tbl_BookInventory
(
  TitleID     INT             NOT NULL PRIMARY KEY,
  Title            NVARCHAR(100) NOT NULL,
  Quantity         INT             NOT NULL
  CONSTRAINT Quantity_Default_1 DEFAULT 0
);
GO
IF OBJECT_ID (N'dbo.Tbl_BookOrder', N'U') IS NOT NULL
   BEGIN
          DROP TABLE dbo.Tbl_BookOrder;
   END       
GO
-- Creating the Source Table
CREATE TABLE dbo.Tbl_BookOrder
(
  TitleID     INT           NOT NULL PRIMARY KEY,
  Title       nVARCHAR(100) NOT NULL,
  Quantity    INT           NOT NULL
  CONSTRAINT Quantity_Default_2 DEFAULT 0
);
GO
--Inserting Records In Target Table
INSERT INTO dbo.Tbl_BookInventory
       (TitleID, Title, Quantity)    
VALUES
  (1, 'The Catcher in the Rye', 6),
  (2, 'Pride and Prejudice', 3),
  (3, 'The Great Gatsby', 0),
  (5, 'Jane Eyre', 0),
  (6, 'Catch 22', 0),
  (8, 'Slaughterhouse Five', 4);
GO 

-- Inserting Record in Source Table 
INSERT INTO dbo.Tbl_BookOrder
       (TitleID, Title, Quantity)    
VALUES
  (1, 'The Catcher in the Rye', 3),
  (3, 'The Great Gatsby', 0),
  (4, 'Gone with the Wind', 4),
  (5, 'Jane Eyre', 5),
  (7, 'Age of Innocence', 8);
GO 

-- The Marge statement
MERGE dbo.Tbl_BookInventory bi
USING dbo.Tbl_BookOrder bo ON bi.TitleID = bo.TitleID
WHEN MATCHED AND
  bi.Quantity + bo.Quantity = 0 THEN
  DELETE
WHEN MATCHED THEN
  UPDATE SET bi.Quantity = bi.Quantity + bo.Quantity
WHEN NOT MATCHED BY TARGET THEN
  INSERT (TitleID, Title, Quantity)
  VALUES (bo.TitleID, bo.Title,bo.Quantity);
GO 

----------------------------------
-- Marge Statement in SQL 2005 --
----------------------------------

BEGIN
  DECLARE @tblContacts table (ContId INT);
  -- Update Statement     
  UPDATE bi
     SET bi.Quantity = bi.Quantity + bo.Quantity
     OUTPUT inserted.TitleID INTO  @tblContacts
  FROM Tbl_BookInventory AS bi
       INNER JOIN Tbl_BookOrder AS bo
                 ON bi.TitleID = bo.TitleID;
  -- Delete Statement
  DELETE bi
  FROM   Tbl_BookInventory AS bi
         INNER JOIN Tbl_BookOrder AS bo
         ON bi.TitleID = bo.TitleID
            AND (bi.Quantity+bo.Quantity)=0;
  -- Insert Statement
  INSERT INTO Tbl_BookInventory
       (TitleID, Title, Quantity)
  SELECT TitleID, Title, Quantity
  FROM   dbo.Tbl_BookOrder
  WHERE  TitleID NOT IN (SELECT ContId
                         FROM   @tblContacts);
END



SELECT * FROM Tbl_BookInventory

TitleID       Title                   Quantity
1             The Catcher in the Rye  9
2             Pride and Prejudice     3
4             Gone with the Wind      4
5             Jane Eyre               5
6             Catch 22                0
7             Age of Innocence        8
8             Slaughterhouse Five     4


Hope you like it.



Posted by: MR. JOYDEEP DAS

Friday, 18 May 2012

IDENTITY Columns Violation


We all know about the identity columns of SQL Server and how important it is. This article is related to it but I am representing this article to solving a common proble.
First take a quick look about the identity columns and how it works. Then we are going to discuss about the problem and how to solve it programmatically.
Definition of Identity Columns
An IDENTITY column contains a value for each row, generated automatically by Adaptive Server that uniquely identifies the row within the table.
Each table can have only one IDENTITY column. You can define an IDENTITY column when you create a table with a create table or select into statement, or add it later with an alter table statement. IDENTITY columns cannot be updated and do not allow nulls.
You define an IDENTITY column by specifying the keyword identity, instead of null or not null, in the create table statement. IDENTITY columns must have a datatype of numeric and scale of 0. Define the IDENTITY column with any desired precision, from 1 to 38 digits, in a new table:
CREATE TABLE  table_name
             (column_name  INT NOT NULL IDENTITY(1,1))

The Problem comes for Identity
One of my friends told me that, he has a problem for IDENTITY columns. He told me that when he make the INSERT entry into table objects, he never check the uniqueness of the records for that the primary key violation error occurs. He just shows the error.
The problem is the table objects contain identity columns. The value of the identity columns increases each time, even the PK violation exists.
The problem is mentioned by T-SQL statements
Step-1 [ Create the Base Table with IDENTITY columns ]
-- Table defination
DROP TABLE tbl_Example
CREATE TABLE tbl_Example
    (
       ROLL     INT          NOT NULL PRIMARY KEY,
       SNAME    VARCHAR(50)  NULL,
       SCLASS   INT          NULL,
       ROWNUM   INT          NOT NULL IDENTITY(1,1)
    ) 
Step-2 [ Normal Insertions of Values ]
INSERT INTO tbl_Example
            (ROLL,          
                   SNAME,   
                   SCLASS)
VALUES (1, 'JOYDEEP', 1)                     

INSERT INTO tbl_Example
            (ROLL,          
             SNAME,   
             SCLASS)
VALUES (2, 'SUKAMAL', 1)
Step-3 [ See the Output ]
SELECT * FROM tbl_Example

-- Output
ROLL  SNAME       SCLASS      ROWNUM
----  -----       ------      ------
1     JOYDEEP     1           1
2     SUKAMAL     1           2

Step-4 [ Make an Invalid entry that generate an error ]
-- Violation of Primary Key
INSERT INTO tbl_Example
            (ROLL,          
             SNAME,   
             SCLASS)
VALUES (2, 'RAJESH', 1)

-- Output
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__tbl_Exam__44C28DB623BDA346'.
Cannot insert duplicate key in object 'dbo.tbl_Example'.
The statement has been terminated.

Step-5 [ Now Make the Correction entry after correction of data ]
-- Correction of Entry
INSERT INTO tbl_Example
            (ROLL,          
             SNAME,   
             SCLASS)
VALUES (3, 'RAJESH', 1)

Step-6 [ Look the INDENTITY columns has Increased it gives 4 instead of 3 ]

SELECT * FROM tbl_Example

--Output
ROLL        SNAME       SCLASS      ROWNUM
----        -----       ------      ------
1           JOYDEEP     1           1
2           SUKAMAL     1           2
3           RAJESH      1           4

Note that: It is the Normal behavior of the IDENTITY columns. It maintains the uniqueness. Here we are going to break it depends on our needs and it is not good for development. However I am just demonstrating it that we can do it if needed.
Here I am going to make a stored procedure to demonstrate it.
CREATE PROCEDURE my_proc
    (
       @param_roll   INT,
       @param_name   VARCHAR(50),
       @param_calss  INT
    )
AS
   DECLARE @v_NOREC INT
   BEGIN
          BEGIN TRY
            BEGIN TRANSACTION
                  INSERT INTO tbl_Example
                             (ROLL,    
                                            SNAME,   
                                            SCLASS)
                          VALUES (@param_roll, 
                                  @param_name,
                                  @param_calss)           
            COMMIT TRANSACTION
          END TRY
          BEGIN CATCH
            ROLLBACK TRANSACTION
            PRINT 'ERROR EXISTS'
            SELECT @v_NOREC=COUNT(*) FROM tbl_Example
            DBCC CHECKIDENT (tbl_Example, reseed, @v_NOREC)
          END CATCH
   END   
Now we execute it and see the result step by step.
   -- Execution-1
   EXECUTE my_proc
           @param_roll   = 1,
           @param_name   = 'JOYDEEP',
           @param_calss  = 1
          
   SELECT * FROM tbl_Example
 
   ROLL     SNAME       SCLASS      ROWNUM
   1        JOYDEEP     1           1
   -- Execution-2
   EXECUTE my_proc
           @param_roll   = 2,
           @param_name   = 'SUKAMAL',
           @param_calss  = 1
          
  

   SELECT * FROM tbl_Example
   ROLL     SNAME       SCLASS      ROWNUM
   1        JOYDEEP     1           1
   2        SUKAMAL     1           2
   -- Execution-3 [ Primary Key Error ]
   EXECUTE my_proc
           @param_roll   = 2,
           @param_name   = 'SANGRAM',
           @param_calss  = 1

   0 row(s) affected)
    ERROR EXISTS
    Checking identity information: current identity value '3', current column value '2'.
    DBCC execution completed. If DBCC printed error messages, contact your system administrator.
          
   SELECT * FROM tbl_Example
   ROLL     SNAME       SCLASS      ROWNUM
   1        JOYDEEP     1           1
   2        SUKAMAL     1           2
      -- Execution-4       
   EXECUTE my_proc
           @param_roll   = 3,
           @param_name   = 'SANGRAM',
           @param_calss  = 1   
          
   SELECT * FROM tbl_Example
   ROLL     SNAME       SCLASS      ROWNUM
   1        JOYDEEP     1           1
   2        SUKAMAL     1           2
   3        SANGRAM     1           3  
    
Hope you like it.

Posted by: MR. JOYDEEP DAS









Thursday, 17 May 2012

Database SCHEMA


From SQL Server 2005 the DATABASE SCHEMA is introduced by Microsoft. Before understanding the database schema we must review the SQL Server 2000 to understand it properly.

Problem with earlier version of SQL Server (Before SQL Server 2005)

In SQL Server 2000 the schema is owned by, and was inextricably linked to that means a user creates a table in the database, that user cannot be deleted without deleting the table or first transferring it to another user.

How Microsoft helps us to solving this problem

To solve this problem Microsoft is introducing database schema from SQL Server 2005.
A database schema is a way to logically group objects such as tables, views, stored procedures etc. Think of a schema as a container of objects. We can assign user login permissions to a single schema so that the user can only access the objects they are authorized to access. Schemas can be created and altered in a database, and users can be granted access to a schema. A schema can be owned by any user, and schema ownership is transferable.

Default Schema
Users can be defined with a default schema. The default schema is the first schema that is searched when it resolves the names of objects it references.
The default schema for a user can be defined by using the DEFAULT_SCHEMA option of CREATE USER or ALTER USER. If no default schema is defined for a user account, SQL Server will assume "dbo" is the default schema. It is important note that if the user is authenticated by SQL Server as a member of a group in the Windows operating system, no default schema will be associated with the user. If the user creates an object, a new schema will be created and named the same as the user, and the object will be associated with that user schema.
Some properties of database schema
     1.     Ownership of schema and schema-scoped securable is transferable.
  1. Objects can be moved between schemas.
  2. A single schema can contain objects owned by multiple database users.
  3. Multiple database users can share a single default schema.
  4. Permissions on schemas and schema-contained securable can be managed with greater precision than in earlier releases.
  5. A schema can be owned by any database principal. This includes roles and application roles.
  6. A database user can be dropped without dropping objects in a corresponding schema.
To get the Information of Schema for database objects

SELECT  sys.objects.name [Object Name],
        sys.schemas.name AS [Schema Name]
FROM    sys.objects
        INNER JOIN sys.schemas ON sys.objects.schema_id = sys.schemas.schema_id
Object Name                Schema Name
sysrscols                      sys
sysrowsets                   sys
Tbl_1                            dbo
Tbl_2                            dbo


The Example of Database Schema

USE master
GO
CREATE DATABASE my_db
GO
USE my_db
GO
-- Created Schema my_Employee
CREATE SCHEMA my_Employee
GO
-- Created table named in EmpInfo on the my_Employee schema –
CREATE TABLE my_Employee.EmpInfo
    (
      EmpNo int Primary Key identity(1,1),
      EmpName varchar(20)
    )

-- Data insertion

INSERT INTO my_Employee.Empinfo
Values ('Joydeep'),('Tuhin'),('Sangram')

-- Data Selection
SELECT *
FROM   my_Employee.Empinfo

-- Created another schema HR_Dept
CREATE SCHEMA HR_Dept

-- Transfer Objects between Schemas
ALTER SCHEMA HR_Dept
TRANSFER my_Employee.Empinfo

-- Assigning Permission to Schema
GRANT SELECT ON SCHEMA::HR_Dept TO Joydeep


  


Hope you like it.


Posted by: MR. JOYDEEP DAS