Sunday, February 28, 2010

SQL SERVER – INSERT TOP (N) INTO Table – Using Top with INSERT

During my recent training at one of the clients, I was asked regarding the enhancement in TOP clause. When I demonstrated my script regarding how TOP works along with INSERT, one of the attendees suggested that I should also write about this script on my blog. Let me share this with all of you and do let me know what you think about this.

Note that there are two different techniques to limit the insertion of rows into the table.

Method 1:

INSERT INTO TABLE …
SELECT TOP (N) Cols…
FROM Table1

Method 2:

INSERT TOP(N) INTO TABLE …
SELECT Cols…
FROM Table1

Today, we will go over the second method, which in fact is the enhancement in TOP clause along with INSERT. It is very interesting to also observe the difference between both the methods. Let us take one real example and understand what exactly happens in either case.

Method 1:

INSERT INTO TABLE …
SELECT TOP (N) Cols…
FROM Table1

Method 2:

INSERT TOP(N) INTO TABLE …
SELECT Cols…
FROM Table1

Read more: Journey to SQL Authority with Pinal Dave

Posted via email from jasper22's posterous