SlideShare una empresa de Scribd logo
1 de 4
Descargar para leer sin conexión
Using SQL Server 2008's MERGE statement | TechRepublic



   ZDNet Asia   SmartPlanet    TechRepublic                                                                               Log In   Join TechRepublic   FAQ   Go Pro!




                                                  Blogs     Downloads       Newsletters       Galleries      Q&A   Discussions     News
                                              Research Library


    IT Management             Development         IT Support        Data Center         Networks        Security




    Home / Blogs / The Enterprise Cloud                                                  Follow this blog:

    The Enterprise Cloud


    Using SQL Server 2008's
    MERGE statement
    By Tim Chapman
    September 24, 2007, 12:09 PM PDT

    Takeaway: SQL Server 2008’s new MERGE construct allows you to insert, update, or delete
    data based on certain join conditions in the same statement. Tim Chapman shows you how
    MERGE works with a hands-on example.

    SQL Server 2008’s new MERGE statement allows you to insert, update, or delete data based on
    certain join conditions in the same statement. In previous versions of SQL Server, you have to
    create separate statements if you need to insert, update, or delete data in one table based on
    certain conditions in another table. With MERGE, you can include the logic for these data
    modifications in one statement.

    How MERGE works
    The MERGE statement basically works as separate insert, update, and delete statements all
    within the same statement. You specify a “Source” record set and a “Target” table, and the join
    between the two. You then specify the type of data modification that is to occur when the records
    between the two data are matched or are not matched. MERGE is very useful, especially when it
    comes to loading data warehouse tables, which can be very large and require specific actions to
    be taken when rows are or are not present.

    MERGE example
    I will simulate sales feeds being received in the database and loaded to a reporting table that
    records daily sales statistics. In a typical scenario, the records would be loaded into a staging table
    (SalesFeed in this example), and then a series of transformations or DDL statements would be
    executed on the reporting table (SalesArchive in this example) to update the daily sales data. The
    MERGE statement allows you to use one statement to update the SalesArchive table rather than
    use several different DDL statements, which potentially could reduce the time it takes to make the
    updates occur, since only one lookup is done on the data rather than several.

    The following script creates the SalesArchive and SalesFeed tables:

    CREATE TABLE SalesArchive
     (
           CustomerID INT PRIMARY KEY,
           SalesDate INT,
           TotalSalesAmount MONEY,
           TotalSalesCount SMALLINT,
            CreationDate DATETIME CONSTRAINT df_CreationDate DEFAULT(GETDATE()),
                  UpdatedDate DATETIME CONSTRAINT df_UpdatedDate DEFAULT(GETDATE())
     )




http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
Using SQL Server 2008's MERGE statement | TechRepublic



     CREATE TABLE SalesFeed
     (
           CustomerID INT,
           Product VARCHAR(10),
           SaleAmount MONEY
     )

    The script below loads some data into the SalesFeed table. The way in which I am inserting data
    into this table is new to SQL Server 2008; it allows you to specify many values to be inserted
    using the VALUES clause of the INSERT statement.

    INSERT INTO SalesFeed
     (CustomerID, Product, SaleAmount)
     VALUES
     (1,'PoolTable', 1000),
     (2,'BigScreen', 955),
     (3,'Computer', 590),
     (4,'BigScreen', 880),
     (5,'Computer', 700)

    I have a few rows of data in my SalesFeed table and no data in my SalesArchive table. Now it is
    time for me to create my MERGE statement to add data to this table. Below is the MERGE script.

    MERGE SalesArchive AS SA
     USING (
           SELECT
                 CustomerID,
                 LoadDate = MIN(CONVERT(VARCHAR(8), GETDATE(), 112)),
                 TotalSalesAmount = SUM(SaleAmount),
                 TotalSalesCount = COUNT(*)
           FROM SalesFeed
           GROUP BY CustomerID
     ) AS SalesFeedCTE (CustomerID, LoadDate, TotalSalesAmount, TotalSalesCount)
     ON
     (
     SA.CustomerID = SalesFeedCTE.CustomerID AND SA.SalesDate = SalesFeedCTE.LoadDate
     )
     WHEN NOT MATCHED THEN
           INSERT (CustomerID, SalesDate, TotalSalesAmount, TotalSalesCount, CreationDate, UpdatedDate)
           VALUES( SalesFeedCTE.CustomerID, SalesFeedCTE.LoadDate, SalesFeedCTE.TotalSalesAmount,
    SalesFeedCTE.TotalSalesCount, GETDATE(), GETDATE())
     WHEN MATCHED THEN
           UPDATE
            SET SA.TotalSalesAmount = SA.TotalSalesAmount + SalesFeedCTE.TotalSalesAmount,
            SA.TotalSalesCount = SA.TotalSalesCount + SalesFeedCTE.TotalSalesCount,
     SA.UpdatedDate = GETDATE();

    At first glance, it looks reasonably complicated, but it’s not too bad once you get used to it. The
    table immediately following the MERGE statement is the table that will be modified; this is known
    as the TARGET table. In the USING statement, data from the SalesFeed table is being
    aggregated inside of a subquery based on the CustomerID; this portion is known as the SOURCE.
    This aggregation allows me to guarantee that there will be only one record per customer to update
    my SalesArchive table.

    The ON clause of the MERGE statement is where I specify: the joining between the SOURCE, the
    aggregated data from the subquery, and the TARGET, the SalesArchive table.

    The WHEN NOT MATCHED clause is where I specify what action I want to occur when the
    records from the SOURCE are not found in the TARGET. In this scenario, I want to insert those
    records into the SalesArchive table.

    The WHEN MATCHED clause is where I specify what I need to occur when the records from the
    SalesArchive table and the subquery of the SalesFeed table are found. In this scenario, I want to
    update what is currently in the table for that day, such as the TotalSalesAmount, the
    TotalSalesCount, and the UpdatedDate.

    With this scenario, if another sales feed comes into the database, only one statement will need to
    be run for that feed. Any new customer sales will be added to the database, and any existing
    sales will be updated with the new sales information.

    Tim Chapman a SQL Server database administrator and consultant who works for a bank in
    Louisville, KY. Tim has more than eight years of IT experience, and he is a Microsoft certified
    Database Developer and Administrator. If you would like to contact Tim, please e-mail him at



http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
Using SQL Server 2008's MERGE statement | TechRepublic

    chapman.tim@gmail.com.
    —————————————————————————————–

    Get SQL tips in your inbox
    TechRepublic’s free SQL Server newsletter, delivered each Tuesday, contains hands-on tips that
    will help you become more adept with this powerful relational database management system.
    Automatically subscribe today!


    Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
    newsletters.




                    About Tim Chapman
                        Full Bio    Contact




                   Storage considerations for                   Recover lost Windows Server
                   virtual desktops                             2003 files with Volume
                                                                Shadow Copy




        12            Join the conversation!                                             Add Your Opinion
      Comments        Follow via:



      Staff Picks      Top Rated      Most Recent        My Contacts                           See All Comments




                       Can you merge tables across DB's same server?                                 0
                       NewToTheGame Updated - 14th Jul 2010                                         Votes



           Trying to find out if it is possible to merge table data from table on another DB on
           same server

           What syntax is required?

           All web examples us tables in same DB


                 View in thread




                       Re: Performance                                                               0
                       chapman.tim@... 25th Sep 2007                                                Votes


           You're really not going to get around the cost incurred to run the separate
           insert/update/delete statements. I haven't ran any significant tests for this myself, but I
           don't think that the advantages... Read Whole Comment +


                 View in thread




                       Performance                                                                   0
                       richnorgaard@... 25th Sep 2007                                               Votes


           While I agree the table may be scanned once, the MERGE statement still invokes



http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
Using SQL Server 2008's MERGE statement | TechRepublic

           both an INSERT and UPDATE. The optimizer may build a special plan to leverage
           the lookup, but in the end the INSERT and... Read Whole Comment +


               View in thread




                                                See all comments



    Join the TechRepublic Community and join the conversation! Signing-up is
    free and quick, Do it now, we want to hear your opinion.

      Join       Login




http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]

Más contenido relacionado

Destacado

Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...
Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...
Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...Redis Manik
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Panasonic Reflection
Panasonic ReflectionPanasonic Reflection
Panasonic Reflectionnihankepsutlu
 
Bennett resume 3 011813
Bennett resume 3   011813Bennett resume 3   011813
Bennett resume 3 011813tlxdlr909
 
Daily Cleaning Neighbor
Daily Cleaning NeighborDaily Cleaning Neighbor
Daily Cleaning Neighbornihankepsutlu
 
3 бессонова тинькофф_плюс слайд
3 бессонова тинькофф_плюс слайд3 бессонова тинькофф_плюс слайд
3 бессонова тинькофф_плюс слайдEkaterina Abramova
 
Proximity marketing
Proximity marketing Proximity marketing
Proximity marketing Stefano Dindo
 
Richiesta incontro contact center 2017
Richiesta incontro contact center 2017Richiesta incontro contact center 2017
Richiesta incontro contact center 2017Fabio Bolo
 
Conflitto recapito 17
Conflitto recapito 17Conflitto recapito 17
Conflitto recapito 17Fabio Bolo
 

Destacado (15)

Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...
Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...
Sarana plkb 2014~ cv.asaka prima~www.asakaprima.com ~sarana prasarana plkb bk...
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Panasonic Reflection
Panasonic ReflectionPanasonic Reflection
Panasonic Reflection
 
Bennett resume 3 011813
Bennett resume 3   011813Bennett resume 3   011813
Bennett resume 3 011813
 
Daily Cleaning Neighbor
Daily Cleaning NeighborDaily Cleaning Neighbor
Daily Cleaning Neighbor
 
Operation: Move
Operation: MoveOperation: Move
Operation: Move
 
Halloween bag teddy-p_ms
Halloween bag teddy-p_msHalloween bag teddy-p_ms
Halloween bag teddy-p_ms
 
B halloween-flag e-a4
B halloween-flag e-a4B halloween-flag e-a4
B halloween-flag e-a4
 
Halloween bag teddy-i_en
Halloween bag teddy-i_enHalloween bag teddy-i_en
Halloween bag teddy-i_en
 
EIA-Final-Report (1)
EIA-Final-Report (1)EIA-Final-Report (1)
EIA-Final-Report (1)
 
3 бессонова тинькофф_плюс слайд
3 бессонова тинькофф_плюс слайд3 бессонова тинькофф_плюс слайд
3 бессонова тинькофф_плюс слайд
 
EIA Introduction
EIA IntroductionEIA Introduction
EIA Introduction
 
Proximity marketing
Proximity marketing Proximity marketing
Proximity marketing
 
Richiesta incontro contact center 2017
Richiesta incontro contact center 2017Richiesta incontro contact center 2017
Richiesta incontro contact center 2017
 
Conflitto recapito 17
Conflitto recapito 17Conflitto recapito 17
Conflitto recapito 17
 

Similar a Using sql server 2008's merge statement tech republic

Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republicKaing Menglieng
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008Klaudiia Jacome
 
Sql Server 2008 Enhancements
Sql Server 2008 EnhancementsSql Server 2008 Enhancements
Sql Server 2008 Enhancementskobico10
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copyMustafa EL-Masry
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012Eduardo Castro
 
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure WhitepaperMicrosoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure WhitepaperMicrosoft Private Cloud
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
Sql interview question part 7
Sql interview question part 7Sql interview question part 7
Sql interview question part 7kaashiv1
 
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docx
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docxAssignment 5Understanding SQL100 points (Questions 1 to 7 eac.docx
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docxssuser562afc1
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6kaashiv1
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6kaashiv1
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6kaashiv1
 

Similar a Using sql server 2008's merge statement tech republic (20)

Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republic
 
An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008An introduction to new data warehouse scalability features in sql server 2008
An introduction to new data warehouse scalability features in sql server 2008
 
Sql Server 2008 Enhancements
Sql Server 2008 EnhancementsSql Server 2008 Enhancements
Sql Server 2008 Enhancements
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copy
 
TSQL in SQL Server 2012
TSQL in SQL Server 2012TSQL in SQL Server 2012
TSQL in SQL Server 2012
 
Teradata sql-tuning-top-10
Teradata sql-tuning-top-10Teradata sql-tuning-top-10
Teradata sql-tuning-top-10
 
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure WhitepaperMicrosoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
 
Merging data (1)
Merging data (1)Merging data (1)
Merging data (1)
 
Simple ETL Solution - Marco Kiesewetter
Simple ETL Solution - Marco KiesewetterSimple ETL Solution - Marco Kiesewetter
Simple ETL Solution - Marco Kiesewetter
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
Ebook7
Ebook7Ebook7
Ebook7
 
Sql interview question part 7
Sql interview question part 7Sql interview question part 7
Sql interview question part 7
 
Merge In Sql 2008
Merge In Sql 2008Merge In Sql 2008
Merge In Sql 2008
 
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docx
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docxAssignment 5Understanding SQL100 points (Questions 1 to 7 eac.docx
Assignment 5Understanding SQL100 points (Questions 1 to 7 eac.docx
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
Sql interview question part 6
Sql interview question part 6Sql interview question part 6
Sql interview question part 6
 
Ebook6
Ebook6Ebook6
Ebook6
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6
 
Sql interview-question-part-6
Sql interview-question-part-6Sql interview-question-part-6
Sql interview-question-part-6
 

Más de Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republicKaing Menglieng
 
How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services Kaing Menglieng
 
How do i... reseed a sql server identity column tech_republic
How do i... reseed a sql server identity column    tech_republicHow do i... reseed a sql server identity column    tech_republic
How do i... reseed a sql server identity column tech_republicKaing Menglieng
 
How do i... query foreign data using sql server's linked servers tech_repu
How do i... query foreign data using sql server's linked servers    tech_repuHow do i... query foreign data using sql server's linked servers    tech_repu
How do i... query foreign data using sql server's linked servers tech_repuKaing Menglieng
 
Help! my sql server log file is too big!!! tech republic
Help! my sql server log file is too big!!!   tech republicHelp! my sql server log file is too big!!!   tech republic
Help! my sql server log file is too big!!! tech republicKaing Menglieng
 

Más de Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republic
 
How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services How to import an excel file into sql server 2005 using integration services
How to import an excel file into sql server 2005 using integration services
 
How do i... reseed a sql server identity column tech_republic
How do i... reseed a sql server identity column    tech_republicHow do i... reseed a sql server identity column    tech_republic
How do i... reseed a sql server identity column tech_republic
 
How do i... query foreign data using sql server's linked servers tech_repu
How do i... query foreign data using sql server's linked servers    tech_repuHow do i... query foreign data using sql server's linked servers    tech_repu
How do i... query foreign data using sql server's linked servers tech_repu
 
Help! my sql server log file is too big!!! tech republic
Help! my sql server log file is too big!!!   tech republicHelp! my sql server log file is too big!!!   tech republic
Help! my sql server log file is too big!!! tech republic
 

Using sql server 2008's merge statement tech republic

  • 1. Using SQL Server 2008's MERGE statement | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud Using SQL Server 2008's MERGE statement By Tim Chapman September 24, 2007, 12:09 PM PDT Takeaway: SQL Server 2008’s new MERGE construct allows you to insert, update, or delete data based on certain join conditions in the same statement. Tim Chapman shows you how MERGE works with a hands-on example. SQL Server 2008’s new MERGE statement allows you to insert, update, or delete data based on certain join conditions in the same statement. In previous versions of SQL Server, you have to create separate statements if you need to insert, update, or delete data in one table based on certain conditions in another table. With MERGE, you can include the logic for these data modifications in one statement. How MERGE works The MERGE statement basically works as separate insert, update, and delete statements all within the same statement. You specify a “Source” record set and a “Target” table, and the join between the two. You then specify the type of data modification that is to occur when the records between the two data are matched or are not matched. MERGE is very useful, especially when it comes to loading data warehouse tables, which can be very large and require specific actions to be taken when rows are or are not present. MERGE example I will simulate sales feeds being received in the database and loaded to a reporting table that records daily sales statistics. In a typical scenario, the records would be loaded into a staging table (SalesFeed in this example), and then a series of transformations or DDL statements would be executed on the reporting table (SalesArchive in this example) to update the daily sales data. The MERGE statement allows you to use one statement to update the SalesArchive table rather than use several different DDL statements, which potentially could reduce the time it takes to make the updates occur, since only one lookup is done on the data rather than several. The following script creates the SalesArchive and SalesFeed tables: CREATE TABLE SalesArchive ( CustomerID INT PRIMARY KEY, SalesDate INT, TotalSalesAmount MONEY, TotalSalesCount SMALLINT, CreationDate DATETIME CONSTRAINT df_CreationDate DEFAULT(GETDATE()), UpdatedDate DATETIME CONSTRAINT df_UpdatedDate DEFAULT(GETDATE()) ) http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
  • 2. Using SQL Server 2008's MERGE statement | TechRepublic CREATE TABLE SalesFeed ( CustomerID INT, Product VARCHAR(10), SaleAmount MONEY ) The script below loads some data into the SalesFeed table. The way in which I am inserting data into this table is new to SQL Server 2008; it allows you to specify many values to be inserted using the VALUES clause of the INSERT statement. INSERT INTO SalesFeed (CustomerID, Product, SaleAmount) VALUES (1,'PoolTable', 1000), (2,'BigScreen', 955), (3,'Computer', 590), (4,'BigScreen', 880), (5,'Computer', 700) I have a few rows of data in my SalesFeed table and no data in my SalesArchive table. Now it is time for me to create my MERGE statement to add data to this table. Below is the MERGE script. MERGE SalesArchive AS SA USING ( SELECT CustomerID, LoadDate = MIN(CONVERT(VARCHAR(8), GETDATE(), 112)), TotalSalesAmount = SUM(SaleAmount), TotalSalesCount = COUNT(*) FROM SalesFeed GROUP BY CustomerID ) AS SalesFeedCTE (CustomerID, LoadDate, TotalSalesAmount, TotalSalesCount) ON ( SA.CustomerID = SalesFeedCTE.CustomerID AND SA.SalesDate = SalesFeedCTE.LoadDate ) WHEN NOT MATCHED THEN INSERT (CustomerID, SalesDate, TotalSalesAmount, TotalSalesCount, CreationDate, UpdatedDate) VALUES( SalesFeedCTE.CustomerID, SalesFeedCTE.LoadDate, SalesFeedCTE.TotalSalesAmount, SalesFeedCTE.TotalSalesCount, GETDATE(), GETDATE()) WHEN MATCHED THEN UPDATE SET SA.TotalSalesAmount = SA.TotalSalesAmount + SalesFeedCTE.TotalSalesAmount, SA.TotalSalesCount = SA.TotalSalesCount + SalesFeedCTE.TotalSalesCount, SA.UpdatedDate = GETDATE(); At first glance, it looks reasonably complicated, but it’s not too bad once you get used to it. The table immediately following the MERGE statement is the table that will be modified; this is known as the TARGET table. In the USING statement, data from the SalesFeed table is being aggregated inside of a subquery based on the CustomerID; this portion is known as the SOURCE. This aggregation allows me to guarantee that there will be only one record per customer to update my SalesArchive table. The ON clause of the MERGE statement is where I specify: the joining between the SOURCE, the aggregated data from the subquery, and the TARGET, the SalesArchive table. The WHEN NOT MATCHED clause is where I specify what action I want to occur when the records from the SOURCE are not found in the TARGET. In this scenario, I want to insert those records into the SalesArchive table. The WHEN MATCHED clause is where I specify what I need to occur when the records from the SalesArchive table and the subquery of the SalesFeed table are found. In this scenario, I want to update what is currently in the table for that day, such as the TotalSalesAmount, the TotalSalesCount, and the UpdatedDate. With this scenario, if another sales feed comes into the database, only one statement will need to be run for that feed. Any new customer sales will be added to the database, and any existing sales will be updated with the new sales information. Tim Chapman a SQL Server database administrator and consultant who works for a bank in Louisville, KY. Tim has more than eight years of IT experience, and he is a Microsoft certified Database Developer and Administrator. If you would like to contact Tim, please e-mail him at http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
  • 3. Using SQL Server 2008's MERGE statement | TechRepublic chapman.tim@gmail.com. —————————————————————————————– Get SQL tips in your inbox TechRepublic’s free SQL Server newsletter, delivered each Tuesday, contains hands-on tips that will help you become more adept with this powerful relational database management system. Automatically subscribe today! Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. About Tim Chapman Full Bio Contact Storage considerations for Recover lost Windows Server virtual desktops 2003 files with Volume Shadow Copy 12 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments Can you merge tables across DB's same server? 0 NewToTheGame Updated - 14th Jul 2010 Votes Trying to find out if it is possible to merge table data from table on another DB on same server What syntax is required? All web examples us tables in same DB View in thread Re: Performance 0 chapman.tim@... 25th Sep 2007 Votes You're really not going to get around the cost incurred to run the separate insert/update/delete statements. I haven't ran any significant tests for this myself, but I don't think that the advantages... Read Whole Comment + View in thread Performance 0 richnorgaard@... 25th Sep 2007 Votes While I agree the table may be scanned once, the MERGE statement still invokes http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]
  • 4. Using SQL Server 2008's MERGE statement | TechRepublic both an INSERT and UPDATE. The optimizer may build a special plan to leverage the lookup, but in the end the INSERT and... Read Whole Comment + View in thread See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/using-sql-server-2008s-merge-statement/194[08/29/2012 3:20:12 PM]