Отправляет email-рассылки с помощью сервиса Sendsay

MS SQL Server

  Все выпуски  

MS SQL Server - дело тонкое...


Информационный Канал Subscribe.Ru


#162<<  #163

СОДЕРЖАНИЕ

1.СОВЕТЫ
1.1.Планирование репликации с использованием identity
2.ССЫЛКИ НА СТАТЬИ
2.1.Статьи на русском языке
2.2.Новые и обновлённые технические статьи Microsoft
2.3.Англоязычные статьи
3.ФОРУМ SQL.RU
3.1.Самые популярные темы недели
3.2.Вопросы остались без ответа
4.ПОЛЕЗНОСТИ
4.1.Администрирование Microsoft SQL Server 2000. Учебный курс MCSA/MCSE.

СОВЕТЫ

Планирование репликации с использованием identity

По материалам статьи: Michael R. Hotek " Architecting replication with identity columns"

Автор статьи очень часто встречает вопросы о том, что использование поля identity порождает проблемы в репликации. Но он убеждён, что колонка Identity вполне может быть использована в репликации, просто необходимо выполнить некоторое предварительное планирование, наряду с установкой редко используемой опции. Эта статья описывает хороший метод, который автор использовал несколько лет, и который позволил ему успешно использовать колонки identity.
Во-первых, Вы всегда должны управлять значениями колонки identity, если вставка данных происходит более чем в одной базе данных, участвующих в репликации. Когда в первой базе вставляется в качестве значения для identity единица, во второй базе также должно вставляться значение identity равное 1, и при этом должна успешно выполняться проверка на пересечение. Это означает, что должна гарантироваться уникальность нового значения identity в каждой базе данных.
Для тиражирования данных столбца identity, репликация делает явную вставку в такой столбец. Это выполняется инструкцией identity_INSERT, которая вставляет в столбец identity новое значение. Вы должны быть внимательны, т.к. единственной причиной в репликации, из-за которой возникают проблемы, это то, как столбец identity ведет себя при вставке. Когда происходит вставка записи, в столбец identity записывается значение, которое на единицу больше, чем максимальное значение для этого столбца. Это может повредить репликации, т.к. при каждом её сеансе значения колонки identity для новых записей будут заменяться на другие, рассчитанные для получаемой реплицируемые данные таблицы (reseeded). Эти новые значения могут нарушить ограничения первичного ключа. Поэтому, в репликации можно отключить пересчёт значений столбца identity, просто используя предложение "not for replication" для реплицируемых identity столбцов. Выглядит это примерно так:

create table mytable
(Col1 int identity (1,1) not for replication not null
<другие поля таблицы>

Таким образом, Вы сообщите серверу баз данных, что необходимо отключить код, который повторно пересчитывает столбец identity, когда агент репликации вставляет данные в столбец identity. При этом сохраняются диапазоны identity, которые были установлены. Недостаток этой опции состоит в том, что в SQL Server 2000 Вы не можете добавлять эту опцию путём изменения, вносимого в публикуемую таблицу. Встречаются некоторые предложения по изменению для этого системных таблиц, которые автор не хочет рассматривать в рамках этой статьи. Не пробуйте устанавливать эту опцию путём изменения системных таблиц, если Вы не хотите потратить ваше время на восстановление базы данных из резервной копии, поскольку это может привести к повреждению базы данных. Наиболее безболезненным способом включения опции "not for replication" является исполнение представленного ниже алгоритма:

1) Переименуйте таблицу, в которую нужно добавить опцию.
2) Создайте новую таблицу с прежним именем и включённой опцией.
3) Вставьте данные из переименованной таблицы в новую.
4) Проверьте, что данные не повреждены.
5) Удалите переименованную таблицу.

Теперь, когда мы выяснили, как предотвратить пересчёт столбца identity при работе агента репликации, остался только один вопрос: как разделить диапазоны значений колонки identity для разных баз данных. Есть очень простой метод, которым автор пользовался несколько лет.
Большинство DBA используют целочисленный тип данных для identity. Однако, немногие используют тот факт, что целое число может быть и положительным и отрицательным. Использование же обоих диапазонов положительных и отрицательных значений очень простым способом расширяет возможности репликации.
Представленные ниже примеры сценариев кратко дают представление о том, как автор первоначально выделял разделы диапазонов значений identity, и как они расширялись по мере увеличения количества баз данных, участвующих в репликации.

Порядковый
номер базы
данных
Начальное
значение
identity
Приращение
identity
Примечание
2 базы данных
1 1 2 нечётные, положительные числа
2 2 2 чётные, положительные числа
4 базы данных
1 1 2 нечётные, положительные числа
2 2 2 чётные, положительные числа
3 -1 2 нечётные, отрицательные числа
4 -2 2 чётные, отрицательные числа
8 баз данных
1 1 2 нечётные, положительные числа
2 2 2 чётные, положительные числа
3 -1 2 нечётные, отрицательные числа
4 -2 2 чётные, отрицательные числа
5 500,000,001 2 нечётные, положительные числа, начинающиеся с полмиллиарда + 1
6 500,000,002 2 чётные, положительные числа
7 -500,000,001 2 нечётные, отрицательные числа
8 -500,000,002 2 чётные, отрицательные числа
16 баз данных
1 1 2 нечётные, положительные числа
2 2 2 чётные, положительные числа
3 -1 2 нечётные, отрицательные числа
4 -2 2 чётные, отрицательные числа
5 500,000,001 2 нечётные, положительные числа
6 500,000,002 2 чётные, положительные числа
7 -500,000,001 2 нечётные, отрицательные числа
8 -500,000,002 2 чётные, отрицательные числа
9 1,000,000,001 2 нечётные, положительные числа
10 1,000,000,002 2 чётные, положительные числа
11 -1,000,000,001 2 нечётные, отрицательные числа
12 -1,000,000,002 2 чётные, отрицательные числа
13 1,500,000,001 2 нечётные, положительные числа
14 1,500,000,002 2 чётные, положительные числа
15 -1,500,000,001 2 нечётные, отрицательные числа
16 -1,500,000,002 2 чётные, отрицательные числа

Основная идея состоит в том, чтобы при добавлении новых баз данных в схему репликации, разбивать диапазоны identity на чётные/нечётные, которые в свою очередь разбивать на положительные/отрицательные. Когда Вы включаете в систему репликации 4 базы данных, Вы просто разбиваете каждый диапазон напополам. Вы продолжаете это разбиение, по мере добавления баз данных. Для большого количества баз данных, такой алгоритм разбиения может стать проблематичным. Для случаев, когда количество баз превышает 500, автор просто использует для identity тип данных decimal, потому что он обеспечивает более широкий диапазон значений, что облегчает разделение диапазонов identity.
В SQL Server 2000 многие задачи по настройке были автоматизированы. Всё, что Вы должны сделать, это при установке назначить диапазоны для подписчиков, а затем репликация будет управлять ими сама. Она будет делать это, позволяя Вам определять пороговые значения для identity. Нормальные значения будут вставляться репликацией в вашу identity колонку. Когда значение identity достигнет определённого Вами порога, репликация переопределит identity в следующий, более высокий, допустимый диапазон значений. Хотя в ваших значениях и могут оставаться промежутки, Вам больше не нужно будет управлять всеми диапазонами identity. И не забывайте включить опцию SQL Server 2000: "not for replication".

[В начало]

ССЫЛКИ НА СТАТЬИ

Статьи на русском языке

Варианты использования (Use Case)
Сергей Трофимов
Основная цель создания любой программной системы - создание такого программного продукта, который помогает пользователю выполнять свои повседневные задачи. Для создания таких программ первым делом определяются требования, которым должна удовлетворять система. Однако если дать пользователям написать эти требования на бумаге, то часто можно получить список функций, по которому трудно судить будет ли будущая система выполнять свое назначение и сможет ли она облегчить пользователю выполнение его работы вообще. Непонятно какие из выполняемых функций более важны и для кого...
Валидаторы на заказ - пример валидации данных
Веденин Вадим
При разработке ASP.net приложений часто возникает необходимость в контроле за данными, вводимыми пользователем. Для этого применяют объекты, предоставляемые .Net FrameWork: RequiredFieldValidator, ReqularExpresionValidator...
Разработка расширенных хранимых процедур
andrey @ kuban. info
Для программирования расширенных хранимых процедур Microsoft предоставляет ODS (Open Data Service) API – набор макросов и функций, используемых для построения серверных приложений позволяющих расширить функциональность MS SQL Server 2000...

[В начало]

Новые и обновлённые технические статьи Microsoft

HOW TO: Process Results in an Embedded SQL Application
INF: 6.5 SEM Cannot Detect State of SQLMail on 6.0 Servers
INF: Cannot Restore Transaction Log from SQL Server 6.0 to 6.5
INF: Dump File Size Not Updated During Dump Database
INF: How Scheduled Data Transfer Works
INF: How to Obtain German SQL Server 6.5 Service Pack 2
INF: How to Use Editbin to Adjust SQL Server Thread Stack Size
INF: SQL Server Client Memory Required for Open Connection
INF: SQL Server Setup Requires 4MB Where Master.dat Is Located
INF: User-Defined Counters Do Not Show Up Correctly in Perfmon
INFO: New Parameter Options for Service Pack Setup
Post a Question to the Microsoft SQL Server Newsgroups

[В начало]

Англоязычные статьи

Where Do I Want To Go Today? - From the Field 2
Steve Jones
Taking a note from Microsoft's own page, I decided to share some of my wishes for where I want SQL Server to go. Today
Architecting replication with identity columns
Michael R. Hotek
Time and again, I see posts to mailing lists or newsgroups stating that identity columns do not work with replication. Identity columns do in fact work with replication. There is simply some pre-planning that must occur along with setting an option that you normally don't use. This article contains the best practices that I've developed over the years to get replicated systems to work together with identity columns
Using sp_addalias
Andy Warren
The stored procedure sp_addalias probably isn't one you use a lot, if at all. What does it do? Directly from BOL, it says: "Maps a login to a user in a database. sp_addalias is provided for backward compatibility. Microsoft SQL Server version 7.0 provides roles and the ability to grant permissions to roles as an alternative to using aliases."
Upgrade to Firewall-Friendly Updategrams
Roger Jennings
Replace disconnected recordsets with XML updategrams for secure Internet and wireless transactions. ActiveX Data Objects' disconnected recordsets have long been the technology of choice for minimizing overhead with database server connections to many VB6 clients. But if you haven't gone over to XML updategrams yet, now's the time. This proven technology enables you to specify updates to SQL Server 2000 databases through XML. SQL Server's updategram processor automatically generates and executes the SQL statements involved, including inserts, updates, and deletions. And you're in control of what the data will look like
How to troubleshoot connection problems
Alexander Chigrik
Should you have connection problems, review this troubleshooting checklist to find potential solutions
Introduction to MSSQL Server 2000 Analysis Services: MSAS Administration and Optimization: Simple Cube Usage Analysis
William Pearson
Microsoft SQL Server 2000 Analysis Services offers us many tools to assist in the maintenance and optimization of our cubes. Two of these tools highlight the usage-based optimization features of Analysis Services, and the ease with which we can enhance performance of our cubes based upon their usage by information consumers. My experience has been that, regardless of the design effort invested in any given business intelligence application, specifically within the context of anticipating the patterns of use of that application by the intended consumers, nothing can quite equal history as a guide to future human activity
Eric Brown Discusses SQL Server—Past, Present, and Yukon
It's been a busy year for SQL Server. Not only did it celebrate its 10th anniversary last winter, Microsoft is preparing a new version, code-named "Yukon," that's currently undergoing a round of early beta testing. MSDN Magazine recently talked to Eric Brown, a product manager for SQL Server, about the product's past and future.
Microsoft Consolidates SQL Server Tools
Lisa Vaas
Microsoft Corp. has consolidated the database security tools that shield SQL Server 2000 and MSDE 2000 installations from the Slammer worm. SQL Server 2000 SQL Scan, SQL Check and SQL Critical Update are now available in a single download, the SQL Critical Update Kit, which can be downloaded from the Microsoft Web site
SQL Server Hardware Resource Planning
Robert H. Chin
There is a growing demand for high performing, fast response applications in today's industry. In many organizations, a SQL Server 2000 server may be dedicated for the use of one particular application. From the ground up, analyzing and determining hardware requirements best suited for individual specific applications may help these application provide the timely response your end-users may be looking for
Home-grown Data Mining in SQL Server
Drew Georgopulos
You need certain data values to complete a database-programming job, but you don't know where they're located. What can you do? Follow this 10-Minute Solution to navigate through an unfamiliar database, and locate and extract the table and column names that house your values
Getting the Right Data with SQL Joins
Susan Sales Harkins, Patricia E. O' Connor
Associating tables in SQL is usually a breeze. But what happens when you find yourself looking at the completely wrong set of records and you don't know why? Find out how correctly applying joins can help you understand and avoid these mysterious data returns
Optimize Update-Concurrency Tests
Roger Jennings
Compare alternative approaches to SQL Server 2000 concurrency management. Minimizing active database connections is a primary objective of scalable data-access architectures. Maintaining a live connection to the source database while users browse, update, or insert the data behind complex business documents isn't practical for more than a few simultaneous users. ADO's disconnected Recordset objects let you maintain a local copy (snapshot) of the data of interest, disconnect, update the snapshot values, reconnect, and attempt to update the affected tables. ADO.NET's DataSet objects extend the original disconnected-recordset approach to create an in-memory representation of data tables with client-side relationship definitions, primary- and foreign-key constraints, and other data-consistency-checking features. Both object types permit offline editing by persisting the original and edited data versions to a local XML file and attempting an update after reconnecting to the network. The local-persistence scenario also applies to long-running transactions in automated business-to-business (B2B) processes, such as supply-chain management (see Additional Resources)
Manage Data Easily
Fabio Claudio Ferracchiati
Use the DataSet class to manage data you retrieve from a database or an XML source and display it in a DataGrid. Technology Toolbox: VB.NET, SQL Server 2000, ASP.NET, XML, ADO.NET. ADO.NET—the new version of the ADO library that the .NET Framework provides—introduces a revolutionary class called DataSet. The DataSet is an in-memory representation of one or more database entities, such as tables, columns, and relations. It's also much more: It manages XML data easily, allowing you to load an XML schema with related data and create an internal structure of tables, columns, and rows. You access data within the DataSet in the same way, whether you retrieve it from a database or an XML source. Moreover, the DataSet class provides a history state of its data that's useful for updating database tables and XML sources. This feature lets ADO.NET's DataAdapter object analyze the state of DataSet records to understand which data must be deleted from, added to, or changed in the data source. For example, you could show records "to be deleted" in a DataGrid and have the application ask for confirmation before removing them from the data source
MDX in Analysis Services: Intermediate Concepts - Part 2
William Pearson
In our last tutorial, we took MDX beyond the retrieval of member names and properties, and began to focus on leveraging the capabilities of the language to return values from a multidimensional cube. We created calculated measures whose values were based upon a constant, then upon current members, and explored additional uses of calculated members and measures. We practiced returning values, based upon the specification of dimensions within MDX expressions, to extend the expressions' utility within the context of reporting from an OLAP data source. Moreover, we examined various aspects of the MDX notation system along the way
Tips for Full-Text Indexing/Catalog Population/Querying in SQL 7.0 and 2000
Jon Winer
This article is a brief summary of several tips & tricks I have learned through working with the Full-Text features in SQL Server
Split delimiter-separated lists in SQL Server
Rajasekhar Sahitala
This function is useful for splitting a string of values delimited by a special character; e.g., a comma. I recently had a case where the list of employees for a department needed to be inserted into a table. The employee names were in a string delimited by commas. Separating these names in Visual Basic and inserting them into the database involved many database hits. Instead, I passed the string to the following stored procedure. The stored procedure split the string and inserted each employee name along with department name into the database
Row Count and Memory Utilization
Brian Moran
Can I create a SQL query that lists the top 10 largest tables in a database and displays how many rows and total bytes each table uses?
Learn About SQL Server Disaster Recovery from Greg Robidoux of Edgewood Solutions
Brad M. McGehee
Disaster recovery is a topic on the minds of many DBAs. Learn some of the basics about SQL Server disaster recovery from a leading expert in the area, Greg Robidoux of Edgewood Solutions. Greg is currently the Vice Chair for the PASS DBA Special Interest Group (SIG). In addition, he recently gave two presentations at the PASS Summit in Seattle on Change Management and Project Management for DBAs
XML IN 20 MINUTES!
Leon Platt
This article will quickly dive head first right into XML. I will take an everyday object and attempt to describe it using XML. Then I will load the XML file into a XML document object model (DOM). Next, I will demonstrate how to query the XML document using XPath and perform some minor manipulation of the DOM. All of this functionality will be preformed using a simple Visual basic application and the Microsoft parser version 3.0. The final objective of this article will be to produce an ActiveX control which will query the pubs SQL Server database and return a list of book titles in XML format
ASP - Reaping the benefits of SQL 2000's FOR XML clause.
Leon Platt
In the several years that I have been programming ASP pages, I have seen countless methods of dynamically filling HTML drop down list boxes. I myself have developed several re-usable routines for doing this. Being the XML guru that I am, I decided recently to play around with some of sql2000's XML features. It wasn't too long before it hit me.... I wonder if I could get SQL server to return a completely populated HTML list box with a simple query? After all, an HTML Select Tag is nothing more than an XML document! The syntax looks like this
TDS Protocol Documentation
This document attempts to cover the TDS protocol
FreeTDS FAQ
The FreeTDS User Guide, included in each release, is the appropriate place for new users to start. This list of frequently asked questions and answers about FreeTDS is updated between releases to cover problems since the last release, and to answer perennial questions (there are some)
FreeTDS User Guide
Brian Bruns, James K. Lowden
A Guide to Installing, Configuring and Running FreeTDS
Moving entire SQL Server user databases
Eli Leiba
Here are several procedures that you can use to "move" all of your user databases from one SQL Server to another with ease
Microsoft to Add Reporting to SQL Server
Dennis Callaghan
Microsoft Corp. on Wednesday announced that it is adding reporting capabilities to its SQL Server business intelligence platform, a move that financial analysts predicted could threaten reporting software vendors

[В начало]

ФОРУМ SQL.RU

Самые популярные темы недели

Ваше мнение об упражнениях SELECT на http://sql.ipps.ru
Нужен Админ MS SQL - на один раз!
MSSQL и Web. Вопрос практикам - кто какие технологии использует?
Теряются данные из SQL Сервера ПОМОГИТЕ!!!!
очень простой арифметический вопрос про НДС
Naming Convention
Вопрос над которым стоит поразмыслить!
Delphi MS SQL Server-тригер не выдает сообщ
Как узнать, какое действие вызвало триггер?
Связь таблиц - как правильно?
Filter Rows по двойному соединению между таблицами
Profiler не отображает верно наименования БД и объектов
Репликация на коленке. Свой TransactionLog.
Сентябрьский семинар в ТАЛГАРе по MS SQL Server
Вложенный курсор не видит переменной
SQL Server съедает всю память
Как можно сделать такое...???
Internal SQL Server error
TruncateLogOnCheckpoint ?
havig и union работают некорректно ?

[В начало]

Вопросы остались без ответа

de
Установка утилиты экспортирования данных лога счетчиков
Пацаны ну очень нужно сконвертировать базу из Access в Microsoft SQL Server
2Гладченко. Помогите, не создается snapshot
Исталляция DTS у клиента
Хелп !!! Ошибка инициализации остнастки
Ишу материалы по теме Distributed Databases применительно к MS SQL
Ошибка поиска IndexServer
SQL2000 на Win2003 Server
Extened Stored Procedure in Delphi, NText passing
Соединение 1C и MS SQL через ADO
logins
MSDE & Excel: использование значения ComboBox во View...
И снова про MS SQL Notification service...
Помогите с 10038 Attempt to initiate a new SQL Server operation with results....
Может ли глючить MS SQL 7.0?
Нужен ли FULL-TEXT для данных в кодировке ISO-8859-5 ?
Сообщение Could not locate file 'BM_Log' in sysfiles.
Интеграция в DBGrid

[В начало]

ПОЛЕЗНОСТИ

Администрирование Microsoft SQL Server 2000. Учебный курс MCSA/MCSE. Сертификационный экзамен №70-228 (с CD-ROM)
(2-е издание)

Издательство: Русская Редакция

Книга посвящена сопровождению СУБД SQL Server 2000. Здесь рассмотрены планирование, установка, обновление и администрирование SQL Server 2000. Подробно обсуждаются логическая и физическая структура баз данных, процессы восстановления и резервного копирования, управление доступом и разрешениями в SQL Server 2000, реализация и автоматизация административных задач. Освещаются вопросы мониторинга производительности и активности SQL Server, а также проблемы выбора типа и модели репликации. Отдельная глава посвящена обеспечению повышенной доступности баз данных SQL Server. Учебный курс адресован профессионалам, занимающимся развертыванием и сопровождением SQL Server 2000, а также тем, кто хочет подготовиться к сдаче экзамена №70-228 "Installing, Configuring, and Administering Microsoft SQL Server 2000 Enterprise Edition" по программам сертификации MCSA (Microsoft Certified Systems Administrators) и MCSE (Microsoft Certified Systems Engineer). Издание состоит из 16 глав, приложения и предметного указателя. Прилагаемый к книге компакт-диск содержит 120-дневную пробную версию Microsoft SQL Server 2000 Enterprise Edition, а также словарь терминов, учебные и справочные материалы.

Глава 1. Основные сведения о SQL Server 2000
Глава 2. Установка SQL Server 2000
Глава 3. Подготовка к работе с SQL Server 2000
Глава 4. Переход на SQL Server 2000
Глава 5. Системные и пользовательские базы данных
Глава 6. Создание и конфигурирование пользовательских баз данных
Глава 7. Заполнение базы данных
Глава 8. Разработка стратегии восстановления данных
Глава 9. Резервное копирование и восстановление баз данных
Глава 10. Управление доступом к SQL Server 2000
Глава 11. Управление разрешениями SQL Server
Глава 12. Администрирование SQL Server
Глава 13. Автоматизация административных задач
Глава 14. Мониторинг производительности и активности SQL Server
Глава 15. Репликация баз данных
Глава 16. Обеспечение повышенной доступности
Приложение. Вопросы и ответы.
Предметный указатель

[В начало]


Вопросы, предложения, коментарии, замечания, критику и т.п. присылайте Александру Гладченко на адрес: mssqlhelp@pisem.net

sql.ru Описание рассылки

МИНИФОРМА
ПОДПИСКИ




http://subscribe.ru/
E-mail: ask@subscribe.ru
Отписаться
Убрать рекламу

В избранное