Você está na página 1de 11

Snapshot replication acts in the manner its name implies.

The publisher simply takes a snapshot of the entire replicated database and shares it with the subscribers. Of course, this is a very time and resource-intensive process. For this reason, most administrators dont use snapshot replication on a recurring basis for databases that change frequently. There are two scenarios where snapshot replication is commonly used. First, it is used for databases that rarely change. Second, it is used to set a baseline to establish replication between systems while future updates are propagated using transactional or merge replication. SQL Server's snapshot replication technology allows you to automatically transfer information between multiple SQL Server databases. This technology is a great way to improve the performance and/or reliability of your databases. Here are some examples of replication use cases: Geographically distributing data to databases located at remote sites. This improves performance for end users by placing the data in a network location close to them and simultaneously reduces the load on intersite network connections.

Distributing data across multiple servers for load-balancing purposes. One common deployment strategy is to have a master database that is used for all update queries and then several subordinate databases that receive snapshots and are used in read-only mode to provide data to users and applications

Update data on a backup server to be brought online in the event the primary server

fails When you use snapshot replication, you copy the entire database from the Publisher SQL Server to the Subscriber SQL Server(s) on a one-time or recurring basis. When the Subscriber receives an update, it overwrites its entire copy of the data with the information received from the Publisher. This can take quite a long time with large datasets and it is imperative that you carefully consider the frequency and timing of snapshot distribution. For example, you would not want to transfer snapshots between servers in the middle of a busy data on a highly congested network. It would be much more prudent to transfer the information in the middle of the night when users are at home and bandwidth is plentiful. Initiating snapshot replication is a three-step process and About Databases contains detailed tutorials explaining each step: 1. 2. 3. Create the distributor Create the publication Subscribe to the publication

You may repeat the final step of creating a subscriber as many times as necessary to create all of the subscribers you would like. Snapshot replication is a powerful tool that allows you to transfer data between SQL Server installations in your enterprise. The tutorials linked above will help you get started moving data in a matter of hours.

Creating a Snapshot Replication Distributor


SQL Server's snapshot replication technology allows you to automatically transfer information between databases to keep them synchronized. In this article, we look at the first step of the snapshot replication process: creating the replication distributor. Difficulty: Average Time Required: 30 minutes Here's How: 1. Open SQL Server Management Studio and connect to the database server that you wish to serve as the distributor. 2. 3. Right-click on Replication and choose Configure Distribution from the pop-up menu. Click Next to advance past the welcome screen.

4. Select " will act as its own Distributor; SQL Server will create a distribution database and log", then click the Next button to continue. 5. Click the Next button to accept the default setting that SQL Server Agent should start automatically. 6. Provide a location where SQL Server should store the snapshot replication files by providing either a local folder path or a UNC share name, then click Next to continue. 7. Accept the default name and paths for the distribution database by clicking the Next button. 8. If servers other than the distribution server will publish to this distribution server, provide their information and then click the Next button to continue. 9. Click the Next button to advance to the confirmation screen. 10. Review the choices presented in the Complete the Wizard screen and click Finish to configure your distributor. What You Need:

Microsoft SQL Server 2008 SQL Server Management Studio

Creating a Publication
Once you've created a publisher/distributor, you can then use SQL Server Management Studio to create publications that subscribing servers may receive. Each publication contains a collection of database objects that will be replicated to all subscriber servers. With SSMS open, expand the Replication folder of the publisher and right-click on Local Publications. Then select New Publication from the pop-up menu.

Choose the Publication Database

Click the Next button to bypass the first screen of the wizard and then select a database to publish from the screen, as shown above. Once you've selected a database, click the Next button to continue.

Choose the Publication Type

As shown in the figure above, select the publication type you wish to use:

Snapshot publication Transactional publciation Transactional publication with updatable subscriptions Merge publication Press the Next button to continue.

Choose the Articles to Publish

Next, you must select the specific articles (objects) within the database that you wish to include in the publication. These are the objects that will be replicated across all subscribers. You may select any tables, user-defined functions or stored procedures. Once you've selected the items you wish to publish, click the Next button to continue.

Configure the Snapshot Agent

You'll want to advance past the Filter Table Rows screen, unless you wish to limit the data included in the publication. On the next screen, you'll have the option to create a snapshot immediately and/or create a schedule for future snapshots using the Snapshot Agent. Click on the Security Settings button to provide the account and connection details for the Snapshot Agent, as shown above. Once you've provided the details, click OK to close the Snapshot Agent Security screen and click the Next button to continue.

Finishing Up

Click through to the final screen of the wizard, which allows you to set the publication name. Once you've provided a descriptive name, click the Finish button to create the publication. You'll see the status window shown above while SQL Server creates your new publication.

How to Subscribe to a SQL Server Publication


Once you've configured a distributor and created a publication, the last step in configuring SQL Server replication is to create a subscriber who will receive publication updates from the publisher. In this tutorial, we walk through the process of subscribing to a publication, step-bystep. The process may be accomplished either at the publisher or the subscriber. Difficulty: Easy Time Required: 10 minutes Here's How: 1. Open SQL Server Management Studio, connect to the publishing server and expand the Replication folder. 2. Expand the Local Publications folder inside of the Replication folder. 3. Right-click on the publication that you wish to create a subscription to and choose New Subscription from the pop-up menu. 4. The New Subscription Wizard will open. Click Next to advance past the initial screens that welcome you to the wizard and confirm the publisher and publication you selected.

5. Select whether you wish to create a push or pull subscription and click Next to continue. In a push subscription, the Distribution Agent will run on the distributor and changes will be sent out to the subscriber as they occur. In a pull subscription, the Distribution Agent will reside on the subscriber and will check in with the publisher periodically to check for available updates. 6. In the next window, select the subscriber server(s) by checking the box to the left of each server you wish to receive the subscription. If the server you wish to use is not listed, click the Add Subscriber button to add it to the list. You should also select the subscription database for each subscriber using the pull-down menu to the right of each selected server. When you are finished, click the Next button to continue. 7. Click the ellipses ("...") button to configure Distribution Agent Security. You will be asked to provide account information that will be used to authenticate the subscription connection. When you are finished, click the Next button to continue. 8. Select a schedule for the Distribution Agent if you wish to vary from the default value of continuous distribution. Click the Next button to continue. 9. Select an initialization time if you wish to vary from the default value of immediately. Click the Next button to continue. 10. Click Next to accept the default value of creating the subscription immediately. Your alternative is to create a script that may be run at a later date. 11. Click the Finish button to create the subscription. SQL Server will provide a status window informing you of its progress creating the new subscription. What You Need:

Administrative access to the publisher and subscriber databases SQL Server Management Studio

Importing Bulk Data into SQL Server


SQL Server provides three methods you can use when you need to insert large quantities of data into a SQL Server database. These automated techniques will help you insert data from the results of a SQL query, a text file or another database. The three techniques discussed in this article are:

Copying data between tables with INSERT INTO Importing data from text files with BULK INSERT Copying data from the command line with bcp

Inserting Query Results The first method of inserting bulk data into a table is using the INSERT INTO statement. This allows you to import the results of another SQL statement and is useful for copying full or partial tables. Here's an example that copies students in the class of 2009 from a student table into an alumni table: INSERT INTO alumni SELECT * FROM students WHERE class_year = '1998' When using the INSERT INTO statement, you must either copy between tables with identical table structures or manipulate the data so that the columns match up correctly. Using BULK INSERT The BULK INSERT command allows you to import data from a text file. For example, the following Transact-SQL statement allows you to read a text file from your computer and insert the contents into a SQL Server table: BULK INSERT classes FROM 'C:\classes.txt' Using bcp The bulk copy (bcp) command of Microsoft SQL Server provides you with the ability to insert large numbers of records directly from the command line. In addition to being a great tool for command-line aficionados, bcp is a powerful tool for those seeking to insert data into a SQL Server database from within a batch file or other programmatic method. This powerful command has a number of options available. For full documentation, read the article Importing and Exporting SQL Server Data from the Command Line with bcp.

Importing and Exporting SQL Server Data from the Command Line with bcp
The bulk copy (bcp) command of Microsoft SQL Server provides you with the ability to insert large numbers of records directly from the command line. In addition to being a great tool for command-line aficionados, bcp is a powerful tool for those seeking to insert data into a SQL Server database from within a batch file or other programmatic method. bcp Syntax The basic syntax for using bcp is: bcp <table_name> <direction> <file_name> <options> Where the arguments take the following values: table_name is the fully qualified name of the table. For example, you might use inventory.dbo.fruits to insert records into the fruits table, owned by the database owner, in the inventory database. direction indicates whether you want to import (in direction) or export (out direction) data. file_name is the full path to the file. For example, you could import the file C:\fruit\inventory.txt.

options allow you to specify parameters for the bulk operation. For example, you can specify the maximum number of errors allowed with the m option. You may also use the x option to specify an XML file format. Consult Microsofts bcp documentation for a full list. bcp Import Example Lets put it all together. Imagine that you have a fruits table in your inventory database and that you want to programmatically import all of the records from a text file stored on your hard drive into that database. You would use the following bcp command syntax: bcp inventory.dbo.fruits in "C:\fruit\inventory.txt" -c -T This would produce the following output: C:\>bcp inventory.dbo.fruits in "C:\fruit\inventory.txt" -c -T Starting copy... 36 rows copied. Network packet size (bytes): 4096 Clock Time (ms.) Total : 16 Average : (2250.00 rows per sec.) C:\> If youre sharp-eyed, you might have noticed that I slipped in two new options on that command line. The c option specifies that the file format of the import file will be tab-delimited text with each record on a new line. The T option specifies that bcp should use Windows authentication to connect to the database. bcp Export Example As I mentioned earlier, you can export data from your database with bcp by changing the direction of the operation from in to out. For example, we could dump the contents of the fruit table to a text file with the following command: bcp inventory.dbo.fruits out "C:\fruit\inventory.txt" -c -T Heres how that looks on the command line: C:\>bcp inventory.dbo.fruits out "C:\fruit\inventory.txt" -c -T Starting copy... 42 rows copied. Network packet size (bytes): 4096 Clock Time (ms.) Total : 1 Average : (42000.00 rows per sec.) C:\> Thats all there is to the bcp command. You may use this command from within batch files or other programs with access to the DOS command line to automate the import and export of data from your SQL Server database.

Using TRYCATCH to Handle SQL Server Errors


The TRYCATCH statement in Transact-SQL allows you to detect and handle error conditions gracefully within your database applications. This statement is the cornerstone of SQL Server error handling and is an extremely important part of developing robust database applications. Introducing TRY..CATCH TRY..CATCH works by allowing you to specify two Transact-SQL statements: one that you wish to "try" and another that you wish to use to "catch" any errors that might arise. When SQL Server encounters a TRY..CATCH statement, it immediately executes the statement included in the TRY clause. If the TRY statement executes successfully, SQL Server simply moves on. On the other hand, if your TRY statement generates an error, SQL Server executes the CATCH statement to gracefully handle the error. TRY...CATCH Example It's easiest to understand the use of this statement through the use of an example, so let's turn our attention to one. Imagine that you are the administrator of a human resources database that contains a table named "employees", containing information about each of the employees in your organization. That table uses an integer employee ID number as the primary key. You might attempt to use the statement below to insert a new employee into your database: INSERT INTO employees(id, first_name, last_name, extension) VALUES(12497, 'Mike', 'Chapple', 4201) Under normal circumstances, this statement would add a row to the employees table. However, if an employee with ID 12497 already exists in the database, inserting the row would violate the primary key constraint and result in the following error: Msg 2627, Level 14, State 1, Line 1 Violation of PRIMARY KEY constraint 'PK_employee_id'. Cannot insert duplicate key in object 'dbo.employees'. The statement has been terminated. While this error provides you with the information you need to troubleshoot the problem, there are two issues with it. First, the message is cryptic. It includes error codes, line numbers and other information unintelligible to the average user. Second, and more importantly, it causes the statement to abort and could cause an application crash. The alternative is to wrap the statement in a TRYCATCH statement, as shown below: BEGIN TRY INSERT INTO employees(id, first_name, last_name, extension) VALUES(12497, 'Mike', 'Chapple', 4201) END TRY BEGIN CATCH PRINT 'Error: ' + ERROR_MESSAGE(); EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Employee Mail', @recipients = 'hr@foo.com',

@body = 'An error occurred creating a new employee record.', @subject = 'Employee ID Duplication Error' ; END CATCH In this example, any errors that occur are reported to both the user executing the command and the hr@foo.com e-mail address. The error shown to the user appears below: Error: Violation of PRIMARY KEY constraint 'PK_employee_id'. Cannot insert duplicate key in object 'dbo.employees'. Mail queued. Most importantly, application execution continues normally, allowing the programmer to gracefully handle the error. Use of the TRY..CATCH statement is an elegant way to proactively detect and handle errors that occur in SQL Server database applications.

Você também pode gostar