Monday, December 1, 2008

SQL Server 2008 - Row Constructors

There are times when we need to insert multiple rows into a table. SQL Server 2008 has row constructors which simplifies the data insertion process.

Here are the various ways we can insert multiple rows with a single INSERT statement

--Create a table

CREATE TABLE RealTable

(ID int, name varchar(10))

GO

-- Insert with VALUE clause

INSERT INTO RealTable Values (1,'Mary')

INSERT INTO RealTable Values (2,'Jim')

--Insert with Select clause

INSERT INTO RealTable SELECT 3, 'Hillary'

INSERT INTO RealTable SELECT 4, 'Lisa'

--Insert with UNION ALL

INSERT INTO RealTable

SELECT 5, 'Rick'

UNION ALL

SELECT 6, 'John'

UNION ALL

SELECT 7, 'Tom'

--Insert with Row Constructors (new in SQL Server 2008)

INSERT INTO RealTable (ID, Color)

VALUES

(8, 'Toni'),

(9, 'Joe'),

(10, 'dave')

Thursday, November 27, 2008

SQL Server 2008 MERGE

MERGE statement performs insert,update or delete operations on target table based on the results of a join with source table.



Here is a simple example

--Staging table

CREATE TABLE Staging

(ID int, Color varchar(10))

GO

--Real table

CREATE TABLE RealTable

(ID int, Color varchar(10))

GO

--Populate Staging table

INSERT INTO Staging VALUES (1, 'Red') , (2, 'Blue') , (3, 'Green')

GO

--Merge statement

MERGE RealTable RT

USING

(SELECT ID, Color FROM Staging) S

ON (RT.ID = S.ID)

WHEN MATCHED THEN --update rows when matched

UPDATE SET RT.Color = S.Color

WHEN NOT MATCHED BY TARGET --insert if rows donot exist in the target table

THEN INSERT VALUES (ID, Color)

WHEN NOT MATCHED BY SOURCE --delete if rows donot exist in the source table

THEN DELETE;

GO

SELECT * FROM RealTable

GO

--Test the update

UPDATE Staging SET Color = 'Pink' WHERE ID = 3

GO

MERGE RealTable RT

USING

(SELECT ID, Color FROM Staging) S

ON (RT.ID = S.ID)

WHEN MATCHED THEN --update rows when matched

UPDATE SET RT.Color = S.Color

WHEN NOT MATCHED BY TARGET --insert if rows donot exist in the target table

THEN INSERT VALUES (ID, Color)

WHEN NOT MATCHED BY SOURCE --delete if rows donot exist in the source table

THEN DELETE;

GO

SELECT * FROM RealTable

GO

--Test the delete

DELETE FROM Staging WHERE ID = 2

GO

MERGE RealTable RT

USING

(SELECT ID, Color FROM Staging) S

ON (RT.ID = S.ID)

WHEN MATCHED THEN --update rows when matched

UPDATE SET RT.Color = S.Color

WHEN NOT MATCHED BY TARGET --insert if rows donot exist in the target table

THEN INSERT VALUES (ID, Color)

WHEN NOT MATCHED BY SOURCE --delete if rows donot exist in the source table

THEN DELETE;

GO

SELECT * FROM RealTable

GO

DROP TABLE RealTable

GO

DROP TABLE Staging

GO


UPSERT functionality

It UPDATEs rows if they exist in the selected row set or INSERTs rows if they don’t exist in one Sql command.

SQL Server 2005 does not have this feature. You will need 2 queries to get the functionality.


Here is a simple example

--Staging table

CREATE TABLE Staging

(ID int, Color varchar(10))

GO

--Real table

CREATE TABLE RealTable

(ID int, Color varchar(10))

GO

--Populate Staging table

INSERT INTO Staging VALUES (1, 'Red') , (2, 'Blue') , (3, 'Green')

GO

--UPSERT Functionality

--Perform UPDATE first

UPDATE RealTable

SET Color = S.Color

FROM RealTable AS RT (NOLOCK)

INNER JOIN Staging S (NOLOCK) ON S.ID = RT.ID

GO

--Perform INSERT

INSERT INTO RealTable(ID,Color)

SELECT ID, Color FROM Staging AS S

WHERE NOT EXISTS (SELECT * FROM RealTable AS RT WHERE RT.ID = S.ID)

GO

SELECT * FROM RealTable

GO

--Test the update

UPDATE Staging SET Color = 'Pink' WHERE ID = 3

GO

UPDATE RealTable

SET Color = S.Color

FROM RealTable AS RT (NOLOCK)

INNER JOIN Staging S (NOLOCK) ON S.ID = RT.ID

GO

--Perform INSERT

INSERT INTO RealTable(ID,Color)

SELECT ID, Color FROM Staging AS S

WHERE NOT EXISTS (SELECT * FROM RealTable AS RT WHERE RT.ID = S.ID)

GO

SELECT * FROM RealTable

GO

DROP TABLE RealTable

GO

DROP TABLE Staging

GO


Wednesday, November 19, 2008

SQL Server 2008 - Policy Based Management

After lots of confusion between DMF (Dynamic Management Functions) and DMF (Declarative Management Framework), a new name is given to be clear – Microsoft SQL Server 2008 Policy Based Management.


Policy Based Management allows to define and enforce the polices for configuring and managing SQL Servers across the enterprise. Here is just a brief description of the terminology.


Target – Object to be managed

Facet – Property of the object(target)

Condition – list of criteria for target’s facets

Policy - Set of conditions on the facets of a target


Evaluation Modes

On Demand – policy is evaluated only when manually run by admin

On change: Prevent – DDL triggers prevent policy violations

On Change: log only – Event notifications are used to check the policy when changes are made

On Schedule – SQL Agent job checks the policies for periodical violations

Friday, October 17, 2008

SSIS Data types and expressions


Here is the link to integration services data types


http://msdn.microsoft.com/en-us/library/ms141036.aspx


Expressions in SSIS:


To convert today’s date (getdate()) to string (Format: 2008-05-07)


SUBSTRING((DT_STR, 30, 1252)GETDATE(), 1, 10 )


To convert today’s date (getdate()) to string (format: 20080507)


( (DT_STR, 4, 1252) Year(GETDATE() )+RIGHT("0" + (DT_STR, 2, 1252) MONTH( GETDATE() ), 2) +RIGHT("0" + (DT_STR, 2, 1252) Day(GETDATE() ), 2) )


To convert today’s date (getdate()) to int (Format: 20080507)


(DT_I4) ( (DT_STR, 4, 1252) Year(GETDATE() )+RIGHT("0" + (DT_STR, 2, 1252) MONTH( GETDATE() ), 2) +RIGHT("0" + (DT_STR, 2, 1252) Day(GETDATE() ), 2) )

Thursday, October 16, 2008

Grant permissions to view stored procedure text

Sometimes in a production environment you may want to give developers read access to the text of the stored procedures but not be able to modify or execute them. In SQL Server 2005, you can grant VIEW DEFINITION permissions. Here are different ways to it


To grant view permissions to the entire schema


GRANT VIEW DEFINITION ON SCHEMA::dbo TO [UserName]


To grant permissions to specific stored procedure


GRANT VIEW DEFINITION ON YourStoredProcedureName TO [UserName]


To grant view definition on all the stored procedures in the database


--temporary table

DECLARE @tmpTable TABLE (

PK_ID INT IDENTITY (1, 1) NOT NULL PRIMARY KEY CLUSTERED,

[name] SYSNAME

)

--declare variables

DECLARE @name SYSNAME,

@RowCount INT,

@RecCount INT,

@strSQL VARCHAR(1000)

INSERT INTO @tmpTable ([name])

SELECT ROUTINE_SCHEMA+'.'+ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES

WHERE ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME NOT LIKE 'dt_%'

-- counters for while

SET @RecCount = (SELECT count(*) FROM @tmpTable)

SET @RowCount = 1

WHILE (@RowCount < @RecCount + 1)

BEGIN

SELECT @name = [name]

FROM @tmpTable

WHERE PK_ID = @RowCount

SET @strSQL = N'Grant VIEW Definition on ' + rtrim(cast(@name AS VARCHAR(128))) + ' to [UserName]'

--Execute the Sql

EXEC(@strSQL)

--Decrement the counter

SET @RowCount = @RowCount + 1

--reset vars, just in case...

SET @name = null

END

SELECT * FROM @tmpTable

Database Snapshots

Database snapshot is a read-only static database which provides the view of data at a point in time. Snapshots use the process of copy on write operation. If a page in the source database is modified for the first time, the original page is copied from the database to the snapshot. Updates after that don’t affect the contents of the snapshot.


Snapshots are very useful to off load historical reports from the OLTP systems. If mirroring is used for high availability, snapshots can be created on the mirror database.


SQL server management studio does not provide an option to create snapshots. The following T-SQL creates a snapshot named ProductSnap_0100 (0100 is the time stamp of when the database is created i.e. 1am) on the Products database with its sparse file named Products_data.ss.


--Drop if the snapshot exists

IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'ProductSnap_0100')

DROP DATABASE ProductSnap_0100

--Create a snapshot on CORIS database

CREATE DATABASE ProductSnap_0100

ON (NAME = N'Products_Data', FILENAME = N'E:\Snapshot\Products_data_0100.ss')

AS SNAPSHOT OF Products


Here is an excellent blog about how to switch the reports to the new snapshot.

http://blogs.msdn.com/sqlcat/archive/2008/08/05/microsoft-sql-server-database-snapshots-and-synonyms.aspx