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

Saturday, 6 February 2016

Nested Transaction in Sql Server

The variable @@TranCount is used check the count of running transaction(s)

In nested transactions, the variable @@TranCount can be used to check the count of level of nested transactions.

In nested transaction, commit works only on the same level as of transaction (current transaction) i.e. all the statements under that level of transaction will be committed where as rollback always works on parent transaction i.e. all the statements of all the levels will be rolled back.

Rollback reverts all the changes even if any nested transaction was committed.


Example 1 -

SQL Command :

begin tran
print 'Tran Count on level 1st: ' + cast(@@trancount as varchar)
    insert into tbl_Employee_M select 1,'Mohan' 
    begin tran
    print 'Tran Count on level 2nd: ' + cast(@@trancount as varchar)
        insert into tbl_Employee_M select 2,'Sohan'     
    commit tran
    print 'Tran Count after 2nd leve commit : ' + cast(@@trancount as varchar)
rollback tran
print 'Tran Count after 1st level rollback : ' + cast(@@trancount as varchar)
select * from tbl_Employee_M
end tran



Note : Under this example, rollback revert back all transaction event level 2nd transaction is committed.

Example 2 -

SQL Command :

begin tran
print 'Tran Count on level 1st : ' + cast(@@trancount as varchar)
    insert into tbl_Employee_M select 1,'Mohan' 
    begin tran
    print 'Tran Count on level 2nd : ' + cast(@@trancount as varchar)
        insert into tbl_Employee_M select 2,'Sohan'     
    rollback tran
    print 'Tran Count after 2nd leve commit : ' + cast(@@trancount as varchar)
commit tran
print 'Tran Count after 1st level rollback : ' + cast(@@trancount as varchar)
select * from tbl_Employee_M
End tran



Note : Under this example this, it has rolled back all the transaction that is why there is no transaction left to commit.

End Points in Sql Server

A SQL Server endpoint is the point of entry into SQL Server, or a way to connect to SQL Server instance.

Endpoints in SQL Server are similar to Web Services that expose database access over HTTP.
There are 5 system endpoints that are automatically created and that can’t be dropped (you can only start or stop them), one for each protocol
  • TCP/IP
  • Shared Memory
  • Named Pipe
  • VIA
  • One endpoint for the dedicated administrator connection (DAC). 
 SQL Command to see End Points :

Sunday, 16 June 2013

DATA WAREHOUSING & DATA MINING

Data mining is due to the wide availability of huge amounts of data and the approach need for turning such data into useful information and knowledge. The information and knowledge gained can be used for applications ranging from market analysis, fraud detection, and customer retention, to production control and science exploration.Data mining can be viewed as a result of the natural evolution of information technology. The database system in the development of the following functionalities: data collection and database creation, data management (including data storage and retrieval, and database transaction processing), and advanced data analysis (involving data warehousing and data mining).

Evolution of Database Technology

1960s
Data collection, database creation, IMS and network DBMS
            Since the 1960s, database and information technology has been evolving systematically from primitive file processing systems to sophisticated and powerful database systems. The research and development in database systems
1970s
Relational data model, relational DBMS implementation
            Since the 1970s has progressed from early hierarchical and network database systems to the development of relational database systems (where data are stored in relational table structures; data modeling tools, and indexing and accessing methods.
Efficient methods for on-line transaction processing (OLTP).
1980s
RDBMS, advanced data models (extended-relational, OO, deductive, etc.)
   Research and development activities on new and powerful database systems
           Application-oriented DBMS (spatial, scientific, engineering, etc.)
1990s
Data mining, data warehousing, multimedia databases, and Web databases
2000
Stream data management and mining
Data mining and its applications
Web technology (XML, data integration) and global information systems.


Thursday, 24 January 2013

Convert Single Row into Multiple Rows Via Unpivote


Convert Single Row into Multiple Rows Via Unpivote

create table tbl_SingleRow
(
    col1 varchar(5),
    col2 varchar(5),
    col3 varchar(5),
    col4 varchar(5)
)

insert into tbl_SingleRow values ('aaa', 'bbb', 'ccc', 'ddd')

select A,B FROM tbl_SingleRow
unpivot
(
B for A in (col1, col2, col3, col4)
) MultipleRows


Thursday, 3 January 2013

CTE

A common table expression (CTE) can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement.

For Example : -


WITH useOf_CTE(Col1,Col2,Col3,Col4)
as
(
select Col1,Col2,Col3,Col4 from tbl_Table1
)
select * from useOf_CTE


Wednesday, 26 December 2012

Delete Duplicate Rows From Table


If your table become like this


id name salary no

1abc10001
2xyz20002
3pqr30003
4abc10001
5xyz20002
6pqr30003

 then you can remove duplicate row by using T-sql statement


DELETE
FROM  tbl_Duplicate
WHERE ID IN
(
SELECT MAX(ID)
FROM tbl_Duplicate
GROUP BY no
)



Monday, 10 December 2012

Correlated sub-query


A correlated sub-query  is a sub-query that uses values from the outer query in its WHERE clause. The sub-query is evaluated once for each row processed by the outer query.

For Example :-

Select * from EmployeeDetails e
Where Salary = ( Select MAX(Salary) From EmployeeDetails
Where DeptNo = e.DeptNo)

Here if outer query return 10 rows,the inner query will be executed 10 times.

Nested Subqueries

A subquery can contain one or more subqueries. Subqueries are used when the condition of query is dependent on the result of another query, which, in turn,is dependent on the result of another subquery.

For Example :-

Select * from EmployeeDetails
where Salary > /* Level 1 inner query */
(SelectMax(Salary) from EmployeeDetails where DeptNo = /* Level 2 inner query */
(Select DeptNo from DeptDetails where DeptName = 'Admin'))


Wednesday, 5 December 2012

Processing of SQL Statement


Any SQL statement goes through 4 phases..
1) Parsing the syntax of sql statement.
2) Translating to query tree.
3) Develop execution plan.
4) Execute.

Now,
In case "Stored Procedures".
1st & 2nd phase comes once, at creation.
3rd phase comes, if it is not in memory cache.
4th is the only step that runs each time.

Thats why stored procedures are fast, as in this first 2 steps runs only once at the time of creation, and we always says stored procedures are precompiled, then question is what is precompiled, the answer is the execution plan is precompiled i.e. the 3rd step.
Stored procedure contains multiple sql statements, even then it is treated as a single statement and the only step runs that is the execution everytime.

Note:- "Execution Plan" is created when it is not in memory, execution plan is not created on stored procedure compilation but on the first use of stored procedure, and reuse that execution plan on subsequent uses.
That is what i mean to say 3rd step runs when it is not in memory, if it is in memory then skips that step and runs the final step that is "Execution".

Hope will be helpful in understanding "Store Procedure" :)

Nth Min Salary and Nth MAX Salary


Nth Min Salary and Nth MAX Salary

exec usp_tbl_EmployeeSalary_MinMax NthMIN, NthMAX

Create procedure usp_tbl_EmployeeSalary_MinMax
@NthMIN as int,
@NthMAX as int
as
Begin

declare @min as float;
declare @max as float;
--Nth lowest
set @min = (SELECT salary FROM( SELECT id, salary, Row_Number() OVER(ORDER BY salary ASC) AS lowest FROM tbl_EmployeeSalary ) as x WHERE lowest = @NthMIN)

--Nth highest
Set @max = (SELECT salary FROM ( SELECT id, salary, Row_Number() OVER(ORDER BY salary DESC) AS highest FROM tbl_EmployeeSalary ) as x WHERE highest = @NthMAX)


select ID, Name, Salary,
CASE
WHEN Salary = @min
THEN 'Yes'
else 'No'
END as MinSalary,
CASE
WHEN Salary = @max
THEN 'Yes'
else 'No'
END as MAXSalary
from dbo.tbl_EmployeeSalary
End

Tuesday, 27 November 2012

CAST vs CONVERT


CAST function In SQL :-

CAST(expression AS data_type)

CONVERT function In SQL :-

CONVERT(data_type[(length)], expression [, style])

Both CAST and CONVERT are much same..

CONVERT is T-SQL specific, it supports style in case of date-time conversions.

CAST is ANSI specific. ANSI-SQL is more portable across database platforms.

Wednesday, 21 November 2012

System Databases in SQL Server

System Databases in SQL Server


Master: Composed of system tables that keep track of server installation as a whole and all other databases that are eventually created. Master DB has system catalogs that keep info about disk space, file allocations and usage, configuration settings, endpoints, logins, etc.

Model: Template database. Gets cloned when a new database is created. Any changes that one would like be applied by default to a new database should be made here

Tempdb: Re-created every time SQL Server instance is restarted. Holds intermediate results created internally by SQL Server during query processing and sorting, maintaining row versions, etc. Recreated from the model database. Sizing and configuration of tempdb is critical for SQL Server performance.

Resource: Stores executable system objects such as stored system procedures and functions. Allows for very fast and safe upgrades.

MSDB: Used by the SQL Server Agent service and other companion services. Used for backups, replication tasks, Service Broker, supports jobs, alerts, log shipping, policies, database mail and recovery of damaged pages.

Sunday, 4 November 2012

SQL Server CROSS APPLY and OUTER APPLY

Apply Operator In Sql Server

The APPLY operator allows you to join two table expressions; the right table expression is processed every time for each row from the left table expression. As you might have guessed, the left table expression is evaluated first and then right table expression is evaluated against each row of the left table expression for final result-set. The final result-set contains all the selected columns from the left table expression followed by all the columns of right table expression.

The APPLY operator comes in two variants:-
1. Cross Apply
2. Outer Apply

Cross Apply
The CROSS APPLY operator returns only those rows from left table expression if it matches with right table expression.

Outer Apply
OUTER APPLY operator returns all the rows from left table expression irrespective of its match with the right table expression.

Sunday, 29 July 2012

Reporting Services (SSRS)


SQL Server Reporting Services provides a full range of ready-to-use tools and services to help you create, deploy, and manage reports for your organization, as well as programming features that enable you to extend and customize your reporting functionality.

Reporting Services is a server-based reporting platform that provides comprehensive reporting functionality for a variety of data sources. Reporting Services includes a complete set of tools for you to create, manage, and deliver reports, and APIs that enable developers to integrate or extend data and report processing in custom applications. Reporting Services tools work within the Microsoft Visual Studio environment and are fully integrated with SQL Server tools and components.

SQL Server Configuration Manager

SQL Server Configuration Manager is a tool to manage the services associated with SQL Server, to configure the network protocols used by SQL Server, and to manage the network connectivity configuration from SQL Server client computers. SQL Server Configuration Manager is a Microsoft Management Console snap-in that is available from the Start menu, or can be added to any other Microsoft Management Console display. Microsoft Management Console (mmc.exe) uses the SQLServerManager10.msc file in the Windows System32 folder to open SQL Server Configuration Manager.

SQL Server Configuration Manager and SQL Server Management Studio use Window Management Instrumentation (WMI) to view and change some server settings. WMI provides a unified way for interfacing with the API calls that manage the registry operations requested by the SQL Server tools and to provide enhanced control and manipulation over the selected SQL services of the SQL Server Configuration Manager snap-in component. For information about configuring permissions related to WMI, see Configure WMI to Show Server Status in SQL Server Tools.

SQL Server Database Engine Tuning Advisor for Performance Tuning

The Database Engine Tuning Advisor (DTA) is a performance tuning tool that was first available with SQL Server 2005.  DTA replaced the Index Tuning Wizard in previous versions of SQL Server.  In a nutshell DTA analyzes a workload and makes recommendations that will enhance query performance.


There are several ways that you can launch DTA:

Use the Start menu and navigate to the Performance Tools folder in the SQL Server program group.

Select DTA from the Tools menu in SQL Server Management Studio (SSMS).

Select DTA from the Tools menu in SQL Server Profiler.

Select Analyze Query in Database Engine Tuning Advisor on the SSMS Query menu from a query window, allowing you to pass a T-SQL batch to DTA for analysis.

Type DTA from a Command Prompt; add -? to the command line to see the available options.

You typically create a workload by putting together a group of queries in a text file or by running SQL Server Profiler.  The key point to consider is that the workload you pass to DTA for analysis should be representative of the typical workload.  The recommendations are based on what DTA sees in the workload.  If the workload is very limited the recommendations may not be optimal.  Usually the best bet is to capture the workload by running SQL Server Profiler, save the trace to a file, and pass that file on to the DTA.

Tuesday, 24 July 2012

Tuning options for SQL Server 2008

You can use these trace flags to improve the performance of SQL Server. Typically, you use these trace flags when SQL Server is running in high performance workloads. 

Tuesday, 17 July 2012

Create Database Using Manual FileGroup Creation

There are two Filegroups for newly created database :-


Primary File Group - MDF
Secondary File Froup - LDF


Creation of New Database:-



CREATE DATABASE [ DemoTest ] ON  PRIMARY
( NAME =  DemoTest ',
FILENAME = C:\data\ DemoTest .mdf' ,
SIZE = 3072KB , 
FILEGROWTH = 1024KB ),
FILEGROUP [Secondary]
( NAME =  DemoTestSecondry',
FILENAME =   C:\data\ DemoTest2.ndf' ,
SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME =   C:\data\ DemoTestlog',
FILENAME =  C:\data\ DemoTest Log.ldf' ,
SIZE = 1024KB , FILEGROWTH = 10%)
GO


To use this query you must have data folder in your c drive or you can also specify your own database database folder.



Monday, 16 July 2012

Excel Data Import to SQL Server

Microsoft.Jet.OLEDB.4.0


SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=E:\demo.xls', [Sheet1$])

SELECT * FROM OPENDATASOURCE('Microsoft.Jet.OLEDB.4.0','Data Source=E:\demo.xls;Extended Properties=Excel 8.0')...[Sheet1$]

Microsoft.ACE.OLEDB.12.0


SELECT * FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;Database=E:\Demo.xlsx', [Sheet1$])

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0','Data Source=C:\Demo.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]

Thursday, 5 July 2012

Tracing a SQL Server Deadlock

Deadlock information can be captured in the SQL Server Error Log or by using Profiler / Server Side Trace. If you want to capture this information in the SQL Server Error Log you need to enable one or both of these trace flags.
1.  1204 - this provides information about the nodes involved in the deadlock
2.  1222 - returns deadlock information in an XML format


You can turn on each of these separately or turn them on together.

To turn these on you can issue the following commands in a query window or you can add these as startup parameters.  If these are turned on from a query window, the next time SQL Server starts these trace flags will not be active, so if you always want to capture this data the startup parameters is the best option.


Deadlocking occurs when two or more SQL Server processes have locks on separate database objects and each process is trying to acquire a lock on an object that the other processes have previously locked.  For example, process one has an exclusive lock on object one, process two has an exclusive lock on object two, and process one also wants an exclusive lock on object two, and object two wants an exclusive lock on object one. Because two processes can’t have an exclusive lock on the same object at the same time, the two processes become entangled in a deadlock, with neither process willing to yield of its own accord.

Since a deadlock is not a good thing for an application, SQL Server is smart enough to identify the problem and ends the deadlock by choosing one process over another. It does this by killing one of the processes (usually the process that has used the least amount of server resources up to this point) and lets the other one to continue to run. The aborted transaction is rolled back and an error message is sent to the application. If the application is deadlock aware, it will resubmit the killed transaction automatically and the user may never know the deadlock happened. If the application is not deadlock aware, then most likely an error message appears on the application’s screen and you get a call from a disgruntled user. Besides irritating users, deadlocks can use up SQL Server's resources unnecessarily as transactions are killed, rolled back, and resubmitted again.


-- Activate deadlock tracing
dbcc traceon (1204, 3605, -1)
go
dbcc tracestatus(-1)
go

-- Deadlock simulation - CONNECTION (session) 1
USE AdventureWorks;
WHILE ( 1< 2)
BEGIN
      BEGIN TRANSACTION
            UPDATE Sales.SalesOrderHeader SET ModifiedDate=ModifiedDate
            UPDATE Purchasing.PurchaseOrderHeader SET ModifiedDate=ModifiedDate
      COMMIT TRANSACTION
END

-- Deadlock simulation - CONNECTION (session) 2
USE AdventureWorks;
WHILE ( 1< 2)
BEGIN
      BEGIN TRANSACTION
            UPDATE Purchasing.PurchaseOrderHeader SET ModifiedDate=ModifiedDate
            UPDATE Sales.SalesOrderHeader SET ModifiedDate=ModifiedDate
      COMMIT TRANSACTION
END
/* Messages

(4000 row(s) affected)
Msg 1205, Level 13, State 56, Line 7
Transaction (Process ID 60) was deadlocked on lock resources with another
process and has been chosen as the deadlock victim. Rerun the transaction.

*/

/* SQL Server ERROR LOG
2019-03-02 05:44:58.59 spid55      DBCC TRACEON 1204, server process ID (SPID) 55. This is an informational message only; no user action is required.
2019-03-02 05:44:58.59 spid55      DBCC TRACEON 3605, server process ID (SPID) 55. This is an informational message only; no user action is required.
2019-03-02 05:45:48.09 spid4s      Deadlock encountered .... Printing deadlock information
2019-03-02 05:45:48.09 spid4s      Wait-for graph
2019-03-02 05:45:48.09 spid4s  
2019-03-02 05:45:48.09 spid4s      Node:1

2019-03-02 05:45:48.12 spid4s      OBJECT: 6:402100473:0          CleanCnt:3 Mode:X Flags: 0x0
2019-03-02 05:45:48.12 spid4s       Grant List 1:
2019-03-02 05:45:48.12 spid4s         Owner:0x10195FA0 Mode: X        Flg:0x0 Ref:3 Life:02000000 SPID:62 ECID:0 XactLockInfo: 0x2A4CCD0C
2019-03-02 05:45:48.12 spid4s         SPID: 62 ECID: 0 Statement Type: UPDATE Line #: 7
2019-03-02 05:45:48.12 spid4s         Input Buf: Language Event: -- Deadlock simulation - CONNECTION (session) 2
USE AdventureWorks;
WHILE ( 1< 2)
BEGIN
      BEGIN TRANSACTION
            UPDATE Purchasing.PurchaseOrderHeader SET ModifiedDate=ModifiedDate
            UPDATE Sales.SalesOrderHeader SET ModifiedDate=ModifiedDate
      COMMIT T
2019-03-02 05:45:48.12 spid4s       Requested By:
2019-03-02 05:45:48.12 spid4s         ResType:LockOwner Stype:'OR'Xdes:0x2A4CC250 Mode: IX SPID:55 BatchID:0 ECID:0 TaskProxy:(0x189CA378) Value:0x16bb9420 Cost:(0/6371044)
2019-03-02 05:45:48.12 spid4s  
2019-03-02 05:45:48.12 spid4s      Node:2

2019-03-02 05:45:48.12 spid4s      OBJECT: 6:722101613:0          CleanCnt:2 Mode:X Flags: 0x0
2019-03-02 05:45:48.12 spid4s       Grant List 1:
2019-03-02 05:45:48.12 spid4s         Owner:0x101A9940 Mode: X        Flg:0x0 Ref:14 Life:02000000 SPID:55 ECID:0 XactLockInfo: 0x2A4CC274
2019-03-02 05:45:48.12 spid4s         SPID: 55 ECID: 0 Statement Type: UPDATE Line #: 6
2019-03-02 05:45:48.12 spid4s         Input Buf: Language Event: USE AdventureWorks;
WHILE ( 1< 2)
BEGIN
      BEGIN TRANSACTION
            UPDATE Sales.SalesOrderHeader SET ModifiedDate=ModifiedDate
            UPDATE Purchasing.PurchaseOrderHeader SET ModifiedDate=ModifiedDate
      COMMIT TRANSACTION
END
2019-03-02 05:45:48.12 spid4s       Requested By:
2019-03-02 05:45:48.12 spid4s         ResType:LockOwner Stype:'OR'Xdes:0x2A4CCCE8 Mode: IX SPID:62 BatchID:0 ECID:0 TaskProxy:(0x19F2A378) Value:0x1019ba20 Cost:(0/800164)
2019-03-02 05:45:48.12 spid4s  
2019-03-02 05:45:48.12 spid4s      Victim Resource Owner:
2019-03-02 05:45:48.12 spid4s       ResType:LockOwner Stype:'OR'Xdes:0x2A4CCCE8 Mode: IX SPID:62 BatchID:0 ECID:0 TaskProxy:(0x19F2A378) Value:0x1019ba20 Cost:(0/800164)

*/

-- Turn off deadlock tracing
dbcc traceoff (1204, 3605)
go