SQL Server Replication: How to completely remove replication
SQL Server Replication provides a comprehensive set of features for synchronising data between SQL Server databases and can be configured to suit many different scenarios.
As a business scales and its software requirements change, it’s not uncommon for the data architecture to also change. When this happens there may be a need to move data to different servers, remove existing replication configurations, and possibly set up existing hardware for other purposes.
In cases like this, or when errors have been made in the original replication setup, it can be very useful to have a quick way of completely removing replication from a server to ensure a clean slate.
In the section that follows I provide a script that will allow you to remove replication from your SQL Server and know with confidence that the process has been completed successfully.
Replication removal
It’s possible to remove most of a replication setup visually via the SQL Server Management Studio GUI.
However, it takes time to go through this process and oftentimes there are replication objects such as databases and constraints that fail to drop correctly. This leaves your system in an untidy state and potentially causes issues if you intend to set replication up again from scratch on the same server.
As a result, my recommendation is to use a SQL script that executes the stored procedures that are needed to remove the replication objects. This means that you can check the results of the procedures to ensure that they have completed execution with no errors.
The script
In my experience, I have found the following script to be a very reliable way of completely obliterating all replication objects from your SQL Server instance (for the parameters specified).
CAUTION
The script below is designed to remove ALL replication objects from your server. Please make sure that you only execute this script if you are 100% sure that you want to completely wipe your entire replication setup.
Note that before running the script, you must update all of the variables to match your setup. The variables and lines of code that you will need to consider changing have a comment in CAPITALS beside them.
Let’s walk through the above script in detail.
In the first few lines, some variables are declared and set.
In most cases, the distribution database will simply be called the default name of ‘distribution’. If you happen to have changed this when you set up replication originally, please update the value of the @distributionDB variable to match the custom name you chose.
The @publisher variable should be set to the name of the SQL Server instance that acts as the publisher. Usually, this is just the server name on its own, or the server name followed by a backslash and the instance name.
The @publicationDB variable should be set to the name of the publication database.
The next line switches to the publication database context by using the USE keyword followed by the name of the database to switch to. Make sure you have specified the name of the publication database here.
The sp_removedbreplication stored procedure removes all replication objects from the publication database. This will remove things like the ‘rowguid’ column and the constraints and triggers that are added to the database after setting up Merge Replication.
Before calling the next stored procedure, the script switches over to the primary system database.
The sp_dropdistpublisher stored procedure is used to remove the publisher registration at the distributor.
The sp_dropdistributiondb stored procedure deletes the distribution database.
Finally, the sp_dropdistributor stored procedure is used to uninstall the local server as a distributor.
If you have executed the script and there are no errors then you can be sure that your server and databases are replication-free and you can now operate from a clean slate again.
Other notes
For the most common replication setups, the above script can be executed without any tweaks, other than updating the variables etc. to the appropriate values.
In most cases, the publisher and distributor are installed on the same server, simplifying the replication setup. If you happen to have your distributor set up on a different server to the publisher, then you’ll need to execute the distributor scripts on the distribution server.
The stored procedures used in the script apply to all types of SQL Server Replication (Snapshot, Transactional, Merge). However, some of the stored procedures have arguments that can control how they affect specific types of replication setups e.g. for the sp_removedbreplication stored procedure you can specify the value of the @type argument as ‘merge’ to only remove Merge Replication objects from the database.
Summary
In this blog post, I have provided a SQL script that will completely remove all aspects of a SQL Server Replication setup.
I started by mentioning why I believe it’s important to use a script to perform the removal operation and proceeded to provide a listing of the SQL code.
I then walked through each part of the SQL script in detail to explain what it is doing and finished with some notes regarding things that you may need to consider if your replication setup is more complex.
I hope you enjoyed this post! Comments are always welcome and I respond to all questions.
If you like my content and it helped you out, please check out the button below
SQL Server script to remove replication?
I have been asked to write a SQL script that can be run, which will stop replication and remove the subscriber/subscription.
Is this at all possible? Or do you have to use the GUI?
2 Answers 2
Which version of SQL Server you are using.
Google as well provides MSDN article in results
How to: Disable Publishing and Distribution (Replication Transact-SQL Programming) — http://msdn.microsoft.com/en-us/library/ms147921.aspx
If you’re look to completely remove replication, including all the «bits». Or your server only has one publication and this is the one you’re trying to remove.
I would recommend:
- Connect to the Publisher or Distributor you want to disable in Microsoft SQL Server Management Studio, and then expand the server node.
- Right-click the Replication folder, and then click Disable Publishing and Distribution.
- Follow the steps in the Disable Publishing and Distribution Wizard, and instead of processing select the option to generate scripts.
This has the advantage of not only completely cleaning things up. But also removing the distribution database, which if you’ve ever dealt with before is known to become littered with remnants of replications past.
Как удалить репликацию ms sql
Статья представляет собой краткий справочник по использованию утилит командной строки для репликации MS SQL Server 2000.
Одну из ведущих ролей в репликации MS SQL Server играют агенты, которые являются утилитами командной строки. В данной статье мы рассмотрим четыре агента репликации: distrib.exe — Replication Distribution Agent, snapshot.exe — Replication Snapshot Agent, replmerg.exe — Replication Merge Agent и logread.exe — Replication Log Reader Agent.
Обычно, все эти четыре утилиты можно найти в каталоге C:\Program Files\Microsoft SQL Server\80\COM . Для того, что бы посмотреть параметры их вызова, необходимо запустить соответствующие исполняемые файлы с ключом «-?». На Вашем экране будет представлен синтаксис их запуска и перечень возможных ключей. Эта информация собрана в находящейся ниже по тексту таблице.
distrib.exe [-?] | snapshot.exe [-?] | replmerg.exe [-?] | logread.exe [-?] |
Код |
CREATE PROCEDURE dbo.ZvkList AS SELECT * FROM ACCESSDB. [Заявки] |
Код |
CREATE PROCEDURE dbo.ZvkList AS SELECT * FROM ACCESSDB. "Заявки" |
Код |
CREATE PROCEDURE dbo.ZvkList AS SELECT * FROM "ACCESSDB. Заявки" |
"Check Syntax" проходит на ура, а вот если жму на кнопку OK , то выскакивает
Цитата |
Error 7475: Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection. This ensures consistent query semantics. Enable these options and then reissue your query. |
В свойствах сервера выставлял галки ANSI_NULLS и ANSI_WARNINGS. Не помогло.
Профиль
Группа: Завсегдатай
Сообщений: 1330
Регистрация: 24.2.2005
Где: Орёл
Репутация: 2
Всего: 44
Профиль
Группа: Участник
Сообщений: 642
Регистрация: 17.5.2006
Репутация: нет
Всего: 8
Профиль
Группа: Завсегдатай
Сообщений: 1330
Регистрация: 24.2.2005
Где: Орёл
Репутация: 2
Всего: 44
Цитата(HappyLife @ 7.9.2007, 13:55 ) |
DimW, нет, эти самые точки означают что база данных слинкованная а не локальная. Это синтаксис MS SQL |
сори, кто бы мог подумать
Профиль
Группа: Модератор
Сообщений: 20541
Регистрация: 8.4.2004
Где: Зеленоград
Репутация: 13
Всего: 453
О(б)суждение моих действий — в соответствующей теме, пожалуйста. Или в РМ. И высшая инстанция — Администрация форума.
Данный форум предназначен для обсуждения вопросов о базах данных не попадающих под тематику других форумов:
- вопросам по СУБД для которых нет отдельных подфорумов
- вопросам которые затрагивают несколько разных СУБД (например проблема выбора)
- инструменты для работы с СУБД
- вопросы проектирования БД
- теоретически вопросы о СУБД
Данный форум не предназначен для:
- вопросов о поиске разлиных БД (если не понимаете чем БД отличается от СУБД то: а) вам не сюда; б) Google в помощь)
- обсуждения проблем с доступом к СУБД из различных ЯП (для этого есть соответсвующие форумы по каждому ЯП)
- обсуждения проблем с написание SQL запросов, для этого есть форум Составление SQL-запросов
- просьб о написании курсовой, реферата и т.п., для этого есть Центр помощи или фриланс биржа
- объявлений о найме специалистов, для этого есть раздел Объявления о найме специалистов
Если вы не соблюдаете эти правила, не удивляйтесь потом не найдя свою тему/сообщение.
Полезные советы:
При написании сообщения постарайтесь дать теме максимально понятное название. В теме максимально подробно опишите проблему. Если применимо укажите: название базы данных и версии (MySQL 4.1, MS SQL Server 2000 и т.п.); используемых язык программирования; способа доступа (ADO, BDE и т.д.); сообщения об ошибках.
Для вставки кода используйте теги [code=sql] [/code].
Литературу по базам данных можно поискать здесь.
Действия модераторов можно обсудить здесь.
Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, LSD, Zloxa.
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей) | |
0 Пользователей: | |
« Предыдущая тема | СУБД, общие вопросы | Следующая тема » |
[ Время генерации скрипта: 0.1090 ] [ Использовано запросов: 21 ] [ GZIP включён ]
Как удалить репликацию ms sql
Скрипт SQL Server для удаления репликации?
Меня попросили написать сценарий SQL, который можно запустить, чтобы остановить репликацию и удалить подписчика/подписку.
Это вообще возможно? Или вам нужно использовать графический интерфейс?
Ответы
Какую версию SQL Server вы используете.
Google также предоставляет статью MSDN в результатах
Как отключить публикацию и распространение (программирование репликации на языке Transact-SQL) — http://msdn.microsoft.com/en-us/library/ms147921.aspx
Если вы хотите полностью удалить репликацию, включая все «биты». Или на вашем сервере есть только одна публикация, которую вы пытаетесь удалить.
Я бы порекомендовал:
- Подключитесь к издателю или распространителю, который вы хотите отключить в Microsoft SQL Server Management Studio, а затем разверните узел сервера.
- Щелкните правой кнопкой мыши папку «Репликация» и выберите «Отключить публикацию и распространение».
- Выполните действия, описанные в мастере отключения публикации и распространения, и вместо обработки выберите параметр для создания сценариев .
Преимущество этого заключается не только в полной очистке вещей. Но также удаление базы данных распространителя, которая, если вы когда-либо имели дело раньше, как известно, засорена остатками прошлых репликаций.
Полную документацию можно найти здесь .
и используйте номер процесса, чтобы убить его, как показано ниже: kill 65
Связанные вопросы
Добавить столбец со значением по умолчанию в существующую таблицу в SQL Server
Вставить результаты хранимой процедуры во временную таблицу
SQL-запрос для выбора дат между двумя датами
Как я могу выполнить инструкцию UPDATE с JOIN в SQL Server?
Перед созданием временной таблицы проверьте, существует ли временная таблица, и удалите, если она существует.
Как удалить все публикации транзакций из базы данных Microsoft Sql Server?
Моя база данных имеет много подписчиков на множество таблиц, использующих репликацию Sql Server.
Когда я пытаюсь удалить таблицу или столбец в моей базе данных, который участвует в подписке на опубликованную базу данных, миграция базы данных не выполняется.
Эти подписчики проверяют, активна ли их публикация, и если нет, они повторно подписываются.
Мне нужно удалить все публикации из текущей базы данных через T-SQL, поэтому, когда я автоматизирую миграцию базы данных, удаляю столбцы или таблицы без сбоев миграции и необходимости ручного вмешательства.