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

MS SQL Server

  Все выпуски  

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


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

#233<<  #234

СОДЕРЖАНИЕ

1.СТАТЬИ
1.1.Изменение столбца таблицы, участвующей в репликации
1.2.Snapshot - изоляция транзакций
2.ССЫЛКИ НА СТАТЬИ
2.1.Статьи на русском языке
2.2.Англоязычные статьи
3.ФОРУМ SQL.RU
3.1.Самые популярные темы недели
3.2.Вопросы остались без ответа
4.АНОНСЫ
4.1.Microsoft Imagine Cup 2005

СТАТЬИ

Изменение столбца таблицы, участвующей в репликации

По материалам статьи Paul Ibison: Altering a column on a Replicated Table
Перевод Маргариты Баскаковой

Иногда структура таблицы, участвующей в репликации нуждается в изменении. Для этого может быть несколько причин - изначально неправильный выбор типа данных, отсутствие значения по умолчанию или необходимость переименовать столбец. Попытка изменить структуру таблицы непосредственно закончится ошибкой:

"Cannot alter/drop the table 'tablename' because it is being published for replication".
"Невозможно изменить/удалить таблицу 'имя таблицы', так как она опубликована для репликации".

Так как же изменить существующий столбец, не отключая репликацию? Допустим, мы хотим сделать следующие изменения структуры:

на

Метод, который мы выбираем, зависит частично от типа репликации и размера таблицы, но есть два основных варианта:

  1. изменение подписок

      exec sp_dropsubscription   @publication =  'tTestFNames' 
         ,  @article =  'tEmployees' 
         ,  @subscriber =  'RSCOMPUTER'
         ,  @destination_db =  'testrep' 
      
    
      exec sp_droparticle  @publication =  'tTestFNames'
         ,  @article =  'tEmployees'
      
    
      alter table tEmployees alter column Forename varchar(100) null
      
    
      exec sp_addarticle  @publication =  'tTestFNames' 
         ,  @article =  'tEmployees' 
         ,  @source_table =  'tEmployees' 
      
    
      exec sp_addsubscription  @publication =  'tTestFNames'
         ,  @article =  'tEmployees'
         ,  @subscriber =  'RSCOMPUTER' 
         ,  @destination_db = 'testrep' 

    Для репликации моментальных снимков (Snapshot Replication) это очевидный выбор. Мы удаляем подписку на эту статью, удаляем статью, затем вносим изменения в таблицу. Далее в обратном порядке (добавляем статью, добавляем подписку на статью). В следующий раз, когда Snapshot Agent (агент снимков) будет запущен, он соберет новую схему без всяких проблем.
    Для репликации транзакций (Transactional Replication) мы тоже можем выбрать сценарий, описанный выше. Однако мы должны быть более аккуратны в этом случае. По умолчанию операции вставки, изменения и удаления, выполненные на издателе, распространяются на подписчике в форме вызова хранимой процедуры. Изменяя определение столбца, мы возможно должны изменить связанные хранимые процедуры на всех подписчиках. Дополнение значения по умолчанию сложностей не вызовет, но непосредственное изменение типа поля как описано выше будет требовать модификации аргументов хранимых процедур. Для таблицы tEmployees из примера выше, эти процедуры существуют на подписчике в виде:

    sp_MSins_tEmployees,
    sp_MSupd_tEmployees,
    sp_MSdel_tEmployees.

    Они могут быть сгенерированы на издателе с помощью хранимой процедуры sp_scriptpublicationcustomprocs, но для этого потребуется, чтобы система была в пассивном состоянии, то есть во время этих (быстрых) изменений не должно быть никаких других изменений данных подписчика. Затем всех подписчиков необходимо полностью синхронизировать.
    Это ситуация не идеальна и влечет за собой скрытые проблемы, столкновение с которыми неизбежно. Обычно, когда вы добавляете новую статью в уже существующую публикацию транзакционного типа, при запуске Snapshot Agent (агента моментальных снимков) он создаст снимок только новой статьи. В нашем случае он создаст снимок таблицы 'tEmployees'. Таким образом, чтобы избежать всех проблем и сложностей, упоминавшихся выше, наиболее простым решением является запуск Snapshot Agent (агент моментальных снимков) немедленно после выполнения хранимой процедуры sp_addsubscription и уже затем выполнить синхронизацию.
    В репликации сведением (Merge Replication) нет никакой возможности удалить подписку, основываясь на использовании сценария, описанного выше, как при репликации транзакций и репликации моментальных снимков. Если мы удалим подписку, полностью включающую все статьи (sp_dropmergesubscription), то в случае если моментальный снимок уже был создан, попытка запустить sp_dropmergearticle приведет к ошибке ("cannot drop article ' article_name' from publication ' publication_name' because a snapshot is already generated"). Поэтому мы должны установить значение force_invalidate_snapshot в 1, сделать изменения в таблице на издателе, и вновь добавить статью. Затем добавить подписку с требованием первоначальной синхронизации данных с издателем, предварительно создав новый снимок для всех статей в этой публикации. Инициализация без первоначальной синхронизации возможна, но это может привести к существенным ограничениям будущих изменений, и я оставлю это другой статьи.

  2. оперативное изменение таблицы

    В случаях если таблицы большие, и мы не хотим запускать новый моментальный снимок - это касается как случаев с одной таблицей (репликация транзакций) так и всей публикации (репликация сведением) - существует альтернативный метод. Мы можем использовать для изменений системные хранимые процедуры sp_repladdcolumn и sp_repldropcolumn (обратите внимание, что эти процедуры ограничивают типы поддерживаемых подписчиков - только SQL Server 2000). Используя эти хранимые процедуры, мы можем добавить фиктивный столбец для временного хранения данных, удалить старый столбец, добавить новый столбец правильного типа, и переместить данные обратно. Скрипт будет выглядеть следующим образом:

      exec sp_repladdcolumn  @source_object =  'tEmployees'
         ,  @column =  'TempForename' 
         ,  @typetext =  'varchar(100) NULL' 
         ,  @publication_to_add =  'tTestFNames' 
      
    
      update tEmployees set TempForename = Forename
      
    
      exec sp_repldropcolumn  @source_object =  'tEmployees' 
         ,  @column =  'Forename' 
      
    
      exec sp_repladdcolumn  @source_object =  'tEmployees'
         ,  @column =  'Forename' 
         ,  @typetext =  'varchar(100) NULL' 
         ,  @publication_to_add =  'tTestFNames' 
      
    
      update tEmployees set Forename = TempForename
      
    
      exec sp_repldropcolumn  @source_object =  'tEmployees' 
         ,  @column = 'TempForename'

Хотя вышеупомянутый сценарий может использоваться для репликации транзакций или репликации сведением, внутренняя методология различна из-за отличающегося характера этих двух методов. Для репликации сведением, детали обновленных строк были бы сохранены в MSmerge_contents, и если указанная строка была изменена один раз или сто, в этой системной таблице будет только одна запись (для синхронизации/репликации), в то время как при репликации транзакций, 100 изменений строки приведут к 100 обновлениям подписчика. Это означает, что репликация сведением, имеет преимущество перед репликацией транзакций, потому что нам нужно выполнить 2 изменения каждой сроки, чтобы сделать изменение схемы.

[В начало]

Snapshot - изоляция транзакций

По материалам статьи Narasimha Rao AV: Snapshot Isolation
Перевод Александра Гладченко

Эта статья описывает разные уровни изоляции, использующиеся в SQL Server, а также освещает одно из новшеств следующей версии этой СУБД под кодовым название Yukon, Snapshot - изоляцию. Описание Snapshot – изоляции будет сопровождаться примерами, и некоторыми фактами, которые могут показаться неожиданными при использовании этого нового для SQL Server уровня изоляции транзакций.

Хронология:

Как Вы, наверное, знаете, в Yukon появился новый уровень изоляции транзакций, названный Snapshot - изоляцией. Разработчикам, которые знакомы с базами данных Oracle, уже известны аналогичные решения. Давайте, для начала, сделаем небольшой, краткий обзор существующих уровней изоляции транзакций в SQL Server 2000.

1. Read Uncommitted
2. Read Committed
3. Repeatable Read
4. Serializable

Уровни изоляции призваны обеспечить в СУБД правила параллелизма и последовательности работы с данными. Когда устанавливается уровень изоляции, множество пользователей, работающих с одними и теми же наборами данных (одни и те же значения данных в столбцах и строках таблицы), устанавливают блокировки или следуют основанным на установленном уровне изоляции правилам. По умолчанию, устанавливается изоляция Read Committed, и эта установка действует в рамках сеанса. Основной принцип состоит в том, что пишущая транзакция всегда блокирует читающие транзакции, если они имеют уровни изоляции выше её, исключая Read Uncommited. Когда установлен уровень Read Uncommited, пишущая транзакция не блокирует читающие, а читающие не блокируют запись. Таким образом, Вы имеете возможность составить запрос таким образом, что получите грязные данные, которые ещё не сохранены в базе данных, и этим будет нарушен принцип последовательности. Когда установлен Read Committed, прочитать можно только сохранённые данные. Но как только читающая транзакция завершит процесс чтения данных, даже если сама транзакция к этому моменту ещё не завершена, её блокировка уже не будет препятствовать изменениям в этих данных. При использовании Repeatable Read, когда в одной транзакции читаются порции данных, одни и те же данные будут считаться каждый раз, когда происходит чтение в этой транзакции. Поэтому, даже в моменты, когда чтение данных не выполняется, другие транзакции не смогут изменять данные, но они смогут осуществлять вставки новых данных в таблицу или в диапазоны данных, которые в этот момент не блокированы. Уровень Serializable идёт на шаг дальше по отношению Repeatable Read и защищает все другие блоки данных от вставок. Это называется предотвращением фантомных чтений.

Snapshot - изоляция

Представленная выше краткая хронология уровней изоляции SQL Server 2000 демонстрирует то, что кроме Read Uncommited, во всех других уровнях изоляции запись блокирует чтения. Не существует опций на сеансовом уровне, которые бы предписывали запрет установки блокировки пишущей транзакцией для читающих транзакций (кроме использования хинта NOLOCK). Когда транзакция читает данные, иногда допустимо обращаться к уже сохранённым данным, без учёта последних или текущих изменений данных, но зато при этом избежать блокировок. Чтобы реализовать такую возможность, идя на встречу пожеланиям пользователей, в Yukon введён новый уровень изоляции, названным уровнем Snapshot - изоляции. Когда для сеанса установлен этот уровень изоляции, читающие транзакции получают предыдущую копию данных.
Перед изучением того, как новый уровень изоляции реализован в Yukon, сделаем краткий обзор того, как включить эту возможность для баз данных.


ALTER DATABASE Database SET ALLOW_SNAPSHOT_ISOLATION ON;

По умолчанию эта опция выключена - OFF. Вы можете узнать состояние этой опции, запросив данные из sysdatabase.


Select name, snapshot_isolation_state, snapshot_isolation_state_desc from sys.databases

Использование Snapshot – изоляции будет разрешено (ON) только после того, как выполняющиеся в настоящее время транзакции будут завершены. До этих пор состояние этой опции будет находиться в промежуточном состоянии: Pending_On (или Pending_Off при попытке отключить опцию). Наряду с опцией ALLOW_SNAPSHOT_ISOLATION, Вы можете установить опцию READ_COMMITTED_SNAPSHOT на всю базу данных.


ALTER DATABASE Database SET READ_COMMITTED_SNAPSHOT ON;

Когда опция READ_COMMITTED_SNAPSHOT будет включена, читающие транзакции в сеансе с уровнем Snapshot - изоляции не будут иметь возможность установить общую блокировку ресурса. Вы можете проверить установку состояния READ_COMMITTED_SNAPSHOT, сделав запрос к таблице sysdatabases.


Select name, is_read_committed_snapshot_on from sys.databases

Этот запрос возвращает 0 или 1. После того, как Вы включите Snapshot - изоляцию на уровне базы данных, станет возможным использовать уровень Snapshot - изоляции в рамках сеанса, если для него будет установлена следующая опция:


SET TRANSACTION ISOLATION LEVEL SNAPSHOT

Интересный момент, на который стоит обратить здесь внимание, это то, что вышеупомянутая инструкция не выдаст ошибку, если Snapshot – изоляция не разрешена на уровне базы данных. Но это возвратит ошибку, когда в сеансе будет предпринята попытка исполнения любой DML (не DDL) инструкции.

Msg 3952, Level 16, State 1, Line 1
Transaction failed in database 'TestDbase' because the database does not allow snapshot isolation. Use ALTER DATABASE to allow snapshot isolation.

Давайте теперь посмотрим на примере, как работает Snapshot – изоляция. Создайте в базе данных простую таблицу с именем Transactions, скрипт создания которой представлен ниже:


Create Table Transactions
(
TranID int identity(1,1),
TranName nvarchar(1000)
)
Go
Insert Into Transactions Values('ExistingTran1');
Insert Into Transactions Values('ExistingTran2');
Insert Into Transactions Values('ExistingTran3');
Go

Установите для базы данных уровень Snapshot - изоляции, если Вы ещё этого не сделали.


ALTER DATABASE <<Database>> SET ALLOW_SNAPSHOT_ISOLATION ON;
GO
ALTER DATABASE <<Database>> SET READ_COMMITTED_SNAPSHOT ON;
GO

Теперь откройте два разных сеанса. Пробуйте в одном сеансе изменить одну из строк в представленной выше таблице, и, в то время когда транзакция активна, читайте из этой таблицы в другом сеансе. Выполните показанные ниже два скрипта в двух сеансах, один за другим.


-- Для сеанса 1: Запустите этот скрипт первым
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
GO
BEGIN TRAN
GO
Update Transactions Set TranName = 'Tran1' Where TranName = 'ExistingTran1' 
GO 

-- Для сеанса 2
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
GO
BEGIN TRAN
GO
Select * from Transactions
GO

При исполнении инструкции SELECT из второго сеанса, запрос будет блокирован, так как заданным по умолчанию уровнем изоляции установлен Read Committed, и можно читать только сохранённые данные. Так как транзакция первого сеанса еще не завершена, второй сеанс будет заблокирован, и Вы увидите не изменённые данные из снимка. Теперь выполните транзакцию из второго сеанса на уровне Snapshot - изоляции. Чтобы сделать это, используйте следующий скрипт:


COMMIT TRAN
GO
SET TRANSACTION ISOLATION LEVEL SNAPSHOT
GO
BEGIN TRAN
GO
Select * from Transactions
GO

Вы снова увидите предыдущую копию данных из таблицы Transactions. Но в этом случае, второй сеанс не будет блокирован первым сеансом, где транзакция не закончена. Данные, которые Вы увидите, будут теми данными, которые также были перед началом транзакции первого сеанса. Еще один момент, который стоит отметить, Вы можете изменить уровень изоляции, не заканчивая транзакцию. Но ошибка все-таки будет получена, когда Вы выполните выборку, и в ней будет сообщаться, что Snapshot – изоляция не была установлена, когда была начата транзакция. Ошибка показана ниже.

Msg 3951, Level 16, State 1, Line 1
Transaction failed in database 'TestDbase' because the statement used snapshot isolation but the transaction did not start in snapshot isolation.

Еще один интересный момент, даже после завершения транзакции первого сеанса, Вы все еще будете видеть старые данные во втором сеансе со второй транзакцией. Как только Вы завершите второй сеанс (завершите транзакцию, выполните переподключение или установите SET TRANSACTION ISOLATION LEVEL READ COMMITTED) и исполните выборку снова, тогда в неё попадут изменённые данные. До выполнения этих действий, повторное исполнение выборки всегда будет возвращать не изменённые данные.

Совет: как только транзакция начинается с уровнем Snapshot – изоляции, запросы на выборку всегда будут возвращать одни и те же данные до момента окончания транзакции, и это не зависит от состояния других транзакций, работающих с данными.

Как это всё работает:

Как в Yukon реализована Snapshot – изоляция, это интересная тема для изучения. С этого момента автор предполагает, что для базы данных разрешена Snapshot – изоляция, если он специально не оговаривает иного. Каждой исполняемой транзакции присваивается порядковый номер операции. Когда в рамках транзакции изменяются данные, Yukon делает копию первоначальных данных в TempDB и хранит вместе с ними номер операции. Когда другой сеанс запрашивает те же самые данные, процессор запросов возвратит данные из TempDB. В TempDB могут быть сохранены несколько версий данных, если одни и те же данные изменялись несколько раз. Но процессор запросов будет возвращать те данные, номер операции которых наиболее близок номеру операции читающей транзакции. Это объясняет представленный выше совет. Если перефразировать этот совет в терминах транзакций, то считываемые из TempDB данные будут всегда читаться этой транзакцией из TempDB.
После установки для базы данных Snapshot – изоляции, каждая изменяемая строка получит дополнительный привесок в 14 байт, нужный для хранения порядкового номера операции. Кроме этого, ресурсы TempDB будут использованы для хранения разных версий данных, на основании их порядковых номеров операций. Концепцию маркировки каждой строки порядковым номером операции принято называть Версионность Строк.

Автор надеется, что эта статья дала основные понятия того, чем является Snapshot – изоляция, и что нужно для начала её использования. Ваши комментарии направляйте по адресу: avnrao@gmail.com

[В начало]

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

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

Разрешение проблем подключения к SQL Server 2000
Перевод Ирины Наумовой
MSSQLServer: Эта статья ориентирована на то, чтобы помочь Вам решить проблемы, возникающие при подключении к SQL Server 2000, в ней описаны основные проблемы такого типа и действия, которые Вы можете предпринять, чтобы их разрешить...

[В начало]

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

Optimizing Cursor Performance
Kalpesh Thaker
The best performance improvement technique for cursors is not to use them at all if you can avoid it. As I've experienced, SQL Server works much better with sets of data than with individual rows. It's a relational database, and row by row access has never been the strong suit of relational DBMSs. That speaks, there are times when using cursor is unavoidable, so here are a few quick tips for optimizing them

Installing the AdventureWorks DB on SQL Express
Enjoy Every Sandwich
Some people just seem to think it's just terrible that the sample databases don't happen to ship with or install with SQL Server 2005 Express. There are basically four reasons why Microsoft chose to do this from what I can tell

Password policies on object passwords
Bob Beauchemin's Blog
A new feature of SQL Server 2005 that has been fairly well publicized is the ability, on Windows 2003 operating systems, to enforce password stregth, expiration, and lockout policies on SQL Server logins, as the operating system enforces them on Windows logins. The way that this works is that SQL Server calls NetValidatePasswordPolicy, a Win32 function available on Windows 2003. So if I have a machine policy (either standalone or more likely inherited from a domain policy) that a password must be at least 8 characters long, the following DDL will fail

Dealing with very large bitmasks
adam machanic
Continuing in my series of things you should probably not do in SQL Server but sometimes have to, I'm going to do a few posts on dealing with very large bitmasks

CREATE proc track_waitstats & CREATE proc get_waitstats - useful code for diagnosing SQL 2000 performance
Mat Stephen's WebLog
For those attending my TechNet SQL 2000 performance tuning session at TVP Reading on Tuesday 25th Jan, here is the code for the track_waitstats and get_waitstats stored procedures I refer to during the presentation

Fun with static XQuery evaluation - 4 - answers and wrapup
Bob Beauchemin's Blog
Here's the answers to the question from Fun With static XQuery evaluation - 2

Crime Fighter BI
Ted Kemp
I might be the one person in the United States who's never watched a single episode of CSI Wherever-It-Is-Now. That doesn't mean crime shows can't hold my attention, though. It's just that, being more the analytical sort, I'm drawn to the factual, documentary-type criminal cases shown on Court TV, A&E, Discovery and the like

Writing Language-Portable Transact-SQL
Ken Henderson
Ken discusses the enhanced localization features in SQL Server 2000 that make it much easier to write Transact-SQL code that is portable across languages. (9 printed pages)

Database Fundamentals
Mike Chapple
Databases are designed to offer an organized mechanism for storing, managing and retrieving information. They do so through the use of tables. If you’re familiar with spreadsheets like Microsoft Excel, you’re probably already accustomed to storing data in tabular form. It’s not much of a stretch to make the leap from spreadsheets to databases. Let’s take a look

Analysis Services 2000 vs. 2005
I have run across a presentation called “Analysis Services 2000 vs. 2005” prepared by Jaimie Basilico and Mark Frawley (Jamie works in Microsoft as Senior Technology Specialist in the East Cost, and he is one of the best field people in Analysis Services that we have). This presentation is targeted towards people who are familiar with Analysis Services 2000 and want to come on speed with Analysis Services 2005. I have found the presentation very useful, but not all subjects are covered in the same depth. Below are my comments
How to Configure Virtual Server 2005 in Order to Setup a Test SQL Server Cluster
Brad M. McGehee
There are a lot of DBAs who want to learn how to cluster SQL Server. There are also a lot of companies who may have a production SQL Server cluster, but not a test SQL Server cluster. In both cases, the reason for this is that clustering hardware is very expensive, and setting up a non-production SQL Sever cluster is out of the question from a budgetary perspective

Server Performance Advisor
Kevin Kline
There’s an interesting Microsoft tool called the Server Performance Advisor (SPA) v1.0 available at http://www.microsoft.com/downloads/details.aspx?FamilyID=61a41d78-e4aa-47b9-901b-cf85da075a73&displaylang=en

SQL Server 2005 - Interface Overview
Steven Warren
In my last article, we went over how to install SQL Server 2005 and what it entailed. In this article, we will continue by giving you an overview of what the new interface looks like. Let's begin by exploring the menu bar as shown in Figure A

Controlling Stored Procedure Caching with ... Dyanmic SQL?!?
adam machanic
Tell me if this situation sends a chill down your spine: You've written a stored procedure, tested it against a variety of inputs, and finally rolled it out in production. All is well... Or so you think. You start getting complaints from some users that it's taking forever to return. But other users are having no problem. What the..?

Counting occurrences of a substring within a string
adam machanic
I have absolutely no idea why anyone wants to do this, but I keep answering the same question in forums: "How do I count the occurrences of a substring [note: usually comma] within a string?"

Splitting a string of unlimited length
adam machanic
There are many techniques for splitting a string in T-SQL (in other words, taking a character-delimited string and producing a table of the values), the best of which are encapsulated in Erland Sommarskog's famous article. My favorite of his string splitting techniques is adapted from a previous example that was created by Anith Sen

Validate a URL from SQL Server
adam machanic
File this one in your folder of things you should probably never use -- but maybe, some day, in an emergency, you'll need this

Batch Compilation, Recompilation, and Plan Caching Issues in SQL Server 2005
Arun Marathe
This paper explains how batches are cached and reused in SQL Server 2005, and suggests best practices on maximizing reuse of cached plans. It also explains scenarios in which batches are recompiled, and gives best practices for reducing or eliminating unnecessary recompilations

Correction on bitmask handling
Adam Machanic
In the article on handling bitmasks I posted the other day, I made a fatal error in the splitBitmask function. The function treated the low byte as the first byte, instead of the high byte. Therefore

Bitmask Handling, part 2: Bitmask reconstitution
Adam Machanic
Posting the first part of my series on bitmasks (yes, this is now officially a series) taught me a lot about my readers: You don't care about handling bitmasks in the database. And I respect you for that! I'm overjoyed, as a matter of fact! That article has received the least hits of anything I've posted in this blog to date. So good for you for not clicking

Password policies on object passwords
Bob Beauchemin's Blog
A new feature of SQL Server 2005 that has been fairly well publicized is the ability, on Windows 2003 operating systems, to enforce password stregth, expiration, and lockout policies on SQL Server logins, as the operating system enforces them on Windows logins. The way that this works is that SQL Server calls NetValidatePasswordPolicy, a Win32 function available on Windows 2003. So if I have a machine policy (either standalone or more likely inherited from a domain policy) that a password must be at least 8 characters long, the following DDL will fail

Fun with static XQuery evaluation - 1
Fun with static XQuery evaluation - 2
Fun with static XQuery evaluation - 3
Fun with static XQuery evaluation - 4
Bob Beauchemin's Blog
There's been lots of puzzled faces lately when I try to explain doing XQuery against strongly typed XML (XML typed by a SCHEMA COLLECTION) vs untyped XML. The largest FAQ is why when I have this document

Attributes in SQL Server 2005 and Visual Studio 2005
Niels SQL Server Blog
Recently there has been some discussions about SQL Server attributes in the beta newsgroups for SQL Server 2005 and VS 2005. Having tried to answer them, I thought it might be a good idea to write a blog entry about it as well

Coupling Outlook to SQL Server
Kevin Terry
I recently completed an project that I thought might be interesting to the SQL Server Community. First a little background of what my company does, as it's the only way I could think of to explain why I had to do this particular project

Finding and deleting duplicate rows from a table
Serdar Yegulalp
Large table rows should each have distinct values -- but what do you do if they don't? For instance, if data is imported from another source and not properly screened, you may notice duplicate values among rows instead. Duplicate values also crop up when a table that previously had no identity key (never a good idea) needs to have an identity key created for it; an identity key cannot be created for that table until the duplicate rows are removed. The bigger the table, the more time-consuming and difficult it may be to remove the duplicate rows

Deleting duplicate records within a single query
Michael Hotek
Hw can I delete duplicate records from a table in SQL Server 2000 using a single query? I have a table (Table1) with two fields: A,B.

How to improve SQL Server security
Barrie Sosinsky
There are several steps you can take to make SQL Server databases more resistant to tampering and hacking. Some are simply part of good server management, like keeping up with SQL Server's latest patches, while others involve active-user monitoring. The five steps below will get you started.

Using a Subquery in a T-SQL Statement
Gregory A. Larsen
Sometimes the criteria for determining which set of records will be affected by a SELECT, UPDATE, DELETE and/or INSERT statement cannot be obtained by hard coding the selection criteria. Occasionally there is a need to use the results of a SELECT statement to help determine which records are returned or are affected by a T-SQL statement. When a SELECT statement is used inside another statement, the inside SELECT statement is known as a subquery. Subqueries can help to dynamically control the records affected by an UPDATE, DELETE or INSERT statement, as well as to help determine the records that will be returned by a SELECT statement. This article will show different examples of how to use a subquery to help clarify the records affected or selected by a T-SQL statement

Database Benchmarking
Steve Callan
If you have seen advertising literature from major database system vendors, invariably you have seen statements about how that database performed against other systems (benchmark results). All of the major vendors support and participate in benchmarking tests because, to some degree, they have to. The mindset must be along the lines of "Everyone else is doing it, so we'd look odd not participating in the tests ourselves - even though most analysts agree the tests are somewhat artificial and flawed."

FormatDate.sql
Rusty Hansen
This script will create a UDF called FormatDate that allows you to format a date by simply supplying a format such as 'mm/dd/yyyy', 'yyyymmdd', 'dddd, mmmm d1, yyyy', etc. The comment header provides additional examples of how to use the function. The script has been tested on SQL Server 2000

One Welcome Service Pack
Don Jones
Our Beta Man offers an early look at what Windows Server 2003 SP1 will bring. After Windows XP Service Pack (SP) 2 came out, administrators started looking seriously at what Windows Server 2003 SP1 would bring. We knew that new features like the Windows Firewall would certainly be in SP1; after all, Win2003 and WinXP are cousins built on the same code base. But it wasn't clear what the actual implementation of SP1 would look like. Would the firewall be on by default? What new security features would be added? What risks would installing SP1 have on our environments?

What are the popular MDX functions?
Mosha Pasumansky
There are many MDX functions. The exact number depends on how you count (are methods and properties are counted, what about operators, are polymorphic functions counted once or as many times are there are overloads, what version of the Analysis Services we are talking about etc), but around 150 is probably right.

Understanding SET STATISTICS PROFILE
Randy Dyess
Often developers need to obtain an execution plan that they can save and send to others. Currently in SQL Server 2000 the only way to do that is to use text-based execution plans

SQL Server 2005: Two Little Known Features That Matter Big!
Ravindra Okade
SQL Server 2005 brings a host of new features to the table. Ravindra Okade details a couple of nuggets that are not easy to find but can be very useful to every developer and DBA. Synonyms are very handy for managing database objects. And non-clustered index included columns, although a mouthful, is a unique feature that can drastically optimize queries

Using the SQLCMD in SQL Server 2005
Andre Vigneau
Basic command prompt script tools will be around for some time to come (and more I hope), so better get used to it. Many things can be accomplished using those simple “scripts runner”. It always been part of my tool box and many of my admin or troubleshooting scripts are automated using it

SQL Server 2005 Amid DBMS Market Dynamics
Peter O'Kelly
Microsoft positions its DBMS for the next wave of competitors. Last month's Trends & Analysis column provided an overview of database management system (DBMS) trends and the reasons why DBMSs have a resurgent and expanding role in the broader application platform landscape. This month's column assesses Microsoft's SQL Server 2005 product line, in terms of both how Microsoft is addressing DBMS trends and how Microsoft is poised to compete with IBM, Oracle, and open source DBMS initiatives

Trace Messages Part III: Ending Sessions and Adding Metrics
Andrew Novick
The current theme is about application trace messages. The previous two articles (Part I and Part II) described the AppSession and the AppSessionTrace tables and the stored procedures that insert and update their rows. So far we have

Microsoft SQL Server 2005. DB Mirroring and BCP may not mix so well
Larry Chesnut
Well, back in the good ol’ US of A only a day, and I already miss England’s ambrosia, Guiness stout on draft. Actually, it was really hard to leave England. It was like a story book visit. I woke up on my first day in England last Sunday morning to church bells ringing. And then yesterday morning I likewise departed for the airport with the bells again tolling. Folks, it doesn’t get much better than that. Microsoft has a training facility in a quant little town called Chertsey, and every morning I walked from my 400 year old hotel, down a coble stoned lane to the classroom. What a dichotomy, I’m delivering a Yukon Ascend class in a village more than a thousand years old. Yet, the merging of the new with the old seemed so smooth and natural

The Three Ms of BI: Manage, Monitor and Model
Guy Creese
Here is a tripartite look at the world of business intelligence. Editor's note: Guy Creese in a DMReview.com monthly columnist. He writes on the subject of Volume Analytics and discusses online best practices. His column appears the third week of each month. Check it out at www.dmreview.com

The Integration of Unstructured Data into a Business Intelligence System
William N. McCrosky
This article discusses the challenges of merging unstructured data into BI systems and provides an example of such a merge to solve an organizational problem

Exchanging XML with SQL Server 2000 and Reporting Services through the Web and Web Services
Venkat Prasad
Venkat Prasad discusses some programming techniques for saving XML data from Microsoft SQL Servers, Web Servers, XML Web Services, and Microsoft SQL Reporting Servers. Topics include a comparison of traditional techniques used for saving XML streams, using ASP/ASPX and COM, with newer ones using .NET Framework Classes—datasets, XMLTextReaders and XMLTextWriters, XSLTransformation, saving data from SQL Reporting Servers, and uploading XML back to SQL Server. (15 printed pages)

Get your backup problems fixed remotely
Jo Maitland
Advanced Digital Information Corp.,(ADIC), is proposing to fix its users' backup problems over the Web with a new service called iSurety.

SQL Server 2005 T-SQL Enhancements
Jim Duffy
SQL Server 2005 or "Yukon" is going to be a major SQL Server update containing updates to nearly every facet of the program, including T-SQL. In this article I am going to explore some of the new T-SQL features, commands, and capabilities in SQL Server 2005. Because covering everything new in T-SQL would require an entire chapter in a book, I am going to cover some of the more useful and mainstream enhancements

Rebuilding SQL Server Cluster Nodes
Muthusamy Anantha Kumar
Active/Passive SQL Server 2000 clustering gives more reliability and fault tolerance to Production SQL Server environments. When a failure occurs, all of the resources fail over from the active node to the passive node and make the passive node active. This article explains how to rebuild the node that failed and attach it back to the cluster

SQL Server 2005. BACKUP LOG WITH TRUNCATE_ONLY has gone away
Randy Dyess
Just a quick blog today on a SQL Server 2005 Transact-SQL change. Often in the past a developer would create a query that did not run exactly how they wanted and they filled the transaction log. It didn't matter that you keep plenty of space for the log and that the log could auto-grow without a limit, the developer would kick off some query and a few hours later you would have GBs of data being placed into the log and just hose it.

SQL Server Performance Top Tip: Multi Processor (SMP) sudden death syndrome
Mat Stephen's WebLog
You’ve been really proud of your nice new multi processor box, its got eight processors and some serious grunt. Everyone has been really pleased with the system’s lightening responsiveness and the big boss thinks you’re a super computer guru – looks like a pay rise is on its way

Data Dictionary from within SQL Server 2000
Mindy Curnutt
There is functionality within SQL Server 2000 that allows you to enter metadata on the columns in the SQL Server. In fact, the 'Description' field (shown below) is a meta data field that comes right with SQL Server. This functionality can be used to create a traditional "Data Dictionary" - allowing you to define the purpose of each column and then to list all the tables and columns (with their fully described purpose and meaning) in a Dictionary type fashion. The difficulty is generally not easy to populate or query this data

Detecting and Reporting Errors in Stored Procedures - Part 2: SQL Server 2005 TRY-CATCH Blocks
Rob Garrison
If you haven't already read it, take a few minutes now to read "Part 1: SQL Server 2000" for background. This article (Part 2) assumes that you have read Part 1 and will discuss only the new TRY-CATCH blocks in SQL Server 2005. TRY-CATCH blocks in T-SQL allow error detection and reporting in a construct similar to that used in VB .NET, C#, and C++. The specific focus here is how TRY-CATCH blocks are used in stored procedures and where there might be some surprises

Searching the SQL Server ErrorLog with a Stored Procedure
Andrew Novick
There are several ways to log messages in SQL Server; I’d guess that you’re familiar with many of them. Here are some that I know about

Getting to Know I/O
Brian Moran
Two weeks ago, in "Zen and the Art of Hardware-Resource Distribution" ( http://lists.sqlmag.com/t?ctl=E5F:7B3DB ) I said many people have I/O problems they don't know about. If you think you might be one of those people (or even if you know SQL Server I/O Inside and Out--capitalization pun intended ), you can learn about I/O requirements for SQL Server database file operations in a new Microsoft white paper, "SQL Server 2000 I/O Basics" ( http://lists.sqlmag.com/t?ctl=E59:7B3DB ) by Bob Dorr, an escalation engineer with SQL Server Product Support Services.

SQL Server 2000 I/O Basics
Bob Dorr
Learn the I/O requirements for Microsoft SQL Server database file operations. This will help you increase system performance and avoid I/O environment errors

Who lives in Rectangle under a Tree? Spongebob Squaredata!
Enjoy Every Sandwich
RebelGeekz offers up ideas for XML 2.0 that's been running on a background thread for me all day. I've really been trying to see value in my world for what he's proposed in response to Mike Champion's query for XML 2.0 ideas

DB Mirroring and Merge Replication
Larry Chesnut
My class last week had several very good questions for which I did not have an immediate and solid response. So as an agreement with them I promised to post their questions and answers on my blog. One of their questions was what happens if merge replication is in place in which a subscriber is Shiloh (SQL Server 2000) and a db mirroring failover happens? For transparent client redirect, would the Yukon (SQL Server 2005) SNAC applied to the Shiloh box be sufficient, or does the whole MDAC 2.9 need to go on? But perhaps more importantly, since merge repl implies people disconnecting and shutting down their laptops that means relying solely on MDAC caching for the redirection is not an option. Thus, how does one hard code for the mirror server on a Shiloh subscriber?

Understanding the estimated rows column in an execution plan
TransactSQL.Com
The number of rows estimated by the optimizer shown in the execution plan can be a major factor in how the optimizer creates the execution plan. Understanding the number of estimated rows can help a developer in understanding the options used by the optimizer to create an execution plan. A large number of estimated rows can tell the developer why a merge join is more appropriate than a nested loop or why an index scan is favored over an index seek. Developers should investigate situations when small numbers of estimated rows with large estimated costs are seen in execution plan

Creating a Classification Matrix Report
DMTeam
This tip shows how to create a Reporting Services report that emulates the Classification Matrix in BI Dev Studio. Reporting Services makes an excellent delivery vehicle for your data mining results. In addition to exposing query results, you can also use features of Reporting Services to enhance the functionality of DMX. For example, DMX lacks GROUP BY functionality, so you can take advantage of the Reporting Services grouping ability in data mining reports

Are SQL Server 2005 Web Services SOA's friend or foe?
Enjoy Every Sandwich
I've been reading Rocky Lhotka's posts from today on Remoting, SOA as RPC and Services having tiers. I think he's right about a lot of what he has to say and that got me thinking about SQL Server 2005's Web Services and Service Broker (again)

Bucketisation
Chris Webb's BI Blog
I couldn't think of a better title for this entry, but I'm sure there must be a better term for what I'm writing about... Anyway, the original solution I posted for the 'get the names of the currentmembers on all dimensions' problem last week reminded me of some MDX I came up with last year, for dynamic bucketisation

Performing Usage-Based Costing
Brian Moran
My company wants to charge application owners usage fees based on consumption of database resources, such as memory, CPU, I/O, the number of queries executed, and so on. Several third-party tools have this capability, but their data is based on sampling. We have many applications that run in less than 100ms, and a sampling approach misses much of this activity. Is there a comprehensive usage-based costing tool for SQL Server?

Materialize Your Views
Michelle A. Poolet
The next release of SQL Server, SQL Server 2005, will contain many features and extensions to make you more productive, especially if you're doing database-driven Web-application development. (For a preview of SQL Server 2005, check out the May 2004 issue of SQL Server Magazine.) However, Microsoft has delayed the final release of SQL Server 2005 until the first half of next year—and many production shops won't migrate to the new database system for at least a year after that. In the meantime, you can do plenty to optimize your SQL Server 2000 databases

An introduction to the benefits of online analytical processing (OLAP)
TechRepublic
OLAP is designed to convert data into usable information by allowing the aggregation of data - even when you don't know what characteristics may be important to the question

MS SQL Server to FireBird migration. That's a Pain!
firefalcon
A real example of database migration (MSSQL -> FireBird) Recently I read article Embedded Firebird at Code Project and decided to try FireBird. I like the idea of embedded database. FireBird allows .Net developer to put a dll into bin directory, create database file and use usual database access. It sounds very attractive and simple. In theory. So I decided to migrate from SQL Server to FireBird

A Simplified SQL-CSV Import/Export Functionality
codeajay
A simplified SQL-CSV import/export functionality. This small but important utility has been created for the users who would surely like to understand how to import and export data between SQL and CSV files. There are many alternatives to this utility. The (BCP) bulk copy of SQL provides a facility to insert multiple records through a single statement. You can also create a nice package to do this job. But I know C# and this is the way I do it. I don't know if I was Googling wrong but didn't find a nice code that can do this functionality in a more generalized manner, and of course, in a way that a normal user (coder) can understand it

Full Text Search on SQL 2000 Part 3
Don Schlichting
In the previous month's articles, Full Text Searching was introduced as a way to query strings with more refinement than the usual TSQL "like" or equal operator statements. With Full Text Searching, a new file system structure is created, storing key words from selected fields into Catalogs. In addition to storing typical character fields from databases, Microsoft Office documents that have been saved as binaries can also be entered into the Catalogs. In this month's edition, we will begin with the maintenance issues required to keep these Catalogs current

OLAP and GIS - Analysis Services and MapPoint
Mosha Pasumansky
Ever wanted to get the data from your Analysis Services cube into the geographic map. It is actually easier then you think. There is a little publicized free OLAP AddIn for Microsoft MapPoint which allows you to do exactly that. The way this AddIn works is it contains a wizard which builds MDX query behind the scenes, send it to the cube, and then uses standard MapPoint mechanism to map tabular resultset into the map

[В начало]

ФОРУМ SQL.RU

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

Ваше мнение об упражнениях SELECT на Ошибка! Недопустимый объект гиперссылки. Новые упражнения на Ошибка! Недопустимый объект гиперссылки. Суррогатные или естественные
В блокировочнике никогда нельзя быть уверенным за правильность отчета?!
Помогите начинающему поверить в мощь SQL!!!!
Какие грабли перевода базы на другой сервер у которого другой Server collation
Создание клиента на чистой от SQL Server машине
Почемув DML операторах INSERT,UPDATE,DELETE блокировку нельзя снять до окончания транзакц
еще раз по поводу XML
"Вложенные транзакции" или зачем нужна эта профанация ?
Пара вопросов по скриптам
Кэш для MSSQL
SQL Server тормозит с таблицей>3000000
Какие проблемы с MS SQL Server 2005?
Pomogite razobratsa
Обойти транзакцию
Merge replication: could not deliver snapshot...
СЕМИНАР: SQL Server 2005: WMI и другие инструменты DBA
запуск mcdtc в win98
Подскажите, кто может

[В начало]

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

YUKON + DTS + ORACLE : вoт тaкaя кaшa.
Описание DMV i DMF в SQL2K5
Вызов функции без префикса или синоним функции.
Как получить текущий @rownum для курсора зная его handle?
connection
linked server / distributed transaction
Linked server и все все все...
Поиск с помощью FTS
вопрос про свзязанный сервер
помогите со слиянием базы

[В начало]

АНОНСЫ

Microsoft Imagine Cup 2005

1 февраля начался первый этап студенческого соревнования Microsoft Imagine Cup 2005! У студентов и школьников России и СНГ появилась уникальная возможность принять участие в различных конкурсах с ценными призами от Microsoft:

  • Зарегистрируйтесь до 1 марта на сайте http://imagine.thespoke.net, примите участие в одном из конкурсов и получите Visual Studio.NET!

  • Примите участие в одном из конкурсов (например, ИТ, алгоритмы, визуальные игры и т.д.) и получите Microsoft Office 2003 Standard!

  • Создайте свою команду и представьте свой проект на конкурс программных проектов до 22 февраля. Лучшие команды будут приглашены для представления проектов на финал в Москву

Победители российского конкурса программных проектов, а также победители в онлайн-категориях Imagine Cup поедут на финал в Японию c общим призовым фондом более 200,000$!
Более подробная информация о соревновании - на студенческом сайте http://www.theSpoke.ru.

[В начало]


Вопросы, предложения, коментарии, замечания, критику и т.п. оставляйте Виталию Степаненко и Александру Гладченко в форуме: Обсуждение рассылки

СЕМИНАРЫ  КОНФЕРЕНЦИИ

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



ПУБЛИКАЦИИ  АРХИВ


http://subscribe.ru/
http://subscribe.ru/feedback/
Подписан адрес:
Код этой рассылки: comp.soft.winsoft.sqlhelpyouself
Отписаться

В избранное