Showing posts with label SQL2008. Show all posts
Showing posts with label SQL2008. Show all posts

Sunday, December 5, 2010

Get current Identity value, Seed value and Increment value in SQL Server

While working with IDENTITY we might want to know the current value of the IDENTITY, the SEED value and the Increment value. So here is the way by which we can quickly get this information.

SELECT IDENT_CURRENT ('customer') AS CurrentIdentity,
IDENT_INCR('customer') AS Incremented_By,IDENT_SEED('customer') AS SeedValue;

--create customer table
CREATE TABLE customer (custid INT IDENTITY NOT NULL,custname VARCHAR(10));

--insert value
INSERT INTO customer(custname) values ('cust1');

--get the Identity values
SELECT IDENT_CURRENT ('customer') AS CurrentIdentity,
IDENT_INCR('customer') AS Incremented_By,IDENT_SEED('customer') AS SeedValue;

Using the above example, I have inserted two records into the customer table. Here is the result of the current Identity values.


CurrentIdentityValues


Happy Learning !!!

Sunday, August 1, 2010

SQL Server Migration Tools - for Oracle/MySQL/Sybase


Are you planning to migrate to SQL Server....? Don't forget to checkout the Migration Assessment and Planning Toolkit from Microsoft for SQL Server 2008.


Also check out the migration related more information/resources at 

Happy Learning !!!

Saturday, July 31, 2010

SQL Server Driver for PHP 2.0 CTP2 – June 2010

As of June 2010, the SQL Server Driver for PHP V2.0 CTP2 is available for download.

The SQL Server Driver for PHP is a PHP 5 extension that allows for the reading and writing of SQL Server data from within PHP scripts. The extension provides a native procedural and PDO interfaces for accessing data in all editions of SQL Server 2005 and later including SQL Azure.

Please don’t forget to check the System Requirements. One thing I noticed here is, this driver is for Any edition of SQL Server 2005 or SQL Server 2008.

Click here to get more information : http://www.microsoft.com/downloads/details.aspx?FamilyID=DF4D9CC9-459C-4D75-A503-AE3FCEB85860&displaylang=en

Follow SQLPHP blog here

Happy Learning !!!

Sunday, July 18, 2010

Download SQL Server 2008 Service Pack 2 CTP

The CTP version of SQL Server 2008 Service Pack 2 (SP2) is now available. You can use these packages to upgrade any of the following SQL Server 2008 editions:

  • Enterprise
  • Standard
  • Evaluation
  • Developer
  • Workgroup

More Info from MSDN Website : click here

What's New:

  • SQL Server Utility The SQL Server 2008 R2 Utility supports SQL Server 2008 instances that have SP2 installed. The SQL Server Utility models SQL Server-related entities in a unified view. Utility Explorer and SQL Server Utility viewpoints in SQL Server Management Studio provide administrators a holistic view of resource health through an instance of SQL Server that serves as a utility control point (UCP). For more information about the SQL Server Utility, see Managing the SQL Server Utility.
  • Data-tier Applications SQL Server Management Studio in SQL Server 2008 R2 supports all data-tier application (DAC) operations for SQL Server 2008 instances that have SP2 installed. DAC is an entity that contains all databases and instance objects used by an application. A DAC provides a single unit for authoring, deploying, and managing the data-tier objects instead of having to manage them separately. A DAC allows tighter integration of data-tier development with the development of the associated application code. It also gives administrators an application level view of resource usage in their systems through the utility control point. For more information about data-tier applications, see Understanding Data-tier Applications.
  • Reporting Services in SharePoint Integrated Mode (Feature Pack) The Microsoft SQL Server 2008 Service Pack 2 (SP2) Reporting Services Add-in for Microsoft SharePoint Products 2007 allows you to connect to SQL Server 2008 R2 Report Servers. The new features include:
    • Improved handling of credentials and shared data sources.
    • Utilization of the existing instances of Report Builder configured on the Report Server.
    • Support for Report Part Gallery, shared datasets, and shared report items.
    • Report Builder 3.0
    • ATOM feed renderer. For more information, see the ‘Rendering Reports to Data Feeds’ section in "What's New in SQL Server 2008 R2".
Note: While this version of the add-in supports SQL Server 2008 Report Servers, the new features are only supported when connecting to SQL Server 2008 R2 report servers. Please note that installation of the 2008 SP2 add-in is not supported on SharePoint 2010 Products.

Sunday, May 30, 2010

Check current Isolation level in SQL Server

Often we wanted to know the current isolation level set for the SQL Server database. This can be easily checked with the following DBCC command.

DBCC USEROPTIONS;

This command returns the SET options active/configured for the current connection.

Result:

image

Wednesday, May 26, 2010

How to get the list of all the databases in SQL Server

To get the list of all the databases in SQL Server use the following system stored procedure

exec sp_databases;

Result:

DATABASE_NAME DATABASE_SIZE REMARKS
master 5120 NULL
model 2816 NULL
msdb 11264 NULL
ReportServer$SQL2008DEV 10240 NULL
ReportServer$SQL2008DEVTempDB 3072 NULL
SQLThreads 4096 NULL
tempdb 8704 NULL

Alternatively you can also use SQL Query as given below.

SELECT * FROM sys.databases;

image

Sunday, May 23, 2010

Execute SSIS Package based on File Existence

Often we have a requirement to check the file existence before we execute our package and it’s a best practice as well. So let’s understand how to achieve this in SSIS.

Quick Answer : The File.Exists () method will check the file existence on the specified path. The File.Exists() method will be available once you include System.IO; namespace to your script editor.

Complete Demo.

  1. Open the SSIS Package/Create a new SSIS Package
  2. Go to Control Flow
  3. Create three new variables with the Package Level Scope. – See the image 1 below
  4. Create one file (Excel or Flat File) as per your requirement and store it on a C:\
  5. Variables declaration
    1. FileExists – type is Boolean
    2. FileName – type your file name in a value column.
    3. FilePath – type your file path in a value column
  6. Go to  Control Flow and drag the Script Task to the container.
  7. Double click on the  Script Task and go to Script Tab and assign the ReadOnly and ReadWriteVariables as shown in the below Image 2
  8. Click Edit Script
  9. Now, you will be in the script Editor.
  10. Declare the namespace as  using System.IO;
  11. Go to Main() method and copy the below code.
  12. File.Exists will check the file existence for the specified path

public void Main()
{
  string fileNameWithPath=string.Empty ; 

//prepare the complete file path with name

fileNameWithPath =Dts.Variables["FilePath"].Value.ToString ()  + Dts.Variables["FileName"].Value.ToString (); 

            //check for the file existence
            if (File.Exists(fileNameWithPath))
                Dts.Variables["FileExists"].Value = true; 

            //display the result
            MessageBox.Show("File Exists " + Dts.Variables["FileExists"].Value.ToString()); 

            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success; 

        }

Now you are ready with the code. The above code will return true or false based on the file existence and you can use this value in the later part of the package to make conditional execution of the SSIS Package.

Conditional Execution of the package using Precedence Constraints

  1. First connect your Script Task with the other Task Container i.e. Data Flow Task or any other task which you want to execute based on the file existence.
  2. Now, double click on the green line (pipe line) which connects script task to another task.
  3. This will open a Precedence Constraint Editor .
  4. Under the Constraint Options group Select  --> Evaluation Operation as Expression as show in Image 3
  5. In the Expression text box type the expression you want. In our case it' is :  @FileExists=true. This means if the variable is true the the next task will execute.
  6. See the Image 3 for more clarity

Images

Image 1: Variables Declaration

image

Image 2 – Script Task Editor

image

Image 3 – conditional Execution using SSIS Precedence Constraints.

image

image

Happy Learning !!!

SQL Server 2008 R2 Overview resources

Get a very good high level overview on SQL Server 2008 R2 with the videos/documents/Hands on labs  available on Channel 9.


The resources available on Channel 9 contains information about the new features and improvements in SQL Server 2008 R2. Some of the interesting features on which information available is:
  • Creating Data Tier Application with VS 2010 and SQL Server 2008 R2.
  • Lesson on Introduction to StreamInsight
  • PowerPivot feature
  • Reporting Services features and many other new features.
You can view and download the resources from here.


Happy Learning !!!

Thursday, May 13, 2010

Saving changes is not permitted. The changes you have made require the following tables to be dropped and recreated. – SQL Server 2008

Today, after modifying the column when I tried to save I got the below message

“Saving changes is not permitted. The changes you have made require the following tables to be dropped and recreated. You have either made changes to a table that can’t be recreated or enabled the option Prevent saving changes that require the table to be recreated.”

image

 

To resolve the issue please follow the below steps.

1. Go to SQL Server Management Studio Tools –> Options

image

2. Now you will see the Options dialog box as shown in the below image. Under options go to Designers node –> Table and Database Designers.

image

3. Uncheck the option “ Prevent saving changes that require table re-creation.”

4. Now modify the database structure and you should be able to save the changes.

Happy Learning !!!

Thursday, April 22, 2010

SQL Server : ALTER COLUMN – Change the Size of the Column using ALTER Command

We can change the size of the already created column in the table using the ALTER command.

Example:

--Create test table
CREATE TABLE TestAlterCommand
(     EmpNo INT,
      EmpName varchar(10)
);

--Change the size of the column 'EmpName' from 10- 50;
ALTER TABLE TestAlterCommand
 
ALTER COLUMN EmpName varchar(50);

Happy Learning !!!

Get the current Isolation Level for the SQL Server database

Often developers would like to know the current Isolation Level for the SQL Server database. You can get this information using DBCC command. Type the following command in the query window.

DBCC USEROPTIONS;

The above command returns the SET options currently active for the current (active) user in SQL Server.

Note:

  1. Please don’t use DBCC commands without the prior permission of your DBA(s).
  2. Also these commands requires membership in the public roles.
  3. Please try in test environment only.

    Returns the following information

image

Happy Learning !!!

Wednesday, April 21, 2010

Download Free e-book on SQL Server 2008 R2 – Introducing Microsoft SQL Server 2008 R2

Dear Readers,

There is a free e-book available from Microsoft Press on – SQL Server 2008 R2. Introducing Microsoft SQL Server 2008 R2, by Ross Mistry and Stacia Misner.

The book contains the following chapters

PART I   Database Administration

CHAPTER 1   SQL Server 2008 R2 Editions and Enhancements 3
CHAPTER 2   Multi-Server Administration 21
CHAPTER 3   Data-Tier Applications 41
CHAPTER 4   High Availability and Virtualization Enhancements 63
CHAPTER 5   Consolidation and Monitoring 85

PART II   Business Intelligence Development

CHAPTER 6   Scalable Data Warehousing 109
CHAPTER 7   Master Data Services 125
CHAPTER 8   Complex Event Processing with StreamInsight 145
CHAPTER 9   Reporting Services Enhancements 165
CHAPTER 10   Self-Service Analysis with PowerPivot 189

Download e-Book: http://blogs.msdn.com/microsoft_press/archive/2010/04/14/free-ebook-introducing-microsoft-sql-server-2008-r2.aspx

Happy Learning !!!

What is Transactional Integrity – ACID Properties

  1. A transaction is a sequence of activities/tasks/operations which together makes a single logical unit of work.
  2. All of these task/operation must complete or fail as a single activity.
  3. All the transactions must be adhered to the ACID (Atomicity, Consistency,Isolation,Durability) properties.

Atomicity:

  • Transaction must be an atomic i.e.either all of the data is performed or nothing has been performed. Partial transaction should not be written to the disk.

Consistency

  • Once transaction is completed, it must leave all the data in a consistent state.
  • All the data integrity must be maintained.
  • All the rules/constraints must be enforced.

Isolation

  • Each transaction should be isolated from other transaction. i.e. each transaction must get the same set of data it started with.
  • Another user should not get the rows being worked by the first user – until the transaction is completed.

Durability

  • Once the transaction is completed, it must be available all the time regardless of the failure.

Happy Learning !!!

Wednesday, April 7, 2010

SQL Server 2008 Feature Comparison Chart

The below page compares the various editions of SQL Server 2008 based on its features.

Get the details here: http://www.microsoft.com/sqlserver/2008/en/us/editions-compare.aspx

Choose the right SQL Server 2008 Editions

Which edition of SQL Server 2008 is right for me? – The below page answers exactly the same.

http://www.microsoft.com/sqlserver/2008/en/us/editions.aspx

Also visit the below link to understand the components available in the various SQL Server 2008 Editions.

http://msdn.microsoft.com/hi-in/library/ms144275(en-us).aspx

Delete duplicate records from a SQL Server table

Today one of my colleague asked me how to delete duplicate records from a SQL Server Table. So to answer his question, let’s check the following example.

Note: The below example works on SQL Server 2005 and later versions.

--Create Table
CREATE TABLE dbo.TestDuplicate (EmpNo INT, EmpName VARCHAR(10)); 

--Insert Test Data
INSERT
INTO dbo.TestDuplicate VALUES (1,'Emp 1');
INSERT
INTO dbo.TestDuplicate VALUES (1,'Emp 1');
INSERT
INTO dbo.TestDuplicate VALUES (2,'Emp 2');
INSERT
INTO dbo.TestDuplicate VALUES (2,'Emp 2');
INSERT INTO dbo.TestDuplicate VALUES (3,'Emp 3'); 

--Remove Duplicates
WITH
CTE
AS (SELECT
ROW_NUMBER () OVER (ORDER BY EmpNo) SrNo , EmpNo FROM dbo.TestDuplicate)
DELETE FROM CTE WHERE SrNo NOT IN (SELECT MAX(SrNo) FROM CTE GROUP BY EmpNo);

--Check the table
SELECT * FROM dbo.TestDuplicate;

-- Data before deleting the duplicate records.

image

-- Data after deleting the duplicate records.

image

Points to Note:

  1. This was possible because of the ROW_NUMBER() function available in SQL 2005 onwards.
  2. ROW_NUMBER() function Returns the sequential number of a row within a partition of a result set. This means for each row in a result set it will return one unique sequential number for that row.
  3. The OVER clause determines the partitioning and ordering of the row set.
  4. As we have used CTE (Common Table Expression) it allows us to reuse the result set like a temporary table.

Hope this article may help you in deleting the duplicate records.

Happy Learning !!!

Monday, April 5, 2010

Get the list of all the constraints in a table in SQL Server

Often we think of How to get a list of all the constraints in a table. The below post answers that question. We can make use of INFORMATION_SCHEMA views to get the details of the meta data in SQL Server.

    • INFORMATION_SCHEMA view is contained in each database.
    • Each INFORMATION_SCHEMA view contains meta data about each object stored in that particular database.
      • information schema views are defined in a special schema named INFORMATION_SCHEMA.

The below query will list all the details about the meta data available in that particular database.

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS;

For example the above query will give you the below output i.e. List of all the constraints in a particular database. You can even filter data by specific constraint type , schema name, table name etc.

 

image

Example 2: List all the constraint in a table Employee under Schema STTest.

Answer: Following query will result the correct answer

SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
  
WHERE TABLE_NAME ='Employee' AND TABLE_SCHEMA ='STTest';  

image

Note: Here TABLE_CONSTRAINTS is a view defined in a special schema named INFORMATION_SCHEMA.

Happy Learning !!!

Difference between Truncate Table and Delete Table (Truncate Vs Delete)

Today, In this blog post, I would like to point out few differences between Truncate and Delete SQL Statement. This is also one of the most asked questions in SQL Server Interviews (specifically for SQL developers)

TRUNCATE Table

  • Fastest method for deleting all the rows from a table.
  • We can say Truncate Table is similar to Delete Statement without WHERE clause (for.e.g. DELETE FROM EMP)
  • Uses fewer system and transaction log resources. Only the page deallocations are recorded in the Transacton Log.
  • Fewer locks are used. Truncate table always locks the table and page but not the row.
  • Without exception, zero pages are left in the table
  • If the column in a table is having IDENTITY colum then Truncate Table command will reset the identity to it’s seed value. If no seed is defined then value 1 is used as default value.

DELETE Table

  • Deletes one row at a time and each deleted row is logged in the transaction log.
  • Delete statement locks each row for deletion (when used with Row Lock)
  • Once the delete process is over, table still contains the empty pages in a heap.
  • If the DELETE statement doesn’t use the Table Lock then the table may contain many empty pages .
  • To deallocate the empty pages, use TABLOCK hint in the DELETE statement. This will put a shared lock on the table instead of row or page lock and deallocate the pages.

Note: When empty pages are not de allocated, the space cannot be reused by other objects.

Example

TRUNCATE TABLE EMP_TEST;

DELETE FROM EMP_TEST WITH (TABLOCK);

 

Happy Learning !!!

Download SQL Server 2008 Samples

Now we have a new location for SQL Server 2008 Samples. The new location is on the codePlex web site. Please find the below link to download the SQL Server 2008 Samples
http://sqlserversamples.codeplex.com/Wikipage

Quickly :
Download AdventureWorks Family Database:
http://msftdbprodsamples.codeplex.com/releases/view/37109
Download All the samples together without AdventureWorks
http://www.codeplex.com/Release/ProjectReleases.aspx?ProjectName=SqlServerSamples

Happy Learning !!!