Thursday, March 4, 2010

The purpose of Transaction Log

We all know that all DDL and DML changes are logged in Transaction log. But when I ask a question that what is the primary purpose of Transaction log in SQL Server then the most common answers that I get are following:

·         For Transaction log backup.

·         For Transactional Replication, Log shipping or Mirroring.

As we know these two features can not be implemented in SIMPLE recovery model but transaction log is still maintained in this recovery model. This indicates that even these features use transaction log but these are not the prime purpose of Transaction log.

The primary purpose is Rollback & Recovery.

We all know that reversing the changes is called Rollback in SQL Server. This is the process to keep the database consistent and integrated. Transaction is the unit of action and either all statements of a transactions complete successfully or none.  

So what is Recovery? Recovery includes two steps: Redo and Undo. In Redo all changes of completed transactions, after the last checkpoint are updated in data pages. In Undo process all changes of uncompleted transactions up to last checkpoint are rolled back.

Recovery is performed on a database in two cases:

1.       While starting the database when SQL Server starts

2.       While restoring the database.

The recovery process while restoring a database can be paused for later time by using NORECOVERY option in RESTORE DATABASE or RESTORE LOG command.

Wednesday, February 24, 2010

Find who dropped, created or altered the table, SP or any object

If any database object is dropped, created or altered accidently, sometimes you may need information about:

Who dropped, created or altered the object? When culprit not accept the mistake.

When the object was dropped, created or altered? Especially drop time of table is required for point in time recovery from database backups.

These changes are not recorded in SQL Server Error Log but are recorded in default trace. If you have not disabled the default trace and started looking into the issue soon after change occurred you could get this information. The path of trace file is “C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\”. The folder MSSQL10.SQLEXPRESS may be different according to your SQL Server instance name. Here you would find 5 profiler trace files named as “log_1”, “Log_2”, etc. The file number is increased by time (in following example I used “log_16.trc”). Find the file that is most recently modified and use the below t-sql query to open that file:

SELECT ObjectName, DatabaseName, StartTime, NTDomainName, HostName, NTUserName, LoginName

FROM fn_trace_gettable('C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Log\log_16.trc', default)

WHERE objectname is not null  

You would get the output as shown below:

image

Search the contents of SSIS packages

SSIS packages that are deployed to SQL Server or SSIS package Store are stored in msdb..sysdtspackages90 table. Not only SSIS packages but the Maintenance plans are also stored in this table.

Now suppose you are asked to list out all SSIS packages and Maintenance plans:

That update dbo.Sales table (to check dependency of a table).

That use the script file located at “D:\FTP\” folder (to check dependency of a file).

Those fetch data from database SourceDB or use login UserA (to check dependency of a source or user).

If you have not more than a dozen packages than you can check by opening each one in BIDS but if there are hundreds of packages than this approach is a very troublesome.

The better approach is to list all packages in which the particular table, connection or login is used. That would shorten the list of packages that you need to open for more details. For this purpose you can use the msdb..sysdtspackages90 table as below:

 

SELECT [name] 

FROM msdb..sysdtspackages90

WHERE CONVERT(VARCHAR(MAX), CONVERT (VARBINARY(MAX), packagedata))

      like '%dbo.Sales%' --change the literal for your search

Tuesday, February 23, 2010

Some unknown facts about Update (U) lock

You may have read and found the following statement type – lock type relation easy to understand and logical too:

SELECT – Shared (S)

UPDATE – Update (U)

INSERT & DELETE – Exclusive (X)

 

I was clear about the shared (S) and exclusive (X) but not about update (U) lock. Some of my questions about update lock were following:

Is it used only while updating a record or while deleting the record too?

As update (U) lock is converted to exclusive (X) lock then how long update (U) lock persist on a row?

 

To get the answer of these questions I did some analysis and I concluded that work in following points:

1.   Update lock is used not only with UPDATE statements but also with DELETE statements.

2.       Update lock is used only if a transaction wants to update or delete a record that is already locked (S) by another transaction. Otherwise direct X lock is used. In READ UNCOMMITTED isolation level, no shared (S) lock is used so update (U) lock can never be found in GRANT status (in sp_lock output). We can only find it in WAIT status.

3.       Update lock is “Waiting exclusive lock”. So we can never find an exclusive (X) lock in WAIT status (in sp_lock output) because in that case update (U) lock is used.

Please let me know your analysis and review.

Sunday, February 21, 2010

How to start and stop windows service from SSIS

To start or stop a windows service from SSIS package add a Script Task and in design script page use the below code. Replace the ComputerName and ServiceName accordingly.
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports System.ServiceProcess
Public Class ScriptMain
      Public Sub Main()
        Dim controller As New ServiceController
        Dim serviceStatus As ServiceControllerStatus
        Dim conter As Integer
        'Code below is to atop Window services.
        controller.MachineName = "ComputerName"
        controller.ServiceName = "ServiceName"
If ((controller.Status.Equals(serviceStatus.Running)) Or (controller.Status.Equals(serviceStatus.Paused))) Then
            controller.Stop()
            controller.Refresh()
      End If
        'Code below is to start Window services.
If ((controller.Status.Equals(serviceStatus.Stopped)) Or (controller.Status.Equals(serviceStatus.StopPending))) Then
            controller.Start()
            controller.Refresh()
      End If





































The use of Synonyms

We know synonym is an alternate name for an object. If you want to know more about synonym then please visit my blog : http://sqlreality.com/blog/ms-sql-server-2008/synonyms-in-sql-server/
Here I will share some scenario where synonym helps in writing efficient coding.
1.       In most cases the development, testing and production server are different. In testing environment suppose you are using a table in your stored procedures from a linked server’s TestServer. Take the table’s 4 part name is TestServer.Sales.dbo.Employee. While for UAT you need to use the dbo.Employee table from another server take it UATServer and in production the server would be ProdServer.
Here while development you would use table TestServer.Sales.dbo.Employee, during UAT you would have to change the table name to UATServer.Sales.dbo.Employee and while moving into production table name would be changed to ProdServer.Sales.dbo.Employee. Replacing the name repetitively is a wastage of effort and increases the possibility of errors.
Here synonym can solve the issue at great extent. You just create a synonym as below:
CREATE SYNONYM Employee FOR TestServer.Sales.dbo.Employee
And in the coding in stored procedure, views and functions use the synonym Employee at the place of 4 part table name.  After this when you need to test the code in UAT just change the synonym to new server as below:
DROP SYNONYM Employee
GO
CREATE SYNONYM Employee FOR UATServer.Sales.dbo.Employee
In the same way the synonym can be changed to point the production server. This way a long and error prone process of find & replace table name has been eliminated with few lines of code.
NOTE: There is no ALTER SYNONYM statement to change the base object. You will have to drop and re-create the synonym.
So if there is any possibility of change the server, database, schema or object name at later time, synonym can be used to simplify the code change process.
2.       Repetitive use of 4 part name in t-sql statements makes the coding complex & harder to write & read. For example you use a table TestServer.Sales.dbo.Employee as below:
SELECT TOP 5 Emp.EmpName, Mng.EmpName 
FROM TestServer.Sales.dbo.Employee Emp INNER JOIN 
(SELECT EmpId, EmpName FROM TestServer.Sales.dbo.Employee) Mng
ON Emp.MngID = Mng.EmpID

If you create a synonym as below:

CREATE SYNONYM Employee FOR TestServer.Sales.dbo.Employee

The above statement can be replaced with below one.

SELECT TOP 5 Emp.EmpName, Mng.EmpName 
FROM Employee Emp INNER JOIN 
(SELECT EmpId, EmpName FROM Employee) Mng
ON Emp.MngID = Mng.EmpID


Here you can find the difference in the easiness while writing and reading the statement.

Synonyms in SQL Server

Wikipedia says that “Synonyms are different words with identical or very similar meanings like student and pupil is synonym, buy and purchase is synonym.”
And concept of “Synonym” in SQL Server is not different at all, as SQL Server synonym is alternate name of a database object. For example, you can define an alternate name usp_Get_Invoices for a stored procedure Sales.dbo.usp_Get_Current_Month_Invoices.
Few things we should know about synonums are following:
1.       Synonym can be used to refer an object in current server or remote server.
2.       Synonym can be created for following types of objects:
a.       Tables: User-defined that include local and global temporary tables also
b.      Stored Procedures: SQL, CLR and extended, all types of stored procedures
c.       Functions:  SQL and CLR both types of functions
d.      Views
3.       A synonym can not be the base object for another synonym.
4.       Dropping a synonym does not affect the base object.
5.       Synonyms are not schema bound to base object and remain deferred until run-time. In other words the base object’s existence, validity, and permissions are checked only at run time.
6.    Syntax to create a synonym is following:
       CREATE SYNONYM [schema_Name.]Synonym_Name FOR base_Object
7.    Syntax to drop a synonym is following:
       DROP SYNONYM [schema_Name.]Synonym_Name     
8.       Synonym can be used in DML statements. Let us test with following code:
CREATE TABLE dbo.tblTest (Col1 INT, Col2 INT)
GO
INSERT INTO dbo.tblTest VALUES(1,10)
GO
CREATE SYNONYM syn_Table FOR dbo.tblTest
GO
SELECT * FROM syn_Table                -- retunrs 1 record
GO
INSERT INTO syn_Table VALUES (1,1)
SELECT * FROM syn_Table                -- returns 2 records

9.       Synonym can not be used in DDL statements. If we execute the below statements:

ALTER TABLE syn_Table ADD Col3 INT
Following error occur:
Msg 4909, Level 16, State 1, Line 1
Cannot alter 'syn_Table' because it is not a table.

8.       Synonyms are like view in permission checking and ownership chaining. For example if an user TestUser does not have execute permission on a stored procedure dbo.proc_TestSynonym, but have execute permission on a synonym of this stored procedure dbo.syn_Proc then user can execute dbo.syn_Proc successfully. Test this using below script:

CREATE PROCEDURE dbo.proc_TestSynonym
AS
SELECT * FROM dbo.tblTest        --change the table name
GO
CREATE LOGIN TestUser WITH PASSWORD = 'TestUser', CHECK_POLICY = OFF
GO
USE Test    --DB name
GO
CREATE USER TestUser
GO
DENY EXECUTE ON dbo.proc_TestSynonym TO TestUser 
GO 
CREATE SYNONYM dbo.syn_Proc FOR dbo.proc_TestSynonym 
GO 
GRANT EXECUTE ON dbo.syn_Proc TO TestUser 
GO 
EXEC AS USER = 'TestUser' 
GO 
PRINT '1' 
EXEC dbo.proc_TestSynonym --fail with permission denied error
GO 
PRINT '2' 
EXEC dbo.syn_Proc    --successfully executes 
GO 
REVERT 
GO 
 
Use the below scrip to undo the changes performed by above script:

DROP SYNONYM dbo.syn_Proc
GO
DROP PROCEDURE dbo.proc_TestSynonym
GO
DROP USER TestUser
GO
DROP LOGIN TestUser