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

Sunday, July 13, 2014

Stored Procedures Make things Better

Stored Procedures are a set of SQL(T-SQL) statements that compiled in to single execution plan. Think it like Method in Class the method is stored procedure and Class is Database

Benefits of Stored Procedures

 1. Increase Program performance
 Stored procedures are compiled only once and stored it as executable form and that executable cached and shared among all users.Stored procedures execute within a single call even though it has many SQL statements in the body.

2. Interoperability
If you work with stored procedure you don't need to change lot of code lines to make it functional.Stored procedure call is just enough. Each of modern languages have specific libraries for calling stored procedures

3. Security
You can restrict the data access in database with stored procedures. Ex: Just only for read.

4. Scalability
Stored procedures increase scalability by isolating application processing on the server. In addition, automatic dependency tracking for stored procedures aids the development of scalable applications.

5.  Maintainability
Once it is validated, a stored procedure can be used with confidence in any number of applications. If its definition changes, only the procedure is affected, not the applications that call it. This simplifies maintenance and enhancement. Also, maintaining a procedure on the server is easier than maintaining copies on various client machines.  


Stored Procedure Outputs

Stored procedures can return data or cursor values . Return codes in stored procedure always returns integer values and cursor can reference to out side . And there is return data sets for select statement results.

Lets Work on it

I'm working on local database file that attached with my project in Visual studio. Bit there is no difference between SQL Server procedure creation and Procedure creation in Visual studio.

You can add your own SQL Server database to the project.
CTRL+SHIFT+A -> Data->SQL Server Database

Here is tables that I'm going to working on

CREATE TABLE [dbo].[PurchaseHistory] (
    [Id]        INT              IDENTITY (1, 1) NOT NULL,
    [UserId]    UNIQUEIDENTIFIER NOT NULL,
    [AlbumId]   INT              NOT NULL,
    [Units]     INT              DEFAULT ((0)) NOT NULL,
    [Buydate]   DATETIME         DEFAULT (getdate()) NOT NULL,
    [Payed]     BIGINT           DEFAULT ((0)) NOT NULL,
    [PayedDate] DATETIME         NULL,
    [Total]     FLOAT (53)       DEFAULT ((0.00)) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[Users] (
    [ApplicationId]    UNIQUEIDENTIFIER NOT NULL,
    [UserId]           UNIQUEIDENTIFIER NOT NULL,
    [UserName]         NVARCHAR (50)    NOT NULL,
    [IsAnonymous]      BIT              NOT NULL,
    [LastActivityDate] DATETIME         NOT NULL,
    PRIMARY KEY CLUSTERED ([UserId] ASC),
    CONSTRAINT [UserApplication] FOREIGN KEY ([ApplicationId]) REFERENCES [dbo].[Applications] ([ApplicationId])
);
CREATE TABLE [dbo].[Albums] (
    [AlbumId]        INT           IDENTITY (1, 1) NOT NULL,
    [AlbumName]      VARCHAR (255) NOT NULL,
    [ImageSource]    VARCHAR (50)  NOT NULL,
    [Artist]         VARCHAR (255) NOT NULL,
    [Price]          MONEY         NOT NULL,
    [Description]    VARCHAR (MAX) NOT NULL,
    [Tracks]         INT           NULL,
    [Label]          INT           NOT NULL,
    [OrigYear]       INT           NULL,
    [AdditionalInfo] VARCHAR (550) NULL,
    [Rating]         INT           NULL,
    PRIMARY KEY CLUSTERED ([AlbumId] ASC)
);

And make sure your tables containing data to test our procedures

Expand your database objects from Server explorer and R-Click on the stored procedures and select Add New Stored procedure
























If you working on SQL Server Add New Stored Procedure is on Programability->Stored Procedures 





















Here is my requirement is create procedure that returns all unpayed purchases from PurchaseHistory by selected user with Album details. This selected user will indicate by user input from outside. It will take userName as parameter

If we took it as function its like this
List<Object> Procedure(string UserName)

Here is Procedure for it. My procedure name is GetAllCartProcedure

CREATE PROCEDURE [dbo].[GetAllCartProcedure]
    @UserName varchar(255)
AS
    BEGIN
        DECLARE @UserId uniqueidentifier
        DECLARE @Total money
        --select userId from the user table to make connection between Purchase history
        SELECT @UserId=(UserId) FROM Users WHERE UserName=@UserName
        --Select all purchases that not payed by selected User
        SELECT
            Albums.AlbumName,'Images/AlbumImages/'+Albums.ImageSource,Albums.Price,
            PurchaseHistory.Buydate,PurchaseHistory.Units,PurchaseHistory.Total
        FROM Albums,PurchaseHistory
        WHERE
            Albums.AlbumId=PurchaseHistory.AlbumId
            AND
            PurchaseHistory.UserId=@UserId
            AND
            PurchaseHistory.Payed=0         
    END
RETURN

After procedure created you ca test the procedure on R-Click on the created procedure











It will prompt this dialogbox and give the relevent parameters to the prompt and check














Or Use T-SQL
USE [aspnet-E commerce-20140712191038]
GO
DECLARE @return_value Int
EXEC    @return_value = [dbo].[GetAllCartProcedure]
        @UserName = 'UseName'
SELECT  @return_value as 'Return Value'
GO

Here is result













You can access those stored procedures easily with entity framework and ADO.NET libraries. Use those with those and make better code..




Friday, July 26, 2013

Data Replication with SQL Server 2012

Replication is the process of copying and maintaining database objects in multiple databases that make up a distributed database system. Changes applied at one site are captured and stored locally before being forwarded and applied at each of the remote locations. Replication provides user with fast, local access to shared data, and protects availability of applications because alternate data access options exist. Even if one site becomes unavailable, users can continue to query or even update the remaining locations.

In SQL Server 2012 Management Studio you can create replication very simply. Replication makes your database more secure and effective

Here the steps ,
1.  Log on to the database server and R-click on the Replication folder and select new publication
 
2. In new publication click next.
3. Select distributor  that can be responsible for storing replication info. I don't have any other servers I select default server in my desktop


4. In SQL Server Agent  select whether SQL Server agent should start automatically or not  then click next

5. Then it will displays snapshot folder.

6. Then select database that you want to replicate. After that it prompt select Publication type to replicate your database.  For each publication type preview window in bottom will show discription about each of them. Select it as you want and click next.

7. Then in Articles we can choose objects to publish in replication. then click next

8. Add data filters if you need. then click next in the prompt
9. Schedule snapshot agent as you want. It will give you time bounded option as well.
10. In Agent security add snapshot agent. I choose SQL Server agent account and finally click finish. and add publication name in prompt.




Its done..


Tuesday, April 30, 2013

READTEXT in T-SQL (SS2012)

This statement use to read text, ntext, or image values from a text, ntext, or image column, starting from a specified offset and reading the specified number of bytes.
Parameters of statement


  • table.column
Is the name of a table and column from which to read. Table and column names must
comply with the rules for identifiers. Specifying the table and column names is required;
however, specifying the database name and owner names is optional.

  • text_ptr
Is a valid text pointer. text_ptr must be binary(16).

  • Offset
Is the number of bytes (when the text or image data types are used) or characters
(when the ntext data type is used) to skip before it starts to read the text, image, or
ntext data.

  • Size
Is the number of bytes (when the text or image data types are used) or characters
(when the ntext data type is used) of data to read. If size is 0, 4 KB bytes of data is
read.

  • HOLDLOCK
Causes the text value to be locked for reads until the end of the transaction. Other
Users can read the value, but they cannot modify it.

Thursday, February 14, 2013

Document Oriented Database

        Designed for storing, retrieving, and managing document-oriented, or semi structured data, information. Document-oriented databases are one of the main categories of so-called NoSQL databases and the popularity of the term "document-oriented database" (or "document store") has grown with the use of the term NoSQL itself. In contrast to well-known relational databases and their notions of "Relations" (or "Tables"), these systems are designed around an abstract notion of a "Document".           
 At the highest level of organization, it is quite similar to a relational database, but as you get closer to the data itself, you will notice a significant change in the way the data is stored. Instead of databases, tables, columns, and rows you have documents. A document doesn’t have a direct correlation in the relational world. Documents do not have a predefined schema like relational database tables. A document is partly a row, in that it’s where the data is located, but it's also part columns, in that the schema is defined in each document (not table-wide).

          The best way to think of a document is as a multidimensional array. In an array, you have a set of keys that map to values. The values could themselves be another array. Documents map extremely well to objects and other PHP data types like arrays and even multidimensional arrays. Documents encapsulate and encode data (or information) in some standard formats or encoding. Encoding in use include XML, YAML, JSON, and BSON, as well as binary forms like PDF and Microsoft Office documents.
           Currently lot of web based online shopping websites are moving to this kind of databases. Simple and amaizing handling with database solutions like MongoDB, Apache CouchDB , Clusterpoint etc

Sunday, January 20, 2013

Create Database Snapshot

CREATE DATABASE statement can also be used to create database snapshots of existing databases.

Database snapshot is a read only static view of a SQL Server database.Snapshot is transitionally consist with the source database as of the snapshot creation. A database snapshot always resides on the same server instances as it source database. As the source database updates the snapshot is updated.
In database snapshot creation in CREATE DATABASE statement we have to add AS SNAPSHOT OF clause in CREATE DATABASE statement others  are same as general CREATE DATABASE statement.   ( CREATE DATABASE )

Sample code :- 

Create Database in SQL Server 2012

  This example query create table named as db_name  in this case I omitted PRIMARY option and the first file is assumed as a primary file.The logical name of this file is DB_data as I mentioned in query. File name parameter is for specify physical location for the database file. db.mdf in Local disk D:  in my hard drive.

The original size of this file is 10MB ,Additional 20MB from disk may allocated by the system if it needed(FILEGROWTH).
If MAXSIZE option is not specified or it set to unlimited the file will dynamically use all space in disk as it grows.

If you need to use single transaction log file with specific logical name and destination you can use it as follows. parameters are specified are uses as same in ON category.


Full Query for create Database statement
 



Thursday, January 10, 2013

Policies Management In SQL Server

New SQL Server versions upgrade with new Declarative Management Framework (DMF) which policy based system managing one or more server instances, Databases or other Database objects called managed targets. A policy is a DMF condition together with the corresponding behavior and it can contain only one condition.

First before create policy we must have to create condition for policy.
Open SQL Server Management studio  and expand Policy Management 
  • R-Click on the condition and select New Condition
  • In wizard type condition name and choose facet that you need.In my case I want to apply this condition to all server instances therefore I choose Server Configuration from drop down menu.
  • In field select that field that you want and operator  and value as you wish.Or else you can use variable as a value. Click Ok  and create condition.

Now go to the Policies folder in Policy Management
  1. R-click Policies and select New Policy
  2. Type name and select condition from drop down Menu.
  3. In evolution field select on demand (in My Case) and make other fields as it is on default. and clock OK

To test the policy
Expand the Policy Folder and select policy that we created and Evaluate policy(In SQL Server 2008 and previous select Run now) The dialog box notifies you whether the policy fails for existing DB's.

Tuesday, January 8, 2013

Introdiuction to Query Optimizer

     In Practical case most of the DBE's can not find the query that optimized execution process of the query.
          The question that arises when database Engine executes a query is how the data that is necessary for the query can be accessed and process most efficient manner. The component of the Database Engine that responsible for such  thing called query optimizer.
           The task of the query optimizer is to consider variety of possible execution strategies for querying the data relation to given query and select most efficient strategy for executing and it is called execution plan. The optimizer make its decisions using considerations such as How big the tables are that involved with the query and what indices exist, What Boolean operations are use in WHERE closes like statistics. There are different tools that can edit query optimize in SQL Server. We will discuss that in later posts.

Monday, January 7, 2013

Requirements for Database Security

security
Ever since, men had learned and concentrated on ways on how they could protect their files and documents even before computers ever existed. Today, now that most documents are files are saved in computers, while some other important data are usually located in the company's database, men wanted to make sure that they'll practice security and ensure that all of their business' files and data are kept secured - this is the reason why database security and network security services are usually being sought, along with some security tools that could further help them keep their files and documents safe and secured at all times. As a database administrator we have to think about several requirements of database for security implementations.

Physical Database Integrity :- The data in database are directly relate with the physical (external) factors of the Database Server such as Power failures, Some one can drop the database from database server or any hardware damages in database server.

Logical Database Integrity :- The structure of database, If some of elements are changed in one field and it should not be affected to the other fields in database.

Element Integrity :- Each element which data is contained must be accurate.

Auditability :- Must possible to track who accessed or modified data in the Database.

Access Control :- Authorized users only have to access the certain set of data.( restrict read and write ability of data to different users as application behave)

User Authentication :- Every user must correctly identified for audit and access control.

Availability :- If user have permission to access certain data it must be available of user.

Thursday, October 18, 2012

Classification


      Classifications are the internal rules that classify the incoming requests and route them into a workload groups. This classification is based on set of user defined function called classifier function. This classifier function will be created in master database. Once DBA enables the resource governor on SQL Server Then each and every single session to the server will be evaluated by the classifier function. It can evaluate various login properties.

  • USER_NAME
  • HOST_NAME
  • WORKSTATION_NAME
  • DB_NAME
  • SUSER_SNAME