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

Sunday, 20 May 2012

SQL 2008 Transaction

What Is a Transaction?
A transaction may be a single operation or collection of different operations that succeed or fail together as a whole, thereby ensuring consistency of data should unexpected situation arise. One scenario might be a financial transaction. For example, let's say you buy a car. The single transaction of purchasing item from online store a consists of distinct operations as below:
1.       Select a product.
2.       Select the payment mode.
3.       Enter credential for payment.
4.       Payment transferred
5.       Product ship to customer address.
Skipping any of these steps could cause major angst to one or more of the parties involved. This is a simple example of a set of steps that must always occur together in a consistent manner.
Transactions allow us to ensure consistency in our data through four basic principles. These principles provide a set of rules that must be followed for our transaction to succeed. The four principles help ensure that the state of our data is atomic, consistent, isolated, and durable, regardless of the success or failure of the transaction.

Acid Property

Consider the transaction of purchasing product using debit card to purchase a product worth $200. The data for this transaction can be easily represented in a database as a table with two columns, one holding your AccountID and the other holding your AccountBalance.
To begin with, consider your account balance is $200, so after withdrawing $200, your updated balance should be zero. Also, it makes logical sense that the system must ensure that you have the funds available in your account before the cash can be dispensed. What this means in database terms is that two database queries must be run in this transaction. The first query checks the account balance, as shown here:

SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

If the query returns an AccountBalance value greater than or equal to the requested withdrawal, you can withdraw the cash.
After withdrawing the cash, you must update the account record with the updated balance. To do so, you run an UPDATE query:


UPDATE Account
 SET AccountBalance = AccountBalance – 100
 WHERE AccountID = @AccountID

The two distinct operations in this transaction are the two database queries that support the one operation of withdrawing cash. Both must succeed or fail together in an atomic manner, or the transaction should not be considered complete. Atomicity is the first ACID property.
Now let's change the nature of the transaction a bit. Let's say that the original account balance is $250 and that within the same transaction, the user requests to withdraw $200 and to purchase another product worth $75 to a second account. The first update query will succeed, changing the account balance to $250 – $200 = $50. But the second operation will fail because there won't be enough money left in the account to purhcaser the $75. You therefore need a way to undo the cash withdrawal and return the database to its original state. You cannot leave the database midway through a transaction because it is in an inconsistent state. In a real-world scenario, you would not normally wrap a withdrawal and a transfer in the same transaction, but the point here is to show how data can end up in an inconsistent state between multiple operations. Rolling back operations that cannot be completed in this manner demonstrates the second ACID property, consistency.
Let's say now that the withdrawal and transfer operations are separated into two distinct transactions instead of one but that they happen to run simultaneously. Each transaction will have to check the current balance by attempting to execute a query like this:


SELECT AccountBalance FROM Account WHERE AccountID = @AccountID

Unless your system has explicit checks blocking concurrent reads, both transactions will get the same result: $250. Thus they will both assume that the account has enough funds for the transaction. One transaction will disburse $200, and the other will transfer $75. The result will be an overall deduction of $200 + $75 = $275, even though the account actually has only $250 available. In many systems, especially financial applications, such transactions must be isolated from each other to prevent what is known as a "dirty read." A dirty read happens when data is read at one point in a transition state and the result of the query doesn't reflect the data's true state at the end of the current operation. This brings us to the third ACID property, isolation.
Isolation means that other transactions attempting to request a common resource will be blocked. Blocking, in turn, seriously affects the response times of your application. As it turns out, you'll often want to relax this blocking behavior to suit your application architecture. You can do that by using isolation levels, which we'll discuss later in this chapter.
Last, when you have successfully completed all your operations within a transaction, you don't want to lose the changes made. In other words, system failures must not affect the transactional integrity of your operations. This brings us to the fourth ACID property, durability. Durability means that the systems involved with the transaction will faithfully retain the correct transacted state even if the system sustains catastrophic failure nanoseconds after the transaction completes. Conversely, if the transaction isn't completed because of system failure, it won't be allowed to complete (or be undone) until the system is reset and the application restarted. Transacted steps are retained, and the application can resume operations where it left off with no ill effects (at least from a data consistency perspective).
Let's summarize the four ACID properties before we continue:
  • Atomicity Operations succeed or fail together. Unless all steps succeed, the transaction cannot be considered complete.
  • Consistency Operations leave the database in a consistent state. The transaction takes the underlying database from one stable state to another, with no rules violated before the beginning or after the end of the transaction.
  • Isolation Every transaction is an independent entity. One transaction will not affect any other transaction that is running at the same time.
  • Durability Every transaction is persisted to a reliable medium that cannot be undone by system failures. Furthermore, if a system failure does occur in the middle of a transaction, either the completed steps must be undone or the uncompleted steps must be executed to finish the transaction. This typically happens by use of a log that can be played back to return the system to a consistent state.

Tuesday, 15 May 2012

SQL To find tables which contain a particular column


In some case we might need to find the table name that uses a specific columns like ID’s column that are used across several tables in database and we won’t be able to navigate to all the tables to identify the column and its table so the below query solve the issue.


SELECT s.name AS [Table Name] FROM SYSOBJECTS s
INNER JOIN SYSCOLUMNS sc
ON s.id = sc.id
WHERE sc.name LIKE '<column name>'

Thursday, 10 May 2012

SQL to find dependant tables and columns of Stored Procedures present in a database

The below sample code will help to find the depended tables and columns available in the stored procedure.  The stored procedure names are retrieved from sys.object and passed to the cursor. Using sp_depends the depended tables and columns can be retrieved.

BEGIN TRY
Create Table #temp(spname varchar(100),name varchar(150),[type] varchar(150), updated varchar(40),selected varchar(40), [column] varchar(200))


Declare @TempCur varchar(100)
Declare @Temp varchar(100)
Declare @getTemp cursor
Set @getTemp = cursor for
Select Top 245 name from sys.objects where type='p'  

Open @getTemp
Fetch Next
From @getTemp INTO @TempCur
While @@FETCH_STATUS = 0
Begin           
            Set @Temp = @TempCur  
Create Table #temp1(name varchar(150),[type] varchar(150), updated varchar(40),selected varchar(40), [column] varchar(200))
     
Insert Into #temp1
      EXEC Sp_depends @TempCur
       
            Insert Into #temp
Select @TempCur, Replace(name,'dbo.',''),[type],updated,selected,[column]  From #temp1
     
      Drop Table #temp1
     
            Fetch Next
            From @getTemp Into @TempCur
   End
Close @getTemp
Deallocate @getTemp
     
Select * from #temp order by spname
Drop Table #temp
     
END TRY
BEGIN CATCH
Drop Table #temp
END CATCH

Monday, 7 May 2012

SQL Text Substring


The below example show a very simple example for getting substring from a string based a character within a string

DECLARE @val VARCHAR(100)
DECLARE @CHARINDEX INT
SET @val = 'abcsdfsertdbhfbcxvbdsfgsdfgdfg(efg)'
SELECT @CHARINDEX=CHARINDEX('(',@VAL)
SELECT @CHARINDEX
SELECT SUBSTRING (@val,1,@CHARINDEX-1)


The input value : abcsdfsertdbhfbcxvbdsfgsdfgdfg(efg)
The output value: abcsdfsertdbhfbcxvbdsfgsdfgdfg(

Thursday, 3 May 2012

SQL Geospatial Data Types


Geospatial Data Types is a new data type available in MS SQL server 2008. This is feature is so useful to store the information such as to store and manipulate shapes, sizes, and locations using the new geometry and geography data types. It is so helpful in calculating areas, distances, and intersections above that spatial data. SQL Server 2008 is designed specifically to enable the rapid development of application for spatial capabilities in database without requiring deep knowledge of how to program spatial calculations

For eg, this feature is so useful for user to find a nearest gas station from the user current geographic location, similarly we can use this data type for different application based on the user requirement.

Types of Spatial Models
There are two types of Spatial Models in SQL server. They are Planar (Flat-Earth) Model and Geodetic (Round-Earth) Model.

Planar (Flat-Earth) Model: It is specifically designed for the 2-Dimensional geometric figures especially an object in a 2-D plane like world map in an atlas book. Normally the 2-D are represented by (X,Y ) Coordinates. This is so useful to find the distance, area, perimeter of any surface.

Geodetic (Round-Earth) Model: It is specifically designed for the 3-Dimensional geometric figures especially like a world globe. Normally the 3-D are represented by latitude and longitude points in world.

DataTypes
  •    The geometry data type is provided to store and process spatial data for the planar (flat-earth) model. 
  •     The geography data type is provided to store and process spatial data for the geodetic (round-earth) model.

Shapes are projected onto spatial models using vector objects which are collections of points, lines, and polygons (closed shapes). Both the geometry and geography data types support the same Well-Known Text (WKT) markup language, which is a convention that expresses the vector objects.

WKT String
Description
POINT(1,9)
A single point at xy-coordinates 1, 9
POINT(-4.06  5.08)
A single point on the earth (longitude/latitude coordinates)
LINESTRING(1 5,11 55,10 15)
A two-part line, drawn between three points specified as xy-coordinates
POLYGON((

-7.17031 3.95601, -7.16786 3.95778, -7.17921 3.96874, -7.18441 3.96512, -7.17031 3.95601))
An enclosed shape on the earth drawn between the points specified as longitude/latitude coordinates

Geometry Example
The below sample example show how to define geometry data type for City table.


CREATE TABLE City
 (CityId    int PRIMARY KEY,
  CityName  nvarchar(20),
  CityGeo   geometry)

INSERT INTO City VALUES (1, 'New york',
 geometry::Parse('POLYGON ((0 0, 150 0, 150 150, 0 150, 0 0))'))

Geography Example 
To create a map of occurrences of event in different locations across different area is represented by using geography example.

CREATE TABLE EventRegion
 (RegionId    int PRIMARY KEY,
  RegionName  nvarchar(32),
  MapShape    geography)
 
INSERT INTO EventRegion VALUES (1, 'Suite 203', geography::Parse('POLYGON((-7.17031 3.95601, -7.16786 3.95778, -7.17921 3.96874,
 -7.18441 3.96512, -7.17031 3.95601))'))

Wednesday, 2 May 2012

SQL Server Exceptional Handling


The exceptional handling in SQL is so simple after SQL server 2005 version. By using a simple try catch statement as we do in VB.net. Even the syntax looks so similar to that of VB.net program.

Syntax:

Begin Try
Begin Transaction
   //Your Code
Commit Transaction
End Try
Begin Catch
Rollback Transaction
End Catch

The SQL script execute without any issues if everything goes fine within Try block and if there is any error occurs it will go to Catch block and rollback the executed script. This is so useful for DML script execution and Stored Procedures which perform DML operation.

To trap the error in the catch block we can use below built in functions available in the SQL
  • ERROR_NUMBER() - returns the number of the error.
  • ERROR_SEVERITY() - returns the severity.
  • ERROR_STATE() - returns the error state number.
  • ERROR_PROCEDURE() - returns the name of the stored procedure or trigger where the error occurred.
  • ERROR_LINE() - returns the line number inside the routine that caused the error.
  • ERROR_MESSAGE() - returns the complete text of the error message.


Example:

Begin Try
Begin Transaction
Insert into test_table values (key,Foreign_key,textvalue1, textvalue2)
Commit Transaction
End Try
Begin Catch
Rollback Transaction
         Print “Error Number:” + ERROR_NUMBER ()
         Print “Error Message:” + ERROR_MESSAGE ()
End Catch

If there is any foreign key violation while inserting the value it will throw the below error.

Error Number:  1
Error Message:  Foreign key violation while inserting record into test_table record.

Sunday, 29 April 2012

SQL Execute SP using output parameters


In SQL when we think only function can return value that is not at true. Even stored procedure can return value using out parameters. Out parameter are so useful in stored procedure for returning values. It can be performed by introducing OUT keyword in the parameter list in an SP.

Consider this below sample example,

Stored Procedure
CREATE PROCEDURE Get_Customer_Order @orderID  INT, @customerName VARCHAR(100) OUTPUT
AS
SELECT customerName FROM CustomerOrderDetail
WHERE
OrderID = @orderID  

Execution
DECLARE @Name varchar(100)
Exec Get_Customer_Order 178623300, @Name OUT
Print @Name