Sunday, July 24, 2011

Compare Sql Server Table Constraints

Hello friends, after a long period of time I’m back into my blog. As due to continuous projects didn’t get a long stretch to sit with my blog. 

In a BI project I faced a lot challenges for migrating some huge databases which ended up with lot of dependencies on sql server schema and object comparison tools(Redgate Sql Data compare,Sql compare,Xsql) to make my SSIS to execute smoothly. Now I’m in a workshop for synchronizing two databases. In the middle of that I’m sharing some useful sql queries which will be useful for happy coding.


IF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[SP_GET_ALL_CONSTRAINTS]')
and objectproperty(id, N'isprocedure') = 1)
DROP PROCEDURE [dbo].[SP_GET_ALL_CONSTRAINTS]
go
CREATE PROC SP_GET_ALL_CONSTRAINTS
(
@sourceServer nvarchar(1000),
@targetServer nvarchar(1000)
)
--@targetServer db to be migrated(old db) eg 12.3
--@sourceServer is the new database having all new schemas scripts eg:12.4
as
SELECT
'NEW' AS CHANGE,
DatabaseName AS DATABASENAME,
TABLE_NAME AS TABLENAME,
COLUMN_NAME AS COLUMNNAME,
CONSTRAINT_NAME AS CONSTRAINTNAME,
'N-A' AS NEW_CONSTRAINTNAME,
CONSTRAINT_TYPE AS CONSTRAINTTYPE,
ORDINAL_POSITION AS ORDINALPOSITION,
REF_PK_KEY AS REFERENCEPKKEY,
ParentTable AS ParentTable,
ParentField AS ParentField,
TYPE_CLUSTER AS TYPECLUSTER,
CASE CONSTRAINT_TYPE WHEN 'PRIMARY KEY'
THEN 'ALTER TABLE dbo.' + TABLE_NAME + ' ADD CONSTRAINT' + ' ' + CONSTRAINT_NAME + ' PRIMARY KEY (' + COLUMN_NAME + ')'
WHEN 'FOREIGN KEY' THEN
'ALTER TABLE dbo.' + TABLE_NAME + ' ADD CONSTRAINT '+ CONSTRAINT_NAME + ' ' +
CONSTRAINT_TYPE + '(' + REF_PK_KEY + ') REFERENCES ' + ParentTable + '(' + ParentField + ')'
ELSE 'ALTER TABLE dbo.' + TABLE_NAME + ' ADD CONSTRAINT ' + CONSTRAINT_NAME + ' UNIQUE (' + COLUMN_NAME + ')'
END AS Script
FROM
tbl_ALL_CONSTRAINTS
WHERE
DatabASeName = @targetServer
AND
CONSTRAINT_NAME NOT IN
(
SELECT CONSTRAINT_NAME
FROM tbl_ALL_CONSTRAINTS
WHERE DatabaseName = @sourceServer
)
UNION ALL
-- select the changed columns
SELECT
'MODIFIED' AS CHANGE,
v1.DatabaseName AS DATABASENAME,
v1.TABLE_NAME AS TABLENAME,
v1.COLUMN_NAME AS COLUMNNAME,
v1.CONSTRAINT_NAME AS CONSTRAINTNAME,
v2.CONSTRAINT_NAME AS NEW_CONSTRAINTNAME,
v1.CONSTRAINT_TYPE AS CONSTRAINTTYPE,
v1.ORDINAL_POSITION AS ORDINALPOSITION,
v1.REF_PK_KEY AS REFERENCEPKKEY,
v1.ParentTable AS ParentTable,
v1.ParentField AS ParentField,
v1.TYPE_CLUSTER AS TYPECLUSTER,
CASE v1.CONSTRAINT_TYPE WHEN 'PRIMARY KEY'
THEN 'ALTER TABLE dbo.' + v1.TABLE_NAME + ' DROP CONSTRAINT '
+ v1.CONSTRAINT_NAME + ' ALTER TABLE dbo.' + v1.TABLE_NAME
+ ' ADD CONSTRAINT' + ' ' + v2.CONSTRAINT_NAME
+ ' PRIMARY KEY (' + v1.COLUMN_NAME + ')'
WHEN 'FOREIGN KEY' THEN
'ALTER TABLE dbo.' + v1.TABLE_NAME + ' DROP CONSTRAINT ' + v1.CONSTRAINT_NAME + ' ALTER TABLE dbo.' + v1.TABLE_NAME
+ ' ADD CONSTRAINT '+ v2.CONSTRAINT_NAME + ' ' + v1.CONSTRAINT_TYPE + ' (' + v1.COLUMN_NAME + ') REFERENCES '
+ v1.ParentTable + '(' + v1.ParentField + ')'
ELSE 'ALTER TABLE dbo.' + v1.TABLE_NAME + ' DROP CONSTRAINT '
+ v1.CONSTRAINT_NAME + ' ALTER TABLE dbo.' + v1.TABLE_NAME + ' ADD CONSTRAINT ' + v1.CONSTRAINT_NAME + ' UNIQUE (' + v1.COLUMN_NAME + ')'
END AS Script
FROM
tbl_ALL_CONSTRAINTS v1
JOIN
tbl_ALL_CONSTRAINTS v2
ON
v1.TABLE_NAME = v2.TABLE_NAME
AND
v1.COLUMN_NAME=v2.COLUMN_NAME
AND
v1.CONSTRAINT_TYPE=v2.CONSTRAINT_TYPE
AND
v1.DatabaseName = @sourceServer
AND
v2.DatabaseName = @targetServer
AND
v1.CONSTRAINT_NAME<>v2.CONSTRAINT_NAME
GO
SET ANSI_NULLS ON
GO

The below script will populate all the sql server metadata information



----QUERY to Find out All the Constraints in Detailed
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[sp_CreateAllConstraintsInTable]') and objectproperty(id, N'isprocedure') = 1)
drop procedure [dbo].[sp_CreateAllConstraintsInTable]
go
CREATE PROCEDURE sp_CreateAllConstraintsInTable
@sourceServer nvarchar(30), --Database to be compared (New Database)
@targetServer nvarchar(30) --Database to be compared with(Old Database)
as
declare @sql varchar(max)

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tbl_ALL_CONSTRAINTS]') and objectproperty(id, N'istable') = 1)
drop table [dbo].[tbl_ALL_CONSTRAINTS]

select @sql=

' SELECT
u.TABLESCHEMA,
u.DatabaseName,
u.TABLE_NAME,
u.COLUMN_NAME,
u.CONSTRAINT_NAME,
u.CONSTRAINT_TYPE,
u.ORDINAL_POSITION,
u.REF_PK_KEY,
u.ParentTable,
u.ParentField,
u.TYPE_CLUSTER into tbl_ALL_CONSTRAINTS
FROM
(
(SELECT
TAB_CON.CONSTRAINT_SCHEMA AS TABLESCHEMA,
TAB_CON.TABLE_CATALOG as DatabaseName,
TAB_CON.TABLE_NAME AS TABLE_NAME,
KEY_COL.COLUMN_NAME AS COLUMN_NAME,
TAB_CON.CONSTRAINT_NAME AS CONSTRAINT_NAME,
TAB_CON.CONSTRAINT_TYPE AS CONSTRAINT_TYPE,
KEY_COL.ORDINAL_POSITION AS ORDINAL_POSITION,
RC.UNIQUE_CONSTRAINT_NAME AS REF_PK_KEY,
ccu.table_name AS ParentTable,
ccu.column_name as ParentField,
ISNULL(CLUST_TYPE.TYPE_DESC,'+ '''NOT APPLICABLE'''+') AS TYPE_CLUSTER
FROM '+
@sourceServer+'.INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TAB_CON
INNER JOIN
'+@sourceServer+'.INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KEY_COL
ON
TAB_CON.TABLE_SCHEMA = KEY_COL.TABLE_SCHEMA
AND
TAB_CON.TABLE_NAME = KEY_COL.TABLE_NAME
AND
TAB_CON.CONSTRAINT_NAME = KEY_COL.CONSTRAINT_NAME
LEFT JOIN
'+@sourceServer+'.INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
ON
RC.CONSTRAINT_NAME = TAB_CON.CONSTRAINT_NAME
AND
TAB_CON.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
LEFT JOIN '+@sourceServer+'.INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON
RC.unique_constraint_schema = ccu.constraint_schema
AND
RC.unique_constraint_catalog = ccu.constraint_catalog
AND
RC.unique_constraint_name = ccu.constraint_name
LEFT JOIN
(SELECT IDX.OBJECT_ID,IDX.NAME,IDX.TYPE_DESC,SCHEMA_ID FROM SYS.INDEXES IDX JOIN SYS.OBJECTS OBJ ON IDX.[OBJECT_ID] = OBJ.[OBJECT_ID] )
AS
CLUST_TYPE ON OBJECT_NAME(CLUST_TYPE.OBJECT_ID) = TAB_CON.TABLE_NAME
AND
CLUST_TYPE.NAME = TAB_CON.CONSTRAINT_NAME
AND
SCHEMA_NAME( CLUST_TYPE.[SCHEMA_ID]) = TAB_CON.CONSTRAINT_SCHEMA
)
union all
(SELECT
TAB_CON.CONSTRAINT_SCHEMA AS TABLESCHEMA,
TAB_CON.TABLE_CATALOG as DatabaseName,
TAB_CON.TABLE_NAME AS TABLE_NAME,
KEY_COL.COLUMN_NAME AS COLUMN_NAME,
TAB_CON.CONSTRAINT_NAME AS CONSTRAINT_NAME,
TAB_CON.CONSTRAINT_TYPE AS CONSTRAINT_TYPE,
KEY_COL.ORDINAL_POSITION AS ORDINAL_POSITION,
RC.UNIQUE_CONSTRAINT_NAME AS REF_PK_KEY,
ccu.table_name AS ParentTable,
ccu.column_name as ParentField,
ISNULL(CLUST_TYPE.TYPE_DESC,'+ '''NOT APPLICABLE'''+') AS TYPE_CLUSTER
FROM
'+@targetServer+'.INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TAB_CON
INNER JOIN
'+@targetServer+'.INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KEY_COL
ON
TAB_CON.TABLE_SCHEMA = KEY_COL.TABLE_SCHEMA
AND
TAB_CON.TABLE_NAME = KEY_COL.TABLE_NAME
AND
TAB_CON.CONSTRAINT_NAME = KEY_COL.CONSTRAINT_NAME
LEFT JOIN
'+@targetServer+'.INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
ON
RC.CONSTRAINT_NAME = TAB_CON.CONSTRAINT_NAME
AND
TAB_CON.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA
LEFT JOIN '+@targetServer+'.INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
ON
RC.unique_constraint_schema = ccu.constraint_schema
AND
RC.unique_constraint_catalog = ccu.constraint_catalog
AND
RC.unique_constraint_name = ccu.constraint_name
LEFT JOIN
(SELECT IDX.OBJECT_ID,IDX.NAME,IDX.TYPE_DESC,SCHEMA_ID FROM SYS.INDEXES IDX JOIN SYS.OBJECTS OBJ ON IDX.[OBJECT_ID] = OBJ.[OBJECT_ID] )
AS
CLUST_TYPE ON OBJECT_NAME(CLUST_TYPE.OBJECT_ID) = TAB_CON.TABLE_NAME
AND
CLUST_TYPE.NAME = TAB_CON.CONSTRAINT_NAME
AND
SCHEMA_NAME( CLUST_TYPE.[SCHEMA_ID]) = TAB_CON.CONSTRAINT_SCHEMA
)
) u
ORDER BY
u.TABLESCHEMA, u.CONSTRAINT_TYPE DESC,
u.TABLE_NAME,u.ORDINAL_POSITION'
exec (@sql)
go

Get this function also from here

Sunday, September 26, 2010

Bom Sabado Worm Fix for Orkut

Most of the new orkut users are affected with a worm called “BOM SABADO”. Please refrain from login into the new orkut, or you switch to the old one. This worm will send scraps to all of your orkut friends. For safe side you can change your google account password.

You can get out of this virus by using firefox addon Adblock plus  

After installing Click go to Preferences-> Add filter and enter *tptoos.org/* .

Also Revoke the access to worm in your google account settings.

gAcc

  1. Go to google account settings
  2. In Security ,”Change authorized websites”
  3. Revoke the access from “stapi.snacktools.com”
  4. Switch to old orkut, until google had a fix over it.

Happy Social Networking!!!!!!!!!!!!!!

Sunday, July 4, 2010

HTTP Error 500.19 with IIS 7.0

Last week i was deploying an application in IIS 7.0 freshly configured and got a HTTP 500.19 error as elaborated below

Description: The requested page cannot be accessed because the related configuration data for the page is invalid.

Error Code: 0x80070021

Notification: BeginRequest

Module: IIS Web Core

Requested URL: http://localhost:4341/webapplication1

Physical Path: c:\inetpub\wwwroot\webapplication1

Logon User: Not yet determined

Logon Method: Not yet determined

Handler: Not yet determined

Config Error: This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

Config File: \\?\c:\inetpub\wwwroot\webapplication1 \web.config

 

This due to the web.config section is get locked. By default whenever we install ASP.NET this section will be get unlocked. But sometime if we install IIS after ASP.NET installation it will not get unlocked. Here is the appcmd to unlock the section

%windir%\system32\inetsrv\appcmd unlock config -section:system.webServer/handlers

You need to run this command in Administrator mode, also go to control panel-> Turn windows feature on or off and under IIS install ASP.net.

Tuesday, June 8, 2010

Windows Phone 7: No Native Code Support


As in the previous generations of Windows Mobile phones the newly arrived Windows Phone 7 does not have any Native Code(Native code is computer programming (code) that is compiled to run with a particular processor (such as an Intel x86-class processor) and its set of instructions) support.It will support application running in the RIA platform Silverlight runtime and XNA Game studio only. This will make most of the SmartPhone Application developers to refrain from the Windows Phone 7. The user interface overlay the .Windows Embedded CE 6.0 Release 3 kernel , runs only interpreted or managed code through the two runtime environments provided by Silverlight and XNA.

Eventually all the Silverlight developers will become windows mobile developers. Any way that's the new step to the mobile-RIA world, good gaming
platform for the windows mobile with minimum hardware requirements

Saturday, May 8, 2010

VS 2010 –Some amazing features

For the past some months I'm looking into what’s there will be with Visual Studio 2010.At its beta releases VS 2010 faced a series of problems(Installer crash,Add reference empty in Silverlight project, Smart device project creation problem). Now they fixed most of the issues in the latest releases.I’m describing some of the cool new features with 2010 IDE.

View Call Hierarchy

By this we can see the hierarchical list of function usage.We can see the parameter details and function location.

Untitled11

Data & Schema Comparer

Previously most of us struggle a lot in comparing data's and schemas in and between databases. Also there was some third party tools Sql tool belt from Redgate, its so expensive.In Visual Studio 2010(I'm using vs 2010 ultimate) there is a new schema and data comparison tool.You can select two different databases and run the comparison task.

DMenu  Capture

Dcompare

Architectural and UML Model Explorer

This is quite useful for functional & architect.In the tool bat Select->Architecture->Windows->Architecture Explorer.Dig into it and do more!!!

archmen Arch1

Debugging With IntelliTrace

Visual Studio 2010 had a vast changes in the debugging sections.One of the cool feature is “IntelliTrace” which will more helpful while debugging the application as it provide a detailed picture of the debug info , you can record debug information and we can later look up into the previous debug info.

intellitrace

With IntelliTrace, you can actually see events that occurred in the past and the context in which they occurred. This reduces the number of restarts that are required to debug your application and the possibility that an error will fail to reproduce when you rerun the application.

Also we can pin-in values to variables  while debugging!!!

Read more in MSDN Click here

Read more about debugging information on ScottGu Blog Click here

Also VS 2010 newly added

  • Optional & Named parameters(like old vb 6)
  • Insert Code Snippet for JS,Html
  • We drag windows outside the model-Multi monitor support(Like we drag a tab to another window in Firefox&chrome)

Drag

And many more…that i will update in this chain.

Go and Rocks with VS 2010!!!!!!!!!!!!!!!

Converting “Var” to Dataset

After a long time back i’m into my blog…Didn’t get enough time to sit with the things..

In some cases we need to convert the anonymous datatype var to a dataset or datatable.we cant do it directly as so.Here is a

Simple method that will return the var or List item to dataset


public static DataSet ToDataSet(List list)
{

Type type = typeof(T);
DataSet ds = new DataSet("Company");
DataTable dt = new DataTable("Contacts");
ds.Tables.Add(dt);
//Dynamically adding columns to data table
foreach (var propInfo in type.GetProperties())
{
dt.Columns.Add(propInfo.Name, propInfo.PropertyType);

//You can add columns manually also here
if (propInfo.Name == "ID")
{
dt.Columns.Add("Photo");
}
}
foreach (T item in list)
{
DataRow dr = dt.NewRow();
foreach (var propInfo in type.GetProperties())
{
dr[propInfo.Name] = propInfo.GetValue(item, null);
}
dt.Rows.Add(dr);
}
return ds;
}

Wednesday, February 17, 2010

Xml Manipulation Using Linq-Some basic lessons

The “functional construction” feature of Linq to Xml provides great usability in creating and modifying xml documents. XDocument object is used for the xml declarations. The XElement class constructor are used in resolving the xml entities.

string path = Server.MapPath(@"/Linq2XML/DataStore.xml");
XDocument xd = XDocument.Load(path);
var result = from c in xd.Elements("DataStore").Elements("Table") select new { oid = (string)c.Element("oid"), BuildName = (string)c.Element("BuildName"), Appserver = (string)c.Element("Appserver"), DBServerName = (string)c.Element("DBServerName"), dbname = (string)c.Element("DBName"), comments = (string)c.Element("comments") };

This will load the Xml file to your XDocument object and perform a linq operation to get the xml elements. We can use Descendants to return the filtered collection of matching XName elements.

For modifying the elements we can use the SetElementValue Method of XElement, that will set, add and remove child elements.

public void ModifyEnvironments(string oid,string buildName,string appServer,string dbServer,string dbName,string comments )
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
var items = from item in objdoc.Descendants("Table")
where item.Element("oid").Value == oid
select item;
foreach (XElement itemElement in items)
{
itemElement.SetElementValue("BuildName", buildName);
itemElement.SetElementValue("Appserver", appServer);
itemElement.SetElementValue("DBServerName", dbServer);
itemElement.SetElementValue("DBName", dbName);
itemElement.SetElementValue("comments", comments);
}
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

We can use Remove() to delete an element.Also can use RemoveContent method that will make an empty element tag()

public void DeleteEnvironment(string oid)

{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
var items = (from item in objdoc.Descendants(@"Table")
where item.Element("oid").Value == oid
select item).FirstOrDefault();
items.Remove();
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
}

For adding new XElement we can use the Add() method

public void AddEnvironments(string buildName, string appServer, string dbServer, string dbName, string comments)
{
XDocument objdoc = XDocument.Load(HttpContext.Current.Server.MapPath(@"\Envdetails\DataStore.xml"));
XElement xe = objdoc.Descendants("DataStore").Last();
xe.Add(new XElement("Table", new XElement("oid", GetMaxOid()), new XElement("BuildName", buildName)
,new XElement("Appserver",appServer),new XElement("DBServerName",dbServer),new XElement("DBName",dbName),
new XElement("comments",comments)));
objdoc.Save(HttpContext.Current.Server.MapPath(@"\Linq2XML\DataStore.xml"));
}

Please find the sample XML file (“DataStore.xml”)here

Tuesday, February 2, 2010

Location and Sensor Platform in Windows 7

Cool , there are some nice sets of Location and Sensor API associated with windows 7.As now computers are portable like cellular phone the necessity of GPS enabled application are very useful. If your laptop doesn’t have any sensors installed it will take the default location provided by the user. This Location and sensor API open wide variety of applications.

References
http://msdn.microsoft.com/en-us/library/dd318936(VS.85).aspx
http://msdn.microsoft.com/en-us/library/dd464636(VS.85).aspx


Learn how to read the GPS co-ordinates, See this article.
http://blogs.msdn.com/coding4fun/archive/2006/10/31/912287.aspx
Even More..

Thursday, January 14, 2010

Func<T,TResults> – Flexible delegate to create reusable functions

Today while googling i found an interesting feature of delegate Func<T,TResults> ,it allows us to represent a method that can be passed as a parameter without declaring a custom delegate explicitly and the method must have one parameter that is passed to it by value and must return a value.

In the following example we need to explicitly define a new delegate and assign a named method to it.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
delegate int ConvertMethod(int _x);
class Program
{
static void Main(string[] args)
{
ConvertMethod objConv = SquareMe;
int val = 5;
//delegate is called
Console.WriteLine(objConv(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}

Without explicitly defining a new delegate it can be simplified as below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlogSamples
{
class Program
{
static void Main(string[] args)
{
Func convertMethod = SquareMe;
int val = 6;
Console.WriteLine(convertMethod(val));
Console.ReadKey();
}
private static int SquareMe(int myInt)
{
return myInt * myInt;
}
}
}


Please see the msdn link for more references.

Sunday, December 20, 2009

Restoring backup of Partitioned Database in sql server 2008

If we need to restore a database having some 'n' number of partition its very tedious to give all the partitioned filegroup to restore into a particular location in the database server.The below example we demonstrate to perform the task.Run the script in the master database.

IF Exists (SELECT '1' from sysobjects where name = 'RESTOREBKP_2008' and type ='p')
BEGIN
DROP PROCEDURE dbo.RESTOREBKP_2008
END
GO
CREATE PROCEDURE RESTOREBKP_2008
(
@DBName varchar(max), -- DATABASENAME
@BackupPath varchar(max), -- BACKUPFILEPATH
@Path varchar(max) -- PHYSICALPATH
)
AS
BEGIN

DECLARE
--Variables declaration
@ResFilesOnly Nvarchar(max),
@ResQuery Nvarchar(max),
@STR AS nVARCHAR(MAX),
@Logicalname as nvarchar(max),
@physicalname as nvarchar(max)

--- LOOP Variable
DECLARE @I AS INT, @J AS INT


set @ResFilesOnly='RESTORE FILELISTONLY
FROM DISK = '''@BackupPath''''

set @I = 1

DECLARE @RESTORE AS TABLE(
LogicalName nvarchar(128), PhysicalName nvarchar(500), Type char(1), FileGroupName nvarchar(128),
Size numeric(20,0), MaxSize numeric(38,0), FileID bigint, CreateLSN numeric(38,0),
DropLSN numeric(25,0) NULL, UniqueID uniqueidentifier, ReadOnlyLSN numeric(25,0) NULL,
ReadWriteLSN numeric(25,0) NULL, BackupSizeInBytes bigint, SourceBlockSize int,
FileGroupID int, LogGroupGUID uniqueidentifier NULL, DifferentialBaseLSN numeric(38,0) NULL,
DifferentialBaseGUID uniqueidentifier, IsReadOnly bit, IsPresent bit,TDEThumbprint varchar(500)
)
INSERT INTO @RESTORE
EXEC sp_executesql @ResFilesOnly

SELECT @J = MAX(FILEID) FROM @RESTORE
SET @STR = ''
WHILE @I <= @J
BEGIN
SELECT
@Logicalname = LTRIM(RTRIM(Logicalname)), @physicalname = LTRIM(RTRIM(REVERSE(LEFT(REVERSE(physicalname),CHARINDEX('\',REVERSE(physicalname))-1))))
FROM
@RESTORE
WHERE
FILEID = @I
SET @STR = @STR + 'MOVE N''' + @Logicalname + ''' TO N''' + @Path + @physicalname + ''', '

SET @I = @I + 1
END

--Restore Backup Query
set @ResQuery = 'RESTORE DATABASE ' + @dbname + ' FROM DISK = '''+ @BackupPath + ''' WITH '+ @STR +
N' NOUNLOAD, STATS = 10'

EXECUTE SP_EXECUTESQL @ResQuery
END


Execute this Stored Procedure in your master database as given below

EXEC RESTOREBKP_2008 '', '', ''

Note:-In case of any clarification please mail me to mail@renjucool.com

See this article in MSDN by me http://code.msdn.microsoft.com/Sql2008PartionedDb

Thursday, December 17, 2009

Sql Server Reporting Service –Silverlight enabled

For sometime before i’m thinking of the reports(SSRS/CR) to be enabled by silverlight technologies, so after googling i found out a amazing tool from perpetuumsoft to display SSRS reports in RIA enabled UI can do a deep zoom!!!!.Seems rocking!!!!

Debugging for Silverlight

Find out the RIA platform silverlight debugging tool from MSFT,whdc. also see this blog regarding the memory leak problem in silverlight.

 http://blogs.msdn.com/delay/archive/2009/03/11/where-s-your-leak-at-using-windbg-sos-and-gcroot-to-diagnose-a-net-memory-leak.aspx

Friday, December 4, 2009

Table Comparison in Sql Server

SQL Server is having a command line tool (TableDiff) to compare the data in two tables.It will perform the following task.

  1. A row by row comparison between a source table in an instance of Microsoft SQL Server acting as a replication Publisher and the destination table at one or more instances of SQL Server acting as replication Subscribers.
  2. Perform a fast comparison by only comparing row counts and schema.
  3. Perform column-level comparisons.
  4. Generate a Transact-SQL script to fix discrepancies at the destination server to bring the source and destination tables into convergence.
  5. Log results to an output file or into a table in the destination database.
eg:
 
 "C:\Program Files\Microsoft SQL Server\90\COM\TableDiff.exe" -sourceserver "SERVERNAME" -sourcedatabase "DBNAME" -sourceschema "dbo" -sourcetable "SOURCETABLE1" -sourceuser "sa" -sourcepassword "PASSWORD" -destinationserver "SERVERNAME" -destinationdatabase "DBNAME" -destinationschema "dbo" -destinationtable "SOURCETABLE2" -destinationuser "sa" -destinationpassword "PASSWORD" -dt -o "C:\Documents and Settings\renjuraj\My Documents\diff.xls"
 
Run the above command in command prompt.Please refer your sql server installation path(C:\Program Files\Microsoft SQL Server\90\COM\TableDiff.exe).

Thursday, December 3, 2009

Windows 7 Startup Animation Design

Rolf Ebeling, a senior user experience lead for the User Experience Design and Research Team for Windows, Windows Live, and Internet Explorer, is the man who designed the 105-frame Windows 7 boot animation that millions see or will see every day for years to come. Along with developing the famous boot animation, he also helped with the appearance and functionality of the calculator. He's already confirmed that he'll be working on the next version of Windows. Ebeling was only with the company for four months before he was asked to start designing what would become four swirling balls of light that come together to form a pulsing Windows 7 flag. Although the sketches of the early boot animation concept pictured above don't show it, Ebeling said he looked everywhere for inspiration, including street lights in the rain, light reflecting off water, and fireflies. A self-taught designer with a degree in English literature, Ebeling was a creative director for Newsweek.com in New York before joining Microsoft in April 2008, his first software job.

Source :Microsoft

Monday, November 23, 2009

Longest Running Procedures in Sql Server

Its useful to determine which SProc/Code have the greatest impact on the Server. Sometimes, that is determined by examining the I/O cost,sometimes by the Exectution Duration. In this eg, Total Impact is determined by examining the length of execution and the frequency of execution.

SELECT TOP 10
temp.text as ProcedureName,
s.execution_count as ExecutionCount,
isnull( s.total_elapsed_time / s.execution_count, 0 ) as AvgExecutionTime,
s.total_worker_time / s.execution_count as AvgWorkerTime,
s.total_worker_time as TotalWorkerTime,
s.max_logical_reads as MaxLogicalReads,
s.max_logical_writes as MaxLogicalWrites,
s.creation_time as CreationDateTime,
s.total_physical_reads as PhysicalReads,
isnull( s.execution_count / datediff( second, s.creation_time,getdate()), 0 )as CallsPerSecond
FROM sys.dm_exec_query_stats s
CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) temp
ORDER BY
-- s.total_elapsed_time DESC
s.execution_count desc

Friday, November 20, 2009

Transaction Log growing in Sql Server

Transaction log in SQL Server is one of the most important parts of a SQL Server , as well as one of the most common generators of problems I see online.The following are the causes for transaction log growth,
 
1.Due to Uncommitted transactions. We can find if there are any open transactions using DBCC OPENTRAN.
2.Running DBCC REINDEX, CREATE INDEX operations with the database in Full Recovery model.
3.Running extremely large transactions like Bulk Insert, Select Into commands.
http://support.microsoft.com/kb/317375/
 
The following are the proactive measures in order to minimize the unexpected log file growth,
 
1.If you do not want point in time recovery of your databases then you can change the recovery model to Simple.
2.Set the size of the transaction log files to a large value to avoid the automatic expansion of the transaction log files.
3.Configure the automatic expansion of transaction log in terms of MB instead of %.
4.Backup the transaction log regularly to delete the inactive transactions in your transaction log if you are using full or bulk logged recovery model.
5.You can switch the recovery model to Bulk logged from full recovery model if you perform some bulk inserts, select into, bcp, alter index, create index commands because these operations will be minimally logged in bulk logged recovery model and after those operations are completed you can switch over to full recovery model.
 

Solutions
  1. Take full backup of your database
  2. Take t-log backup of your database frequently say every 30 or 15 minutes so that log file will not grow drastically
  3. Shrink if you do not have any free space. You can perform this operation manually if required.
  4. Generally avoid shrinking the database and keep it as the last option.
If you are in full recovery, then no it won't be truncated.run the following command:
 

SELECT DATABASEPROPERTYEX('Lorenzo347', 'RECOVERY')

If it returns FULL or BULK_LOGGED, then you will have to backup the log, either to disk or specifying the truncate only to get it truncate the space off.  If you do that, then you might as well change your recovery model to SIMPLE and be done with this problem.  If it says you are already in SIMPLE, then it should shrink without problem.
 
backup log <your database name> with truncate_only
 
Shrink Log files
 
DECLARE @LogFileName varchar(100)
SELECT @LogFileName = rtrim(name)
FROM dbo.sysfiles
WHERE Name like '%_log%'
dbcc SHRINKFILE(@LogFileName, 2)

Shrinks the log file  to 2 MB


http://msdn.microsoft.com/en-us/library/aa258824(SQL.80).aspx
  
 Note:
Detaching and deleting the log is definitely not advisable 
 At best it forces you to take your database offline. Worst case is that you invalidate your entire database and have to  restore from backup.
 
 
 

Monday, November 16, 2009

Index to be recreated in Sql Server

When your database grows, the index fragmentation becomes too high,that will scale down the performance of the sql server. To overcome that we need to re-build the index, that should be done at the down time of the server.Here there is a query that will list all the index to be recreated/rebuild.It uses the following tables(sys.indexes,sys.tables,sys.schemas,sys.dm_db_index_physical_stats,sys.partitions). For detailed checkup change the last NULL in the dm_db_index_physical_stats call to 'SAMPLED' or even 'DETAILED'


SELECT 'ALTER INDEX [' + ix.name + '] ON [' + s.name + '].[' + t.name +'] ' +
CASE WHEN ps.avg_fragmentation_in_percent > 40 THEN 'REBUILD'
ELSE 'REORGANIZE' END +
CASE WHEN pc.partition_count > 1 THEN ' PARTITION = ' +
cast(ps.partition_number as nvarchar(max)) ELSE '' END
FROM sys.indexes AS ix INNER JOIN sys.tables t
ON t.object_id = ix.object_id
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
INNER JOIN (SELECT object_id, index_id,avg_fragmentation_in_percent, partition_number
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL,NULL, NULL, NULL)) ps
ON t.object_id = ps.object_id AND ix.index_id = ps.index_id
INNER JOIN (SELECT object_id, index_id, COUNT(DISTINCT
partition_number) AS partition_count
FROM sys.partitions
GROUP BY object_id, index_id) pc
ON t.object_id = pc.object_id AND ix.index_id = pc.index_id
WHERE ps.avg_fragmentation_in_percent > 10 AND
ix.name IS NOT NULL

Tuesday, November 10, 2009

VS 2010 Tranining kit

MSFT released the training kit(october preview) of VS 2010 framework.Can download it from Microsoft website.The Beta 2 release of the Training Kit contains 15 presentations, 19 hands-on labs, and 13 demos. Many technologies are covered in this release, including: C# 4, VB 10, F#, Parallel Extensions, Windows Communication Foundation, Windows Workflow, Windows Presentation Foundation, ASP.NET 4, Entity Framework, ADO.NET Data Services, Managed Extensibility Framework, and Visual Studio Ultim

Click here to dowload from Microsoft

Wednesday, October 28, 2009

Getting Country List from CultureInfo

We can use CultureInfo to get the list of countries/languages.Today i got a method to list all the countries, even it has some duplicate values that are elimated by a distinct linq query.

public void CountryList()
{
ArrayList cList=new ArrayList();
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures))
{
RegionInfo ri = new RegionInfo(ci.LCID);
cList.Add(ri.EnglishName);
}
var countries = cList.ToArray();
var i = (from temp in countries select temp).Distinct().OrderBy(s=>s);
foreach (var item in i)
{
listBox1.Items.Add(item.ToString());
}
}

Also an interesting thing with Textinfo to make the first letter of a string/sentence to capital.(Little bit tricky :-))

string temp = "MULTIDIMENSIONAL NEWTON RAPHSON";
string firstSmall = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(temp.ToLower()); //I made a trick to make the string to lower case
MessageBox.Show(firstSmall.ToString());

Output :Multidimensional Newton Raphson

Tuesday, October 27, 2009

Workstation & Server Garbage Collector

There are two types of garbage collector,the workstation GC and Server GC.Workstation is the default on client versions of windows,but server is much faster on multicore machines.The Server GC utilize more memory
  

<configuration> <runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>



Note:All sample code is provided is for illustrative purposes only.These examples have not been thoroughly tested under all conditions.Myself, therefore, cannot guarantee or imply reliability,serviceability, or function of these programs.