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

MS SQL Server

  Все выпуски  

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


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

#228<<  #229

СОДЕРЖАНИЕ

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

СОВЕТЫ

Поддержка XML в Microsoft SQL Server 2005 (продолжение)

По материалам статьи Shankar Pal, Mark Fussell и Irwin Dolobowsky: XML Support in Microsoft SQL Server 2005
Перевод Виталия Степаненко

Вторичные индексы XML

Когда создан первичный индекс XML, можно создать вторичные индексы XML, чтобы ускорить выполнение запросов разных классов. Три типа вторичных индексов XML - PATH, PROPERTY и VALUE - дают выигрыш в запросах, основанных на пути, сценариях управления пользовательскими свойствами, и запросах, основанных на значениях, соответственно.

Индекс PATH строит сбалансированное дерево на столбцах (path, value) первичного индекса XML. Значение для пути рассчитывается из выражения пути; значение узла также используется, если оно существует. С известными основными полями индекса PATH поиск по индексу PATH увеличивает обработки выражения пути. Наиболее распространенным случаем является использование метода exist() на столбцах XML в выражении WHERE команды SELECT.

Индекс PROPERTY создает сбалансированное дерево на столбцах (PK, path, value) первичного индекса XML, где PK - первичный ключ базовой таблицы. Этот индекс помогает искать значения свойств в экземпляре XML.

И, наконец, индекс VALUE создает сбалансированное дерево на столбцах (value, path) первичного индекса XML. Этот индекс ускоряет выполнение запросов, где значение узла известно, но его путь неточно определен в запросе. Такая ситуация обычно возникает при поиске типа descendant-or-self, как, например, в //author[last-name="Howard"], где элементы <author> могут встретиться на любом уровне иерархии. Такая ситуация также возникает в запросах со специальными символами, таких, как /book [@* = "novel"], где запрос ищет элементы <book> с атрибутом, имеющим значение "novel". Индекс VALUE также полезен для сканирования набора значений для типизированного XML.

В иерархии XML может размещаться до 128 уровней; экземпляры XML, содержащие более длинные пути, не принимаются при вставке и изменении.

Кроме этого, индексируется до 128 первых байт значения узла; более длинные значения размещаются внутри системы и не индексируются.

Пример: поиск, основанный на пути

Предположим, что следующий запрос часто выполняется:


SELECT xCol
FROM   docs
WHERE  xCol.exist ('/book[@genre = "novel"]') = 1

Выражение пути /book/@genre и значение "novel" соответствуют ключевым полям индекса PATH. Соответственно, вторичный индекс XML типа PATH может помочь в этом случае:


CREATE XML INDEX idx_xCol_Path on docs (xCol)
  USING XML INDEX idx_xCol FOR PATH

Пример: получение свойств объекта

Рассмотрим следующий запрос, который получает свойства "genre", "title" и ISBN книги из каждой строки в таблице T:


SELECT xCol.value ('(/book/@genre)[1]', 'varchar(50)'),
  xCol.value ('(/book/title)[1]', 'varchar(50)'),
  xCol.value ('(/book/@ISBN)[1]', 'varchar(50)')
FROM docs

В этом случае можно использовать индекс свойств:


CREATE XML INDEX idx_xCol_Property on docs (xCol)
  USING XML INDEX idx_xCol FOR PROPERTY

Пример: запрос, основанный на значениях

В следующем запросе ось потомков descendant-or-self (//) определяет частичный путь, поэтому индекс VALUE помогает выполнять поиск, основанный на значениях ISBN:


SELECT xCol
FROM   docs
WHERE  xCol.exist ('//book[@ISBN = "1-8610-0157-6"]') = 1

Индекс VALUE создается следующим образом:


CREATE XML INDEX idx_xCol_Value on docs (xCol)
  USING XML INDEX idx_xCol FOR VALUE

Индексирование содержимого

Вы можете создать полнотекстовый индекс на столбцах XML; это индексирует содержимое значений XML, игнорируя разметку XML. Значения атрибутов не входят в полнотекстовый индекс (так как они считаются частью разметки), и тэги элемента используются как разграничительные знаки. Вы можете создавать и индексы XML, и полнотекстовые индексы на столбце XML, и совмещать полнотекстовый поиск с использованием индекса XML. Используйте полнотекстовый индекс в качестве первого фильтра, чтобы уменьшить выборку и потом применить XQuery для дальнейшей фильтрации.

Полнотекстовый поиск, использующий CONTAINS(), и contains() языка XQuery имеют разную семантику. Последний метод выполняет сравнение подстроки, а первый выполняет сравнение при помощи разграничительных знаков.

Пример: создание полнотекстового индекса на столбце XML

Шаги, требующиеся для создания полнотекстового индекса на столбце XML, не сильно отличаются от тех, которые выполняются для столбцов других типов. В основной базе необходим уникальный ключ на столбце. Ниже показаны команды DDL, в которых PK__docs__7F60ED59 - первичный ключ на одном столбце таблицы:


CREATE FULLTEXT CATALOG ft AS DEFAULT
CREATE FULLTEXT INDEX ON dbo.docs (xCol) KEY INDEX PK__docs__7F60ED59

Пример: совмещение полнотекстового поиска с запросами XML

Следующий запрос проверяет, что значение XML содержит слово "Secure" в названии книги:


SELECT * 
FROM   docs 
WHERE  CONTAINS(xCol,'Secure') 
AND    xCol.exist('/book/title/text()[contains(.,"Secure")]') =1

Метод CONTAINS() использует полнотекстовый индекс для выборки из документа значений XML, которые содержат слово "Secure". Метод exist() проверяет, что слово "Secure" содержится в названии книги.

Выполнение запроса с использованием индексов XML

Индексы XML ускоряют выполнение запросов. Запросы всегда компилируются по первичному индексу столбца XML, если он существует. Один план выполнения создается для всего запроса (и для реляционной части, и для части XML), который оптимизируется при помощи оптимизатора запросов движка базы данных. Вторичные индексы XML выбираются для использования в соответствии с оценками затрат оптимизатора запросов.

Каталожные представления для индексов XML

Каталожные представления используются для просмотра индексов XML с типом индекса 3 (столбец "type"). В столбце "name" содержится название индекса XML.

Индексы XML также находятся в каталожном представлении sys.xml_indexes, в котором содержатся все столбцы из sys.indexes и несколько дополнительных, имеющих отношение к индексам XML. Значение NULL в столбце "secondary_type" указывает на первичный индекс XML; значения 'P', 'R' and 'V' соответствуют вторичным индексам XML PATH, PROPERTY и VALUE.

Использование пространства в индексах XML может быть проверено при помощи табличной функции sys.fn_indexinfo(). Функция возвращает такую информацию, как количество занятых страниц на диске, средний размер строки в байтах, количество записей, и другую информацию для индексов всех типов, включая индексы XML. Эта информация доступна для каждой секции базы данных; индексы XML используют ту же схему секционирования и функцию секционирования базовой таблицы.

Пример: использование пространства в индексах XML


SELECT sum(Pages)
FROM   sys.fn_indexinfo ('docs', 'idx_xCol_Path' , DEFAULT, 'DETAILED')

Эта команда SELECT выводит количество страниц на диске, занятых индексом XML idx_xCol_Path в таблице T по всем секциям. Без функции sum() результат возвратил бы количество занятых страниц на диске по каждой секции.

ПРОДОЛЖЕНИЕ СЛЕДУЕТ

[В начало]

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

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

Coding Standards Part 2 - Formatting
Steve Jones
One of the areas that I feel is very important for managing and maintaining a stable environment is the use of standards. In any SQL Server environment, we deal with any number of objects or areas, but we often work with T-SQL code in our daily work. And as anyone know who has worked with others, having standards greatly improves and simplifies the ability of one person to take over for another and maintain some continuity between the individuals
Metadata management for Enterprise Applications
Silwood Technology Ltd
This paper describes why metadata management is an issue, why it is important to manage ERP metadata, then outlines how Saphir is a key element in any ERP metadata management strategy
Knowledge Management in Heterogeneous DataWarehouse Environments
Larry Kerschberg
This paper addresses issues related to Knowledge Management in the context of heterogeneous data warehouse environments. The traditional notion of data warehouse is evolving into a federated warehouse augmented by a knowledge repository, together with a set of processes and services to support enterprise knowledge creation, refinement, indexing, dissemination and evolution
Breaking Type Barriers with UDTs in SQL Server 2005
Thiru Thangarathinam
Using SQL Server 2005 and the .NET 2.0 framework you can go beyond the standard data types recognized by SQL Server and create your own User Defined Types (UDTs) using any .NET Language—and then use them exactly the same way you use the built-in types
Counting rows in a subtree
Rudy Limeback
There is a table called User (userID PK, userName, supUserID FK). SupUserID refers to userID and contains the userID value of the user's superior. The highest user has no user superior to itself (NULL instead of a value) and can have under itself one or more users or no users at all. Number of levels in such a tree is not defined
Optimizing Microsoft SQL Server Analysis Services: Enhance Cube Processing Performance with Optimize Schema
William E. Pearson, III
In this article, we will explore another tool that MSAS offers for the enhancement of cube processing, the Optimize Schema option. This option can assist us in significantly reducing a cube’s processing time. Optimize Schema attempts to identify unnecessary joins between our fact and dimension tables, and then to remove them. In many cases, the tool works effectively to accomplish this. Elimination of the joins means more rapid resolution of MSAS’ queries to the relational database upon which our cube is dependent as a data source, which means that data is pulled into Analysis Services in less time, contributing to a more rapid cube build overall
SQL Server 2000 - Merge Replication Step by step Procedure
D J Nagendra
Merge replication step by step procedure for SQL Server 2000. Replication is the process of sharing data between databases in different locations. Using replication, we can create copies of the database and share the copy with different users so that they can make changes to their local copy of database and later synchronize the changes to the source database
SQL Server 2005 Express Tips
Kevin Kline
By now, you’ve probably heard something about Microsoft’s new SQL Express. SQL Express is the replacement for Microsoft's MSDE database. It’s a free, light-weight database version of SQL Server. It is SQL Server, but it’s stripped down to make it a smaller download. It’s less filling and tastes great too!
Deleting Duplicate Records
Sureshkumar Ramakrishnan
This article explains a solution which can be used for deleting non-unique duplicate records from a table. In Oracle, every row in a table has a unique identifier so deleting duplicate records can be done as each record is unique based on its rowid (rowid is the mechanism which Oracle uses to physically locate the records in a table). But as SQL Server 7.0/2000 does not have the concept of row identifier it’s difficult to delete duplicate records from a table
Microsoft Releases SQL Server Health and History Tool
Windows IT Pro
The SQL Server Health and History Tool (SQLH2) lets you collect information from instances of SQL Server, store the information, and run reports against the data to determine how your organization is using SQL Server. SQLH2 collects four main types of information: feature usage (what services and features are installed and running and what the service's workload level is), configuration settings (machine, OS, and SQL Server configuration settings and SQL instance and database metadata), the SQL Server service's uptime, and performance counters (an option that lets you determine performance trends). SQLH2 requires you to create a SQL Server repository database. You should also download the SQLH2 reports to view the data SQLH2 collects. If you're interested in performance data, download and install the SQLH2 Performance Collector. The SQLH2 tool, a deployment guide, fixes to the SQLH2 2.0 version, and the Performance Collector are all available for download at
Fascinating Query Tricks
Danny Lesandrini
I love writing VBA code but I am convinced that, many times what I am trying to accomplish can be done in a more efficient, graceful and elegant way using SQL queries. Over the last few months, I have tried to develop my applications with this in mind. The following article is a summary of problems I have been able to solve by using fascinating query tricks. Here is an overview of what we will cover
MSSQL Server 2000 Reporting Services: Black Belt Components: Ad Hoc Conditional Formatting for OLAP Reports
William Pearson
Over the years that I have spent implementing enterprise Business Intelligence applications, I have found many uses, ranging from "simple to sublime," for conditional formatting. At its most basic, conditional formatting can be used to identify exceptional data in a report. Examples (in the world of the sample FoodMart organization) might include Products that sell over or below certain thresholds, or Employees who have been around for a period exceeding a certain number of years
Evaluating Boolean expressions using T-SQL
Eli Leiba
I wrote a procedure that can be used as a checking tools for evaluating Boolean expressions with up to 4 variable (A,B,C,D) logical operators NOT, AND ,OR are used. The evaluate Procedure gets a Boolean expression string with letters A, B, C, D and Boolean Operators AND, OR, NOT, also the number of parameters in equation and the values for each parameter separated by a dot sign
Designing Role-Based Security Models for .NET
Michele Leroux Bustamante
For any application development cycle, one of the first critical steps to take before you code is to envision and document the entire system's component architecture. With this information on hand, it is possible to evaluate security requirements for each facet and workflow through that component architecture. Evaluating security means that a team should model possible threats to the system, but to support this effort developers must have a firm grasp on security features of .NET including code access security (CAS) and role-based security. They must also understand how the runtime security engine interacts with these security features
SQL Server Configuration Performance Checklist
Brad M. McGehee
In this article, we are going to take a look at some of the performance-related SQL Server configuration settings. These are SQL Server-specific settings that can be modified using either Enterprise Manager or SP_CONFIGURE
SELECT DISTINCT: A SQL Case Study
Tom Copeland
There is an understanding in the database world that using a "SELECT DISTINCT" SQL query is not a good idea, because it is essentially getting duplicate rows out of the database and then discarding them. Usually it is better to rearrange the "WHERE" clause in the query to only get the rows you need. One of these cases came up in a 3-way join query in a PostgreSQL database I administer. This article gives a step-by-step "case study" of analyzing a query in PostgreSQL and how to ensure that your SQL rewrite is actually paying off
SQL Server: A Practical Guide to Backup, Recovery, & Troubleshooting
Chris Kempster
The Role of a DBA is undoubtedly and important one, but many DBAs tend to be somewhat blasi about backup and recovery. This E-book attempts to bridge the knowledge gap and provide working scenarios, policy/procedure and best practice for database backup and recovery. The author assumes a reasonable knowledge of DBMS architecture and in particular, some general DBA experience with SQL Server. ** Please note: Due to the size of this document and its presentation on Adobe Acrobat, it may take several minutes to download
Data Recovery Best Practices: Building a responsible backup and recovery system for your databases
Stephen Wynkoop
When people think about Data Recovery, they think largely about backups and the actual act of both backing up the database and associated files and the process of restoring those files to the server. Without a solid plan in place that reviews the best approaches for setting up a plan, testing the plan and executing on that plan, you can quickly get into trouble
Displaying decimal places in SQL Server 2000
Michael Hotek
I am using the money data type in SQL Server 2000. When I display values on my production server (using ASP.NET), it shows two places after decimal, but on the live server it shows four digits after the decimal. What setting is required to get this rectified on my live server? That is because your ASP.NET application is rounding them off. Money values are stored with 4 decimal places and you can find this explicitly documented in Books Online
Extracting significant rules from a classification tree
DMTeam
This tip shows how to use DMX to extract significant rules from a trained model. One of the typical usages of data mining technology is to get insights into patterns in the data. The DM-oriented insights often lead to potential optimization points in existing business practice. Suppose we have a bug tracking system that keeps track of all bugs from its creation to resolution. Often, a significant number of bugs end up with no useful actions. They could be resolved as duplicates of existing ones, by design, external issue and so on. Reducing such bugs that end up with no action but waste resources for investigation would significantly improve the efficiency of the organization. In order to achieve this, we need to first obtain insights into the conditions of such bugs. A classification model can be very effective for this type of data mining task. Suppose we create a classification model as follows
Working with Datetime
Leo Peysakhovich
Date / Time data types are probably amongst the most used data ones. Based on the Microsoft definition, date and time data types are for representing date and time of day. Values with the datetime data type are stored internally by Microsoft SQL Server as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight
Introduction to MSSQL Server 2000 Analysis Services: Performing Incremental Cube Updates - An Introduction
William Pearson
Having processed cubes in preceding articles, we are aware that processing calculates the aggregations that have been designed for the cube, and then loads the cube with the data, and the calculated aggregations of the data. While we have looked only at Full Processing in most of my articles, we will expose other approaches to processing in this session. We will then focus on the use of a tool that MSAS provides to help us to exploit one of those options, the incremental processing of our cubes
Mapping user and login security
Baya Pavliashvili
If you use SQL Server authenticated logins to connect to databases, the following scenario should sound familiar: you backup the database on the production server, restore it on the development/test server and the application doesn't work. What's wrong? You immediately check the users' node in the Enterprise Manager and notice that database users aren't mapped to respective logins. You next look at the list of logins on your development server and it's identical to that on your production server. How is it then that database users aren't mapped to logins?
Use Query Analyzer Templates to Speed Code Creation
Andrew Novick
This article is a little different from most others in the series in that instead of offering a UDF you're going to see an easier way to create UDFs when using SQL Query Analyzer, or Query Analyzer for short
Multiple Paths in Workflow
Darren Green
Branching workflow is a common requirement, and is quite easy to achieve using the basic On Success or On Failure constraints available through the designer. However branches go in different directions and do not meet up again
Getting the Most out of SQL Server 2000's Query Analyzer, Part I
Brian Kelley
The first time I started up Query Analyzer after upgrading my client tools from SQL Server 7 to 2000, I noticed the Object Browser immediately. Playing around a bit, I tinkered with the Transact SQL debugger and generally just explored some of the new functionality. Most of it was quite useful, but not exactly straight-forward. When I began looking into getting more out of some of these new features, I found the documentation on Query Analyzer was intermingled with the rest of Books Online and I thought then how it could easily be overlooked. About a month ago, I was talking with a developer about some issues he was having debugging code, looking at execution plans, and trying to determine the best places to put indexes. I started asking him some questions about how the development team was using Query Analyzer and quickly realized that they saw it basically as an environment to type in their stored procedures and write simple queries. They weren't using any of the main features, and the reason was because they weren't aware of how to use them

[В начало]

ФОРУМ SQL.RU

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

Ваше мнение об упражнениях SELECT на http://sql.ipps.ru
Tool Вы знаете что твориться на ваших 10-30+ серверах ?
Восстановление данных
SQL Server Health and History Tool (SQLH2) Reports
Дикие Тормоза, есть план запроса, кто посмотрит?
Raw partition
Создание клиента на чистой от SQL Server машине
Книга по Reporting Service
База встает в Loading
ODBC
И снова ADSI & LDAP. Помогите...
Как сделать свой счетчик?
Импорт курсов валют
интервал времени между строками
Запрос..................... Оборотно-сальдовая ведомость
проблемма с выполнением процедуры
Откуда дублирование, не понятно?
Элементарный ORDER BY
Выложил базу стран, городов и прочие классификаторы, иконки сюда...
Профессионалы!!!! Помогите

[В начало]

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

SQLMail + Outlook 2003 (не Exchange)
Передача глобальной переменной в DTS пакет
DTS. Text source не находит файл в цикле
Crystal Reports 8.0.0 + SQL
Вопос по DTS.
sp_OASetProperty - присвоить объекту объект

[В начало]

ПОЛЕЗНОСТИ

Лучше вместе! Специальное предложение для покупателей Microsoft SQL Server 2000

Предложение действует с 17 декабря 2004 по 28 февраля 2005 года.

При покупке лицензии на Microsoft SQL Server 2000 Standard вы получите русскую версию Visual Basic .NET 2003 Standard бесплатно.
При покупке лицензии Microsoft SQL Server 2000 Standard на процессор вы получите лицензию на Visual Studio .NET 2003 Professional бесплатно.
При покупке Microsoft SQL Server 2000 Enterprise Edition вы получите лицензию на Visual Studio .NET 2003 Professional бесплатно.
Условия и дополнительная информация:
» Предложение действительно на территории России.
» Предложением могут воспользоваться организации, приобретающие ПО по программе корпоративного лицензирования Microsoft Open License.
» Дата размещения заказа на лицензии должна быть в периоде с 17 декабря 2004 до 28 февраля 2005 года.
» Предложение не распространяется на заказчиков академической лицензии.

[В начало]

#228<<  #229

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

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

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



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


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

В избранное