Saturday, October 8, 2011

SQL Server 2008 - Wide Tables

Recently I navigated through the Maximum Capacity Specifications for SQL Server 2008

I found something interesting which says that,

Max columns per 'non wide' table : 1024
Max columns per 'wide' table : 30,000

Where non wide tables are regular database tables and wide table is a table which uses column sets and sparse columns. It still follows the same width restrictions per row i.e. 8019 bytes.  So you would typically use it only when most of your columns data in a particular row is NULL.

Refer to below link for more information.

Special Table Types

Reference: DP ( http://dptechnicalblog.blogspot.com/ )


T-SQL Exception Handling

Prior toSQL Server 2005 i.e. in SQL Server 2000 / 7.0, exception handling is a very premitive task with handful of limitations.
SQL Server 2005 architecture is now started using Visual Studio platform and based on Microsoft  .NET framework.
One of the features support is that now SQL Server can leverage on TRY..CATCH functionality provided by the .NET framework.

Following are the inbuilt methods supported by this TRY..CATCH functionality and should be used within CATCH block.

ERROR_NUMBER()
,ERROR_SEVERITY()
,ERROR_STATE()
,ERROR_PROCEDURE()
,ERROR_LINE()
,ERROR_MESSAGE()


For complete information refer to this good article written by Nakul Vachhrajani.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Thursday, October 6, 2011

SQL Server 2008 - Table Valued Parameters

SQL Server 2008 introduced a nice feature called Table Valued Parameters created using user defined table type.

Table-valued parameters offer more flexibility and in some cases better performance than temporary tables or other ways to pass a list of parameters. There are tons of benefits, and here is the list provided by BOL:
  • Do not acquire locks for the initial population of data from a client
  • Provide a simple programming model
  • Enable you to include complex business logic in a single routine
  • Reduce round trips to the server
  • Can have a table structure of different cardinality
  • Table valued parameters are strongly typed
  • Enable the client to specify sort order and unique ke

For more information refer to this link.

Reference: DP ( http://dptechnicalblog.blogspot.com/ )

SQL Server 2008 R2 : T-SQL Data Type Precedence

When an operator combines two different data types, the data type precedence rules says that the data type with lowest precedence converts to the data type with highest precedence.  If the conversion is not supported implicit conversion, an error is returned. If both the operands are of same data type, then the result is of same data type.

SQL Server uses the following order of data type precedence.

1. User defined data types (highest)
2. sql_variant
3. xml
4. datatimeoffset
5. datetime2
6. datetime
7. smalldatetime
8. date
9. time
10. float
11. real
12. decimal
14. money
15. small money
16. bigint
17. int
18. smallint
19. tinyint
20. bit
21. ntext
22. text
23. image
24. timestamp
25. uniqueidentifier
26. nvarchar (including nvarchar(max))
27. nchar
28. varchar (including varchar(max))
29. char
30. varbinary (including varbinary(max))
31. binary (lowest)

For complete details refer to the msdn link below:
 http://msdn.microsoft.com/en-us/library/ms190309.aspx 

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Wednesday, June 22, 2011

SQL SERVER - T-SQL New Line Character

To print information like multi line address, we have to use new line character. Different operating systems have different ways to understand this new line character. Mac supports only '\r' where as Linux supports '\n' and the most popular OS Windows needs both of these characters to understand the new line which is '\r\n'.

Few synonyms for line feed (LF) and carriage return(CR) are listed as below

Line Feed – LF – \n – 0x0a – 10 (decimal)
Carriage Return – CR – \r – 0x0D – 13 (decimal)

E.g.
Without new line character

DECLARE @NewLineCharacter CHAR(2) = CHAR(13) + CHAR(10)
PRINT 'Address1 Address2'
GO
Result:
Address1 Address2

With new line character

DECLARE @NewLineCharacter CHAR(2) = CHAR(13) + CHAR(10)
PRINT 'Address1 ' + NewLineCharacter  +'Address2'
GO
Result:
Address1
Address2




Monday, June 13, 2011

Microsoft Web Camps - Hyderabad

Hi All,

Microsoft Web Camps - Hyderabad will happen on 16th June, 2011.

Please find the details as below.

Venue:
Microsoft R&D India Pvt. Ltd. MPR 1-5, Building 3
Gachibowli Hyderabad Andhra Pradesh 500032
India

Audience(s): Architect and Pro Dev/Programmer. 

To register, click the link here:

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Friday, June 10, 2011

Microsoft Tech.Ed on the Road 2011.

' Tech.Ed on The Road'  had been bringing the best of Tech.ED sessions, that happened in Bangalore during March 2011,  from past one month  in Pune, Trivandrum, Hyderabad, Chandigarh and Delhi. Microsoft's efforts to reach out to thousands of developers and infrastructure professionals have received great appreciation. With great pleasure, Microsoft wish to announce that the rich Tech.Ed content will now be available in the following cities on the dates specified.

   Ahmedabad - 11-June-2001 
   Chennai - 18-June-2011 
   Mumbai - 25-June-2011
   Kolkata - 2-July-2011
   Bangalore - 9-July-2011 

Register at http://www.communitytechdays.com/

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Tuesday, June 7, 2011

SQL Server: Using JOIN Clause(s) with UPDATE and DELETE

SQL Server JOINs are very useful in data processing.
They are commonly used in SELECT queries but can be used with UPDATE and DELETE statements.

E.g.

IF OBJECT_ID('TableA') IS NOT NULL THEN
BEGIN
           DROP TABLE TableA
END
GO

IF OBJECT_ID('TableB') IS NOT NULL THEN
BEGIN
           DROP TABLE TableB
END
GO

CREATE TABLE TableA(
ID INT,
Name VARCHAR(100)
)
GO

CREATE TABLE TableB(
ID INT,
Name VARCHAR(100)
)
GO

Lets assume that these tables are populated with some records.

UPDATE ta
SET ta.Name = 'Join clause with Update statement'
FROM TableA ta
INNER JOIN TableB tb ON ta.ID = tb.ID
GO

DELETE ta
FROM TableA ta
INNER JOIN TableB tb ON ta.ID = tb.ID
GO

Similar to INNER JOIN, other types of JOIN clauses like LEFT JOIN and RIGHT JOIN can also be used with UPDATE and DELETE statements.

Please review this article and provide your comments.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Monday, June 6, 2011

SQL Server: Checking Existence and to Drop Temp Tables

Temporary tables are useful for storing the data temporarily during the data processing. There are two types of temp tables available in SQL Server namely  local temporary tables and global temporary tables.
The name of local temp tables prefix with '#' and global temp tables prefix with that of '##'.

To check existence of a local temparary table, drop and recreate the same use below approach.

IF OBJECT_ID('tempdb.dbo.#localTempTable') IS NOT NULL THEN
BEGIN   
           DROP TABLE #localTempTable
END IF
CREATE TABLE  #localTempTable(ID INT NOT NULL)
GO

IF OBJECT_ID('tempdb.dbo.##globalTempTable') IS NOT NULL THEN
BEGIN   
           DROP TABLE ##globalTempTable
END IF
CREATE TABLE  ##globalTempTable(ID INT NOT NULL)
GO

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Friday, June 3, 2011

SQL Server : To Retrive Columns of an Object

To find the all the columns of a db objects like table  and view we can use below approach using SQL Sever meta data objects like sys.objects and sys.columns.

USE AdventureWorks2008
GO
SELECT DISTINCT c.name [Column Name]
FROM sys.columns c
INNER JOIN sys.objects o on c.object_id=o.object_id

WHERE object_id('Production.Product')=o.object_id
ORDER BY [Column Name]


Where the Production.Product is a db table and can be substituted by any other table or view.

Partial result:
-------------------------------------------------

Column Name
Class
Color
DaysToManufacture
DiscontinuedDate
FinishedGoodsFlag


Reference : DP (http://dptechnicalblog.blogspot.com/ )

Saturday, May 28, 2011

SQL Server : Blackbox XML Method

Often its needed for reporting purpose to summarize the normalized data into groups or list of values. This is also known as row concatenation. This can be best done using some reporting and client side tools which support this functionality directly. Using SQL Server also we can do this in different ways.

IF OBJECT_ID('Products ') NOT NULL
DROP TABLE Products
GO
IF OBJECT_ID('Departments') NOT NULL
DROP TABLE Departments
GO


CREATE TABLE Products (
 PROD_ID INT PRIMARY KEY,
 PRODUCT_DESC VARCHAR(50));

CREATE TABLE Departments (
 DEPT_ID INT PRIMARY KEY,
 DEPT_TITLE VARCHAR(50));

CREATE TABLE DepartmentProducts (
 DEPT_ID INT
   REFERENCES Departments (DEPT_ID),
 PROD_ID INT
   REFERENCES Products (PROD_ID),
 PRIMARY KEY (DEPT_ID,PROD_ID));

INSERT INTO Products VALUES (1, 'Book');
INSERT INTO Products VALUES (2, 'Magazine');
INSERT INTO Products VALUES (3, 'DVD');
INSERT INTO Products VALUES (4, 'Video');
INSERT INTO Products VALUES (5, 'CD');
INSERT INTO Products VALUES (6, 'Map');

INSERT INTO Departments VALUES (1, 'Reference');
INSERT INTO Departments VALUES (2, 'Periodicals');
INSERT INTO Departments VALUES (3, 'Entertainment');

INSERT INTO DepartmentProducts VALUES (1, 1);
INSERT INTO DepartmentProducts VALUES (1, 6);
INSERT INTO DepartmentProducts VALUES (2, 2);
INSERT INTO DepartmentProducts VALUES (3, 3);
INSERT INTO DepartmentProducts VALUES (3, 4);
INSERT INTO DepartmentProducts VALUES (3, 5);

The Blackbox XML methods:

--Using CTE 
WITH cteProdDesc(DEPT_ID,PROD_DESC)
AS
(
      SELECT DEPT_ID,PRODUCT_DESC
      FROM DepartmentProducts AS DP
       INNER  JOIN Products AS P  ON P.PROD_ID= DP.PROD_ID
       WHERE DP.DEPT_ID = D.DEPT_ID
)

SELECT D.DEPT_ID,
       D.DEPT_TITLE,STUFF((SELECT ',' + cpd.PRODUCT_DESC
FROM Departments D
INNER JOIN cteProdDesc cpd ON cpd.DEPT_ID =  D.DEPT_ID
ORDER BY PRODUCT_DESC FOR XMLPATH('')),1,1,'') AS PRODUCT_LIST
FROM Departments D
GO 
-- Using correlated subquery
SELECT D.DEPT_ID,
       D.DEPT_TITLE,
       STUFF((SELECT ',' + PRODUCT_DESC
              FROM DepartmentProducts AS DP
              INNER JOIN Products AS P ON P.PROD_ID= DP.PROD_ID
              WHERE DP.DEPT_ID = D.DEPT_ID
              ORDER BY PRODUCT_DESC
              FOR XML PATH('')), 1, 1, '') AS PRODUCT_LIST
FROM Departments AS D;
GO 
-- Using CROSS APPLY
SELECT D.DEPT_ID,
       D.DEPT_TITLE,
       STUFF(P.PROD_LIST, 1, 1, '') AS PRODUCT_LIST
FROM Departments AS D
CROSS APPLY (SELECT ',' + PRODUCT_DESC
             FROM DepartmentProducts AS DP
             INNER JOIN Products AS ON P.PROD_ID= DP.PROD_ID
             WHERE DP.DEPT_ID = D.DEPT_ID
             ORDER BY PRODUCT_DESC
             FOR XML PATH('')) AS P (PROD_LIST);
GO

-- Results            
DEPT_ID DEPT_TITLE PRODUCT_LIST
-------------- ---------------- ------------
1              Reference        Book,Map
2              Periodicals      Magazine
3              Entertainment    CD,DVD,Video

This method is often called blackbox XML method and here is the explanation for this effect using FOR XML clause. Normally the PATH clause use with input string creates the wrapper element  in result set. However the PATH clause used with empty string gives result without creating wrapper element. And since the content is retrieved as text, the concatenation effect is achieved.

Resources:




Thursday, May 19, 2011

SQL Server : SQL code Formatter Tools

Often while debugging the SQL code written another developer which is not formatted, formatting will help in analysing and debugging the code effectively. Also writting the SQL code with proper formatting improves the readability and is a best practise.

I found couple of online code formatting tools which formats SQL code very good and can be handy.

Tool 1: Instant SQL Formatter
Tool 2: SQLinForm

You may try the above tools next time when you need to format your SQL code.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Saturday, April 30, 2011

SQL Server: Maintaining Integrity during Transactions

Data integrity is the most important aspect of anything and everything we do in database.

We developers often tend to ignore couple of things, or take things for granted. One of them is we forgot the Microsoft left it to the developer to decide whether to abort a transaction automatically when there is an error.

For detailed information, go through this link.

Reference : DP (http://dptechnicalblog.blogspot.com/ )

Wednesday, April 27, 2011

SQL Server: Difference between GetDate() and GetUTCDate()

The difference between GETDATE() and GETUTCDATE() is time zone number of the SQL Server machine.

E.g.

DECLARE @local_time DATETIME;
DECLARE @gmt_time DATETIME;
SET @local_time = GETDATE();
SET @gmt_time = GETUTCDATE();
SELECT 'Server local time: '
   + CONVERT(VARCHAR(40),@local_time);
SELECT 'Server GMT time: '
   + CONVERT(VARCHAR(40),@gmt_time);
SELECT 'Server time zone: '
   + CONVERT(VARCHAR(40),
      DATEDIFF(hour,@gmt_time,@local_time));
GO


Output:
Server local time: Apr 26 2011 09:47PM
Server GMT time: Apr 26 2011  04:17PM
Server time zone: 5

GETDATE = Returns the day of the month for the specified date according to local time.

GETUTCDATE() = Returns the day (date) of the month in the specified date according to universal time.


 Reference: DP(http://dptechnicalblog.blogspot.com )

Monday, April 25, 2011

SQL Server 2008 : Types of T-SQL Functions

There are rich set of different types built-in T-SQL functions available in SQL Server 2008 which can be broadly categorized as below.
Aggregate functions : Aggregate functions are applied to a group of data values from a column and will always return single value.
  • AVG
  • COUNT
  • COUNT_BIG
  • MIN
  • MAX
  • SUM
Scalare functions: Scalare functions are used in the construction of the scalar expressions and they can be operated on one or more columns. These functions can be further categorized as below.
  • Numeric functions
  • Date functions
  • String functions
  • System functions
  • Metadata functions
 For complete information, go through the link here.


Sunday, April 24, 2011

AdventureWork Data Dictionary

Adventure Works is a sample database which is useful for learning the SQL Server concepts, quick tests and demonstrating our thoughts by using scripts. This database need to be downloaded and seperately installed.

While the AdventureWorks family of databases is easily available from CodePlex, there is no well-known place where we can go to for lookup to the description of the schema and the tables.

A data dictionary is a centralized repository of information about data such as meaning, relationships to other data, origin, usage, and format. Data dictionaries are commonly used to circulate copies of the database schema to vendors and technology partners, and once a product is released, this may be made available to the end customers depending upon the need (eg. to allow for customization or study).

You can get the data dictionary for AdventureWorks sample databases at: http://technet.microsoft.com/en-us/library/ms124438(SQL.100).aspx

Reference : DP (http://dptechnicalblog.blogspot.com/ )

Saturday, April 23, 2011

3 Different Methods to Create Primary Keys

Primary key is unique identifier for each record in the database table and creates clustered index on the column on which its defined.

--Cleanup
IF EXISTS ( SELECT OBJECT_ID('constraintTable'))
DROP TABLE constraintTable
GO


CREATE TABLE constraintTable
(ID INT CONSTRAINT ct_ID PRIMARY KEY, Col2 VARCHAR(20))

GO

--Cleanup
IF EXISTS ( SELECT OBJECT_ID('constraintTable'))
DROP TABLE constraintTable
GO


--Primary Key upon table creating Method2
CREATE TABLE constraintTable
(ID INT, Col2 VARCHAR(20) CONSTRAINT ct_ID PRIMARY KEY)

GO

--Cleanup
IF EXISTS(SELECT OBJECT_ID('constraintTable'))
DROP  TABLE constraintTable
GO


--Primary Key upon table creating Method3
CREATE TABLE constraintTable
(ID INT, Col2 VARCHAR(20))

GO

--Primay key doesn't allow NULL values
ALTER TABLE constraintTable
ALTER COLUMN ID INT NOT NULL

GO

ALTER TABLE constraintTable
ADD CONSTRAINT Ct_ID PRIMARY KEY (ID)

GO

Reference: DP (http://dptechnicalblog.blogspot.com/ )

SSIS - Types of Transformations

SSIS transformation tasks can use memory or buffer in different ways. The way transformations use memory can impact the performance of your SSIS package dramatically. Transformations buffer usage can be categorised as below.
  • Non blocking transformations
  • Partially blocking transformations
  • Full Blocking transformations
In general if you can avoid using fully blocking and partial blocking transformations, your SSIS package will perform better. The transfromations can be classified as below

Non blocking transformations
  • Audit
  • Cache Transform
  • Character Map
  • Conditional Split
  • Copy Column
  • Data Conversion
  • Devired Column
  • Export Column
  • Import Column
  • Lookup
  • Multicast
  • OLE DB Command
  • Percentage Sampling
  • Script Component
  • Slowly Changing Dimesion

Partial blocking transformations
  •  Data Mining
  • Merge
  • Merge Join
  • Pivot
  • Unpivot
  • Term Lookup

Fully Blocking Transformations
  •  Aggregate
  • Fuzzy grouping
  • Fuzzy lookup
  • Row Sampling
  • Sort
  • Term Extraction

If you clearly observe Sort is a fully blocking transformation, so its better to sort your data using the SQL command in OLE DB Source instead of using Sort transformation. Merge tranform requires Sort but not Union All, so use Union All wherever possible.

Hope this post helps in analysing the performance bottle necks in your SSIS package and also while developing new SSIS package for performance tuning.

Reference: DP (http://dptechnicalblog.blogspot.com/ )



Saturday, March 26, 2011

SSIS Data Flow Scripting

I am very much excited to post my first BI article on my blog.

Microsoft SSIS is a powerful ETL technology to work on both OLTP and OLAP processes with its rich set of API components like control flow components, data flow components like various types of sources, destinations and transformation.

Using Data flow scripting transformation, we can use .NET code to customize the functionality of SSIS.
To know more about this transformation one should have knowledge of both SSIS and .NET.

For more information,  go through this video posted on Channel9 web site. For starters, Channel9 is a microsoft maintained web site with lots of videos, blogs, shows and series etc.

I hope this information is useful to the relevant audience.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Monday, March 21, 2011

SQL Server: Difference between Primary and Foreign Keys


Primary Keys:
Uniquely identify a row in a table with one or more columns
Column values cannot be null
There can only be one primary key on a table
Candidate for either a clustered or non-clustered index to improve performance
Additional information - Finding primary keys and missing primary keys in SQL Server

Foreign Keys:
They physically define the relationship between tables by preventing data integrity issues in your database (e.g. The database prevents line items from being created without an existing order header).
They logically document the relationships between tables by showing how all data relates to each other. To someone new to your organization, this allows him/her to get a good understanding of how the business works (e.g. Every order taken must have a valid customer assigned).
Foreign Keys are native to SQL Server and are designed to prevent data integrity issues. Business logic developers should not be in the business of verifying table relationships.
If defined and indexed correctly, they can be leveraged by the SQL Server query engine to generate extremely efficient query plans.

Reference: DP(http://dptechnicalblog.blogspot.com )

Monday, March 14, 2011

Extracting Only Numbers from a String

While working on projects, sometimes we may need to exatract only numbers from a string.

The regular approach is to run a while loop on given string to check each and every character and extract it to get the result.

Here is alternative approach I read in another article,

Declare @str varchar(100),@result_num varchar(100)
set @str='zr3jgc124785ce64'
set @result_num=''
select @result_num = @result_num+
case when number like '[0-9]' then number else '' end from
(select substring(@str,number,1) as number from
(select number from master..spt_values
where type='p' and number between 1 and len(@str)) as t
) as t
select @result_num as [only numbers]
go

Result:
312478564

Reference : DP (http://dptechnicalblog.blogspot.com/ )

Tuesday, March 8, 2011

SQL SERVER: User Defined Data Types

To create user defined data types, use either of the 2 methods.

1. Using T-SQL syntax

CREATE TYPE [Schema].[Datatype Name] FROM Datatype [NULL / NOT NULL]

E.g.
USE [AdventureWorks2008]
GO

/****** Object: UserDefinedDataType [dbo].[Test] ******/
CREATE TYPE  [dbo].[Test]  FROM  [int]  NOT NULL
GO

2. Using SSMS also we can acheive this.

In database expand the Programmability section, the Type section and the User Defined Data Type section
Right click and select New User-defined Data Type and a pop up appears as below
Fill appropriate data for Schema, Name and Data type fields and save it.


Reference : DP (http://dptechnicalblog.blogspot.com/ )

SQL Server : Challenges of Working with Nothing

If your data contains NULL values there will be deviations in result set, so the developer should be very careful while dealing with NULL values data.

Usually when comparing a column's data to a value or comparing column's data it results either in TRUE or FALSE, but comparision with NULL returns UNKNOWN which in somemeans same as FALSE.
We don't find the difference with '=' operator but with remaining operators like '<>' , the results will vary significantly as shown below.

USE AdventureWorks2008
GO
--Returns 504 rows
SELECT ProductID,Name
FROM Production.Product
GO
--Returns 248 rows
SELECT ProductID,Name
FROM Production.Product
WHERE Color IS NULL
GO
--Expected 478 rows but returns 230 rows
SELECT ProductID,Name,Style,Size,Color
FROM Production.Product
WHERE Color <> 'Blue'
GO
--Returns 478 rows
SELECT ProductID,Name,Style,Size,Color
FROM Production.Product
WHERE Color <> 'Blue' OR Color IS NULL
GO

We can observe the significance in result set due to NULL in last 2 query results.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Saturday, January 29, 2011

SQL SERVER: Calling Code from another Database

To call object from another database on the same server we should use 3 part syntax


Database.Schema.Object

e.g.


Use tempdb
GO

SELECT Name,ModifiedDate 
FROM [AdventureWorks2008].[Production].[ProductCategory]

Reference: DP (http://dptechnicalblog.blogspot.com)

Thursday, January 27, 2011

SQL Server: Renaming Database Column, Table Name

Often we get requirement to rename database column or table.
Here the syntax to do it using T-SQL scripts.

Script to rename any column

sp_RENAME 'tableName.OldColumnName' , 'NewColumnName', 'Column'
GO

Script to rename any db object (table, sp etc)

sp_RENAME 'objectOldName', 'objectNewName'
GO

Reference: DP (http://dptechnicalblog.blogspot.com/)

Wednesday, January 26, 2011

SQL Server: Difference between LEN() and DATALENGTH()

Sometimes we look for simple information like difference between  SQL Server built in functions LEN() and DATALENGTH().

DATALENGTH() returns length of string in bytes, including trailing spaces. LEN() returns length of  string in characters excluding trailing spaces.

e.g.

Executing the below script returns the result as shown in below screenshot.

SELECTLEN('sqlserver'),LEN('sqlserver '),DATALENGTH('sqlserver'),DATALENGTH('sqlserver '),LEN(N'sqlserver'),LEN(N'sqlserver '),DATALENGTH(N'sqlserver'),DATALENGTH(N'sqlserver ')
-------------------------------------------------------------------------











Reference: DP (http://dptechnicalblog.blogspot.com/)

Wednesday, January 19, 2011

SQL Server: Finding Duplicate Records

Recently I came across a situation where we need to findout the duplicate records based on certain criteria.

Problem: To findout duplicate users based on firstname and lastname
Solution:
Asssume tableA has below definition and already having data.
tableA(UserID,FirstName,LastName,LoginID,Password,Status)

SELECT a.UserID,a.FirstName,a.LastName,a.LoginID,a.Password
FROM tableA a
WHERE (
SELECT COUNT(b.FirstName+''+b.LastName) FROM tableA b
 WHERE a.FirstName=b.FirstName AND a.LastName=b.LastName AND b.Status <> 'delete'
) > 1
AND a.Status <> 'delete'
Order By FirstName,LastName

Please add your valueble comments and if any other alternative ways to get the same result.

Reference: DP (http://dptechnicalblog.blogspot.com/ )

Thursday, January 13, 2011

SQLSERVER Foreign Key Constraint Resolution

Recently I came across a scenario in db cleanup where we need to drop and restore the foreign keys in data migration. Some times we face an issue, foreign key constraint error during both dropping and adding foreign key relationship.
Eg:
tableA(pkEmpID, Name)
tableB(pkDeptID,fkEmpID,Name) where fkEmpID is foreign key for tableA and the foreign key constraint is fkEmpID_tableA_tableB.

To cleanup the data in tableA without deleting the data in tableB, use below syntax and this step is simple.

ALTER TABLE tableA DROP Constraint fkEmpID_tableA_tableB

After this, do db cleanup and complete the data migration.
Again while restoring back the foreign key relationship, use below syntax

ALTER TABLE tableA ADD Constraint fkEmpID_tableA_tableB FOREIGN KEY (pkEmpID) REFERENCES tableB (fkEmpID)

Sometimes the above query fails due to the difference in data between tableA and tableB w.r.t forienkey i.e. fkEmpID. To avoid this issue use below approach

DELETE FROM tableB WHERE fkEmpID NOT IN (SELECT pkEmpID from tableA)
The above query deletes the unmatching EmpID data from tableB, so restoring foreign key will be possible.

Hope this approach helps SQL guys in dealing with foreign key constraint errors.
Please post if you found any other solution or having any suggestions.

Reference
DP (http://dptechnicalblog.blogspot.com/)

Saturday, January 1, 2011

Difference between SQLManagementStudio_x64_ENU.exe and SQLManagementStudio_x86_ENU.exe

Recently I came across installation procedure for SQL Server 2008 Management Studio.
I found that there are 2 download exe files available and confused to choose between which one will be suitable for my PC's hardware configuration.

After a little anlaysis found the difference between the two exe files and here is the difference.
First one i.e. SQLManagementStudio_x64_ENU.exe  is for 64 bit and the second  one i.e. SQLManagementStudio_x86_ENU.exe is for 32 bit of Windows version. If you confuse between the 2, use 2nd one as it will work for both 32 bit and 64 bit of Windows which is not applicable for the 1st one.

Regards,
DP.