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

MS SQL Server

  Все выпуски  

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


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

#231<<  #232

СОДЕРЖАНИЕ

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

СТАТЬИ

Разрешение проблем подключения к SQL Server 2000 (окончание)

По материалам статьи Microsoft: How to troubleshoot connectivity issues in SQL Server 2000
Перевод Ирины Наумовой

Тестирование разных способов подключения к экземпляру SQL Server

Если у Вас возникают проблемы при подключении к SQL Server, можно воспользоваться одним из следующих способов, чтобы определить причину возникновения этой проблемы:

  • Попробовать подключиться с использованием разных типов авторизации, с помощью учетных записей Windows и SQL Server.

  • Попробовать подключиться, используя другой источник данных, такой как ODBC DSN, файл .udl. Или используя другую программу: SQL Query Analyzer, SQL Server Enterprise Manager, утилиты isql или osql.

  • Проверить возможность подключения к SQL Server с использованием разных протоколов. Для этого можно создать псевдоним для сервера и определить для него протокол. Также указать протокол можно в строке подключения, дописав перед именем сервера tcp:, np:, lpc:, или rpc:. То есть, если подключение через tcp/ip заканчивается ошибкой, можно попробовать подключиться через именованные каналы.

  • Проверить возможность подключения с использованием различных учетных записей. Это поможет, если проблема связана с подключением с конкретной учетной записью.

  • Попытайтесь добавить соответствие IP адреса и имени узла, на котором работает SQL Server в следующий файл: %systemroot%\system32\drivers\etc\hosts

  • Попытайтесь подключиться к SQL server с компьютера, где он работает, а потом с клиентского компьютера.

  • Когда Вы подключаетесь с компьютера, на котором выполняется SQL Server, вместо полного имени сервера можно использовать "." или "(local)" (без кавычек).

  • Попытайтесь подключиться к SQL server используя не имя сервера, а его IP адрес.

  • Попытайтесь определить вручную имя порта на котором "слушает" SQL Server путем создания псевдонима или в строке подключения (Например MyServer\MyInstance, 1433).

[В начало]

Мониторинг сети

Если проблема подключения не разрешилась с помощью методов, описанных в разделе "Тестирование разных способов подключения к экземпляру SQL Server", используйте утилиту Network Monitor для анализа трассы сетевого обмена.
Для получения дополнительной информации о сетевом мониторинге, прочитайте следующие статьи базы знаний Майкрософт:

148942 How to capture network traffic with Network Monitor (Запись сетевого трафика с помощью сетевого монитора)
294818 Frequently asked questions about Network Monitor (Часто задаваемые вопросы по Network Monitor)
169292 The basics of reading TCP/IP traces (Основы трассировки TCP/IP)
102908 How to troubleshoot TCP/IP connectivity with Windows 2000 or Windows NT (Поиск и разрешение проблем с соединениями TCP/IP в Windows 2000 и Windows NT)

Для получения более детальной информации можно использовать SQL Profiler, а также Network Diagnostics Tool, если компьютер, на котором работает SQL Server, не является одним из узлов кластера. Для получения информации о том, как использовать Network Diagnostics Tool, изучите следующую статью:

321708 HOW TO: Use the Network Diagnostics Tool (Netdiag.exe) in Windows 2000 (Использование Network Diagnostics Tool (Netdiag.exe) в Windows 2000)

[В начало]

Ссылки

Для изучения проблем связанных с подключением к SQL Server, предлагаются следующие статьи из Базы Знаний Майкрософт:

812817 Support WebCast: Microsoft SQL Server 2000: Troubleshooting connectivity
319930 HOW TO: Connect to Microsoft Desktop Engine (Установка подключения к Microsoft Desktop Engine)
257434 INF: Network library in existing DSN replaced by network library in new DSN to the same SQL Server name
306985 RPC errors when connecting a cluster virtual server with named pipes
313062 HOW TO: Connect to a database by using Active Server Pages in Windows 2000
313295 HOW TO: Use the server name parameter in a connection string to specify the client network library
320728 HOW TO: Resolve "The maximum connection limit has been reached" error message
328306 INF: Potential causes of the "SQL Server does not exist or access denied" error message (Возможные причины появления сообщения об ошибке "SQL-сервер не существует, или отсутствует доступ")
247931 INF: Authentication methods for connections to SQL Server in Active Server Pages
169377 How to access SQL Server in Active Server Pages
328383 INF: SQL Server clients may change protocols when they try to connect
238949 HOWTO: Set the SQL Server network library in an ADO connection string
270126 PRB: How to manage client connectivity to both SQL Server 2000 virtual servers after an active/active cluster 7.0 upgrade
316779 PRB: Clients with Force Protocol Encryption set on may fail to connect with an IP address
216643 INF: ODBC/OLEDB connect options not seen when tracing connections to SQL Server 7.0
265808 INF: How to connect to an SQL Server 2000 named instance with the previous version's client tools
191572 INFO: Connection pool management by ADO objects called from ASP
313173 Sample connection pool manager for use with Microsoft SQL Server 2000 driver for JDBC
237844 HOWTO: Enable ODBC connection pooling in a Visual Basic ADO application
259569 PRB: Installing third-party product breaks Windows 2000 MDAC registry settings

Информация в статье применима к Microsoft SQL Server 2000 Standard Edition.

[В начало]

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

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

Поддержка XML в SQL Server CLR

Используя поддержку SQL Server CLR, вы можете писать логику на серверной стороне в управляемом коде для поддержки бизнес-правил. Бизнес-логика может быть добавлена в данные XML следующими способами:

Вы можете писать функции SQLCLR в управляемом коде, в который вы передаете значения XML, и использовать возможности обработки XML, предоставленные пространством имен System.Xml. Ниже показан пример трансформации XSL в данные XML. Вы также можете разложить XML на один или больше управляемых классов и оперировать ими, используя управляемый код. Вы можете написать хранимые процедуры и функции T-SQL, которые вызывают обработку столбца XML.

Пример: применение трансформации XSL

Рассмотрим функцию CLR TransformXml(), которая принимает в качестве аргумента экземпляр XML и трансформацию XSL, применяет трансформацию к данным XML, и возвращает измененный XML. Схематично функция, написанная на C#, выглядит следующим образом:


public static SqlXml TransformXml (SqlXml XmlData, string xslPath) {
   // Load XSL transformation
   XslTransform xform = new XslTransform();
   XPathDocument xslDoc = new XPathDocument (xslPath);
   xform.Load (xslDoc.CreateNavigator(),null);

   // Load XML data
   XPathDocument xDoc = new XPathDocument (XmlData.CreateReader());
   XPathNavigator nav = xDoc.CreateNavigator ();

   // Return the transformed value
   SqlXml retSqlXml = new SqlXml (xform.Transform(nav, null));
   return (retSqlXml);
}

Когда сборка зарегистрирована и создана пользовательская функция T-SQL SqlXslTransform(), соответствующая функции CLR TransformXml(), то эта функция может быть вызвана из T-SQL следующим запросом:


SELECT SqlXslTransform (xCol, 'C:\yukon\xsltransform.xsl')
FROM    T
WHERE  xCol.exist('/book/title/text()[contains(.,"custom")]') =1

Результат запроса содержит набор записей трансформированного XML.

SQLCLR открывает новые возможности по разложению данных XML в таблицы и запрашиванию данных XML, используя управляемые классы в пространстве имен System.Xml. Дополнительную информацию вы сможете найти в системах справки SQL Server 2005 и Visual Studio® 2005.

Обработка XML на стороне клиента в SQL Server 2005

Поддержка XML на стороне клиента

Поддержка ADO.NET XML в .NET Framework V2.0

Тип XML рассматривается как класс SqlXml в пространстве имен System.Data.SqlTypes метода SqlDataReader.GetSqlXml(). Вы можете получить XmlReader из объекта SqlXml, используя функцию SqlXml.CreateReader().

Имя коллекции схем XML, состоящее из трех частей, которая типизирует столбец XML, можно получить из метаданных столбца XML (используя GetSchemaTable() или GetSqlMetaData (int) объекта SqlDataReader) в виде трех свойств, содержащих имя базы данных (XmlSchemaCollectionDatabase), реляционную схему (XmlSchemaCollectionOwingSchema) и коллекцию схем XML (XmlSchemaCollectionName).

Новый набор данных схемы XMLSCHEMA доступен пользователям для получения схем XML с сервера. Набор данных XMLSCHEMA содержит три столбца для коллекции схем XML, пространства имен, и самого содержимого схемы XML.

Следующие примеры показывают код для управляемого доступа к данным XML.

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

Код на C#, показанный ниже, демонстрирует, как можно получить доступ к данным XML из встроенного провайдера. Код для доступа клиента SQL требует встроенного доступа.


using System;
using System.Xml;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlServer;

class xmldtADONETReadAccessInProc
{
   static void ReadXmlDataType () {
      // Встроенное соединение с сервером
      SqlConnection conn = SqlContext.GetConnection();

      // Подготовка запроса для выборки данных XML
      SqlCommand cmd = conn.CreateCommand();
      cmd.CommandText = "SELECT xCol FROM docs";

      // Выполнение запроса и получение данных
      SqlDataReader r = cmd.ExecuteReader();
      r.Read();

      // Доступ к столбцу с данными XML в наборе данных
      SqlXml xml = r.GetSqlXml(0);
      new XmlTextWriter(Console.Out).WriteNode( 
xml.CreateReader(), true);
   }
}

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

Код ниже демонстрирует метод WriteXmlDataType(), который изменяет значение столбца XML, используя клиентский провайдер SQL. Код для встроенного провайдера такой же.


using System;
using System.Xml;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;

class xmldtADONETUpdateAccess
{
   static void WriteXmlDataType () {
      // Соединение с сервером
      SqlConnection conn = new SqlConnection("server=server1;" +
" database=XMLtest; Integrated Security=SSPI");
      conn.Open();

   // Обновление столбца XML на сервере
   SqlCommand cmd = conn.CreateCommand();
   cmd.CommandText = "UPDATE docs SET xCol=@x WHERE id=1";

// Установка значения параметра XML
   SqlParameter p = cmd.Parameters.Add("@x", SqlDbType.Xml);
p.Value = new SqlXml(new XmlTextReader("<hello/>", 
XmlNodeType.Document, null));

// Выполнение обновления и закрытие соединения
   cmd.ExecuteNonQuery();
conn.Close();
}
}

Встроенный клиентский доступ к SQL

В провайдере OLE DB нового встроенного доступа к SQL (SQLNCLI) столбец XML может быть получен как в виде строки Unicode (DBTYPE_XML, DBTYPE_BSTR, DBTYPE_WSTR и DBTYPE_VARIANT), так и в виде потока символов Unicode, используя ISequentialStream. По умолчанию используется DBTYPE_XML.

Имя коллекции схем XML, состоящее из трех частей, передается тремя новыми столбцами в наборе данных схемы COLUMNS, возвращаемом IDBSchemaRowset::GetRowset(): столбцом SS_XML_CATALOGNAME, передающим название каталога; столбцом SS_XML_SCHEMANAME, передающим имя реляционной схемы, в которой размещается коллекция схем XML, и столбцом SS_XML_SCHEMACOLLECTIONNAME, передающим имя коллекции схем XML. Эти имена принадлежат типу DBTYPE_WSTR. Столбцы имеют значение NULL для нетипизированного столбца XML.

Такие же изменения были сделаны в наборе данных схемы PROCEDURE_PARAMETERS и в IColumnRowset:GetColumnRowset().

Чтобы получить содержимое коллекции схем XML, клиент может создать отдельный доступ к серверу, используя эти имена в вызове XML_SCHEMA_NAMESPACE(), и получить схемы XML в виде данных XML. Также IDBSchemaRowset с новым набором данных схемы SS_XMLSCHEMA возвращает имя каталога, имя реляционной схемы, имя коллекции схем XML, пространство имен и схему XML.

Для доступа ODBC с помощью SQLNCLI, данные XML конвертируются в символьные данные Unicode, называемые SQL_SS_XML. Имя коллекции схем XML, состоящее из трех частей, передается через SqlColAttribute для столбца XML CharacterAttributePtr. Идентификаторы полей следующие: SQL_DESC_SS_XML_SCHEMA_CATALOG_NAME, SQL_DESC_SS_XML_SCHEMA_SCHEMA_NAME и SQL_DESC_SS_XML_SCHEMA_COLLECTION_NAME для имен базы данных, реляционной схемы и коллекции схем XML, соответственно.

Пользователи должны устанавливать сервер базы данных или клиентские инструменты SQL Server 2005, чтобы получить встроенный клиентский доступ к SQL. Доступ OLE DB к данным XML, с использованием MDAC 2.8 ADO, невозможен.

Конвертация SQLXML между XML и реляционными схемами

Вы можете создать логические представления XML Ваших реляционных данных, используя технологию конвертации SQLXML. Представление XML, также называемое к "конвертацей" или к "аннотируемой схемой", создается с помощью добавления специальных аннотаций к существующей схеме XSD. После этого другие технологии SQLXML могут использовать эту аннотируемую схему для трансформации запросов и обновлений логического представления XML в запросы и обновления реляционных таблиц:

Когда представление XML комбинируется с запросом XPath, SQLXML сгенерирует запрос FOR XML, чтобы найти запрошенные данные и оформить их, как определено в схеме. Апдейтаграммы SQLXML отражают изменения в экземпляре XML, который, будучи совмещенным с аннотируемой схемой, вносит эти изменения в реляционную структуру с оптимистической блокировкой, чтобы удостовериться, что обновились нужные данные. SQLXML Bulkload использует представление XML, чтобы "разрезать" данные XML на реляционные таблицы. Для дополнительной информации обратитесь к документации по SQLXML.

Создание представления XML реляционных таблиц

Чтобы создать представление XML базы данных, начните со схемы XSD для ваших данных XML. Строки таблицы/представления базы данных будут конвертироваться в элементы сложного типа в схеме. Значения столбцов в базе данных конвертируются в атрибуты или элементы простого типа.

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

Если имя элемента/атрибута не такое, как имя таблицы/представления или имя столбца, с которым он конвертируется, то должна быть создана явная конвертация. Следующие аннотации используются для определения конвертации между элементом или атрибутом в документе XML и таблицей (представлением) или столбцом в базе данных:

* sql:relation - конвертирует элемент XML в таблицу базы данных.
* sql:field - конвертирует элемент или атрибут в столбец базы данных.

Конвертация отношений для создания иерархий в представлениях XML

В Вашей базе данных таблицы могут быть связаны внешними ключами. В XML эти же отношения отражаются в виде иерархии элементов. Чтобы создать правильную иерархию в Вашей конвертации, Вы должны определить, как элементы связаны между собой. Вы можете установить эти связи между элементами схемы конвертации, используя аннотацию sql:relationship. В этой аннотации Вы можете определить родительские и дочерние таблицы, как и столбцы в каждой из них, которые должны использоваться для выполнения объединения. Тогда SQLXML будет использовать эту информацию для создания правильной иерархии для вашей конвертации.

Использование столбца overflow для хранения нераспределенных данных

Конвертация работает, когда Ваши данные XML имеют постоянную структуру. Однако, могут быть некоторые данные в Вашем XML, которые или не структурированы, или не конвертируются в специальный столбец. Для хранения этих данных и дальнейшего их получения может использоваться аннотация sql:overflow. Аннотация sql:overflow определяет столбец, в котором хранится вся нераспределенная информация, и из которого ее можно получить запросами.

Столбец overflow также подходит для расширения XML без необходимости добавления нового столбца в Вашу базу данных. Элементы и атрибуты могут быть добавлены к Ввашей структуре XML в любое время без добавления столбцов для их хранения в базе данных. Они просто будут храниться в поле overflow, и могут быть получены в нужное время.

Дополнительная информация

Для дополнительной информации по созданию представлений XML и примеров конвертации смотрите "Создание представлений XML с помощью аннотируемых схем XSD".

ОКОНЧАНИЕ СЛЕДУЕТ

[В начало]

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

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

XQuery и SQL - в чем разница
Ken North
XML: Невозможно обсуждать будущее программной индустрии без обсуждения XML. XML стал настолько важен, что SQL уже не является шаблонным ответом на вопрос "Какой язык запросов поддерживается всеми основными компаниями - производителями СУБД?" Новое дитя в семействе языков - XQuery, язык запросов для поиска документов с тегами XML в файлах и базах данных...
Сбор и публикация проектных метрик в процессе разработки Программного Обеспечения
Новичков Александр, Лапыгин Дмитрий
CASE: Данная статья описывает методы формирования отчетной информации с процессе разработки программного обеспечения. Статья дает практические навыки и рассказывает о том как сформировать отчетную систему на базе штатных средств IBM Rational ClearCase...
Генераторы отчетов в SQL Server 2000: создание отчета с нуля
Mysorian
MSSQLServer: В данном руководстве мы опишем создание отчета с нуля, используя те же самые средства разра-ботки. В качестве данных для создания отчета будет использоваться база данных Biblio из MSDE [XPHTEKTEST]. MSDE, который также называют Desktop SQL Server, представляет собой упрощенную версию SQL 2000 Server и в ней отсутствуют некоторые функции, присущие полным версиям (Profes-sional или Enterprise). В генераторе отчетов мы создадим и сконфигурируем объект DataSet, который будет источником данных для нашего отчета. Макет отчета по внешнему виду напоминает подобные макеты в Access или Crystal Reports. Далее приводится пошаговое иллюстрированное описание построения отчета с нуля...
C#: DataGrid + Checkbox(Delete/Insert)
Топоровский Александр
C-sharp: Написать эту статью меня побудило старательное игнорирование описание процедуры использования checkbox-ов в DataGrid в литературе (по крайней мере доступной мне), так и на форумах (в том числе англоязычных). Достаточно много задавалось вопросов, но вот ответы были разрозненными и не были в полной мере ясными для понимания и усвоения. Когда я сам несколько дней взялся за решение данной задачи (т. е. использование checkbox-ов в DataGrid ), в полной мере ощутил непроработанность данной проблематик...

[В начало]

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

View Security as the Basis for Data Warehouse Security
Arnon Rosenthal and Edward Sciore
A key challenge for data warehouse security is how to manage the entire system coherently - from sources and their export tables, to warehouse stored tables (conventional and cubes) and views defined over the warehouse. Permissions on the warehouse must satisfy the restrictions of the data owners, and be updated quickly as those local concerns evolve. Yet the system cannot demand extensive administrator time, since there are too few people with both technical skills to understand derivation logic, and business skills to balance security versus accessibility
Script kiddies learn grown-up hacking techniques
ZDNet UK
Hackers with relatively few skills are using online guides to learn how to launch SQL injection hacking attacks
Making Headlines with RSS
Jonathan Eisenzopf
In the early years of the Web, most sites were not concerned about sharing data with other sites. Today, the trend is that sites are increasingly interdependent and many rely upon integrating content that originates somewhere else. Such content might include news feeds, events listings, a set of project updates, and even interchange of corporate information. Effective integration usually requires a good deal of effort on the part of the information provider, as well as the recipient of each unique data source
Version 2005. Easy Package Configuration
Jamie Thomson
One of the age old problems in DTS is moving packages between your development, test and production environments. Typically a series of manual edits needs to be done to all the packages to make sure that all the connection objects are pointing to the correct physical servers. This is time consuming and gives rise to the possibility of human error, particularly if the solution incorporates many DTS packages. Many companies have provided their own custom solutions for managing this problem but these are still workarounds for a problem that is inherently DTS's
Data Access and Transaction Handling Framework
Deyan Petrov
Generic data access component for different datasources, sprocs/sql, implicitly propagated transactions, explicitly managed transaction contexts etc. This is another go at the problem for data access and transaction handling in a multi-tier business application (for example web application). The suggested approach should help for building a database independent data layer. The database can be changed later by simply translating the xml config files to the required database dialect. Both SQL and Stored procedure commands can be used and easily switched between, without changing the data layer code. The transactions are managed implicitely, but the code explicitely deals with transaction contexts. Several TransactionHandlers supplied
What is the difference between density and selectivity in column statistics?
Randy Dyess
Often when you are reviewing information on column statistics, two terms keep popping up: Density and Selectivity. Many developers and DBAs do not properly understand the differences in these two key elements of column statistics. Below is a very basic introduction to the terms Selectivity and Density and how each one may help you determine which column will make a good candidate for an index
Eliminating Recompilation
Umachandar Jayachandran
Congratulations to Narasimhan Jayachandran, a senior DBA for First Data Resources in Omaha, Nebraska and Chris Watson, a senior developer for the Auckland University of Technology in Auckland, New Zealand. Narasimhan won first prize of $100 for the best solution to the January Reader Challenge, "Eliminating Recompilation." Chris won second prize of $50. Here’s a recap of the problem and the solution to the January Reader Challenge
Setting up a reboot cycle for Active/Passive Cluster SQL Server
Muthusamy Anantha Kumar
Every organization has a system of weekly reboots or monthly reboots etc., for all their servers. When it comes to clustered servers, the reboot cycle would be little different. Usually the active node in the cluster will always be active, unless there is a failover initiated manually or when there is a hardware failure etc
Loading Aggregate Data in Yukon 2005
Richard Tkachuk
In some cases, the source data is pre-aggregated in one, some or all dimensions. In the simplest example, employee salary is loaded to all employees. Because a manager’s salary is not the aggregate of his reports, it should not be aggregated up the employee dimension. There are several other such examples. This document discusses how pre-aggregated data can be loaded directly into Analysis Services 2005
Using Linear Regression MDX functions for forecasting
Mosha Pasumansky
MDX provides several functions for computing linear regression, however those functions are anything but intuitive or easy to use. This is definitely an area in MDX, that given a chance I would've done differently now. The problem is that when we designed those functions, we unnecessarily generalized them so it would be possible to use them on any dimension with any expression for both "x" and "y" coordinates, but in the process of generalization, we made the most natural use cases - forecasting by Time too difficult and unnatural. Microsoft even published KB article 307276 which explains how to use MDX Linear Regressions family of functions. Unfortunately, while syntactically and mathematically the examples in this KB article are correct, they don't make sense from the business problem point of view, because instead of time, they use "Units Sales" as an "x" coordinate. So let's try to understand how those functions work and what they expect as parameters. I will be focusing on the LinRegPoint function, since it is one of the more useful functions, but same principals apply to others as well. Let's start with what Books Online tell us about it. I slightly modified the content of BOL, because it makes reference to other LinRegxxx functions
Dynamic Dimension Security in Analysis Services 2000
Mosha Pasumansky
Subject of security in Analysis Services is close to my heart (besides my regular responsibilities, I am also responsible for the overall security in Analysis Services). According to the OLAP Report, Analysis Services has most advanced security features among all OLAP servers, security can be controlled on cube, dimension and cell levels, contingently and noncontingently, with or without visual totals etc. But what is even more interesting - all security definitions are done through MDX. This opens a whole big area of possibilities. For example, security definitions can be data driven, i.e. come from the member properties or even they can come from the external data sources by embedding calls to UDFs inside MDX security definitions. Another interesting scenario is to have single role behave differently for different users, by using the Username MDX function inside the security definitions. This is what we call "dynamic security". The clear advantage of this method is that instead of creating multiple roles, the single one can be maintained, which automatically adjusts as users are added, removed or their access rules change. When we released OLAP Services 7.0 SP1, I have written a whitepaper which explained how to get both data driven and dynamic security for the cell security definitions. Later, Russ Whitney wrote two articles for SQL Server Magazine(1,2), where he explored similar ideas but applied to dimension security. Russ's articles are often cited and referred to whenever there is a need to implement data driven or dynamic dimension security. However, while those articles are technically accurate on how to configure dynamic security, they have somewhat misleading and up to incorrect statements when it comes to the number of roles that can be handled by Analysis Services. Dave Wickert has done deep and thorough investigation of the subject, and gave several presentations about it. He now offered to share his presentation slides, speaker notes, sample project, demo notes, setup instructions etc on mosha.com. I am very grateful to Dave for that, and I am sure everybody who needs to implement dimension security is going to benefit greatly from his work
ADOMD.NET source code for querying KPIs in Ananlysis Services 2005 in ASP.NET
Mosha Pasumansky
One of the more publicized features of Analysis Services 2005 is the intrinsic support for the KPIs (for more information on Analysis Services 2005 check out http://www.mosha.com/msolap/yukon.htm). KPIs are defined by cube designer and any client application can programmatically get the rich metadata about them (i.e. Goals, Trends, Graphics etc) and query them. Support for programmability of KPIs is built-in into all layers of Analysis Services APIs - schema rowset in XML for Analysis, OLEDB for OLAP, MDX functions, objects in ADOMD.NET object model etc. In September Olivier Pieri visited our team in Redmond for two weeks in a SWAP project, and implemented KPIViewer - an ASP.NET application for querying and displaying KPIs. Now he was kind enough to publish the essentional ADOMD.NET code for it in his blog. Another interesting thing about that source code is that it makes use of parametric queries in ADOMD.NET. Parametric queries are something that application developers have asked for and now Analysis Services 2005 supports them. One additional comment about Olivier's code - when he wrote it, the MDX functions KPIValue, KPIGoal, KPITrend etc didn't accept KPI name as a string, and a result he was forced to use StrToMember functions in the MDX query generation. In the more recent Yukon builds it changed, so the code now will be simplified - i.e. the following snippet
Analysis Services 2000 Internals
Mosha Pasumansky
There is a lot of resources about Microsoft Analysis Services. There are literaly hundrends of Web pages available (see http://www.mosha.com/msolap), there are dozens of books written (http://www.mosha.com/msolap/books.htm) etc. They cover all the possible subjects about Analysis Services but one - how does the engine works internally. Such information is very scarce and difficult to find. We, as a product team, occasionally give presentations about Analysis Services internals, but the content of those presentations isn't usually publicaly available. So I was surprised to discover several presentations from TechEd 2002 on www.only4gurus.com, and one of them is called “Analysis Services: Server Internals”. This presentation was originally prepared by my old-time friend and colleague - Sasha (Alexander) Berger together with Richard Tkachuk, and later used by Tom Conlon. To understand the context of the presentation, let's take a look at one of the first slides - supersimplified architecture of Analysis Services engine
Typed member properties and MDX .Properties function
Mosha Pasumansky
After my previous post I got some questions about whether it will be possible to use .Properties MDX function in AS2005 in order to get true data type of the property and not the string. While it is easy to give a simple answer to this question (yes, it is possible, see details below), this question raises many other questions and interesting discussions, and I hope that one day I will cover this subject in depth. For now, I will just give a quick preview of what are the issues
Converting Strings to Numbers in MDX or StrToValue vs. Val
Mosha Pasumansky
In Analysis Services 2000 there often a need to convert string to number. Usually it happens when there is a level which has member property, and the values for that member property represent some number. For example, in the FoodMart 2000 sample database, the [Store Name] level of the [Store] hierarchy has member property called [Store Sqft] which represents size of the store in square feet. However, the only way in Analysis Services 2000's to access those values from MDX is by using .Properties function, which always returns a string regardless of the data type of the member property. It is worth to note, that internally, Analysis Services doesn't store member properties as strings, it really preserves the true data type, but unfortunately this data type is not exposed in MDX. So the user now needs to convert back this string to the number in order to perform some calculations using it. Normally one looks at MDX function list, and quickly spots the StrToValue function, which accepts string and returns number - so from the first look it seems like the perfect choice, so user writes something like
Comparing Levels in MDX and CONDITION vs. SCOPE in cell calculations
Mosha Pasumansky
A follow up to the “Comparing Members in MDX” blog (archived here). I just run across a thread on OLAP forum hosted at sql.ru, where someone makes a suggestion to exclude level from calculation by applying this formula
Comparing members in MDX
Mosha Pasumansky
Often I run across MDX expressions which require to apply different formulas based on whether or not current member is some hierarchy is equal to some particular member. For example, we may need to check whether current time member is the very first month, or whether current account is Flow. While the best way to approach those problems is try to split calculation into several calculations, each one with its own scope, it is not always possible, and the checks for member equivalence are done as part of the MDX expression itself, usually inside condition of IIF function. So let's see what is the best way to perform such comparisons both from correctness and performance point of view. I will use the example of check for current account being Flow. So we need to compare two members: On one hand we have MDX expression for the current account - [Account].CurrentMember, and on another hand we have unique name of the Flow account - [Account].&[Flow]. It is not uncommon to see people trying to write something like following
Optimizing Microsoft SQL Server Analysis Services: MDX Optimization Techniques: Optimizing the CROSSJOIN() Function
William E. Pearson, III
In this article, we will return to our intermittent examination of various MDX optimization techniques which we have intermingled with other MSAS optimization topics within this series. The function upon which we will focus will be CROSSJOIN(), whose mission it is to combine two sets of dimension members into one. We will discuss how CROSSJOIN() works in general, and then discuss how performance can become an issue in medium- to large-sized data sets. We will then undertake a multiple-step practice example to gain an understanding of the issues, before examining approaches to minimizing the performance overhead that we can encounter in using CROSSJOIN() to reach our reporting and analysis needs
SQL Server Jobs Can Negatively Affect Performance, If You Are Not Careful
Brad M. McGehee
Virtually every SQL Server runs one or more daily jobs. And most likely, runs many weekly jobs. Unfortunately, most DBAs set up jobs, and then forget about them, unless of course they break. But if they run day after day without any problems, most jobs are forgotten about
Finding size of Table/Indexes in SQL Server 2005
Vinod Kumar
This is an question that came up in the newsgroups to how fo we find the size of tables and indexes in the new version of SQL Server 2005. The solution to the same was using some of the DMVs (Dynamic Management Views) that have statistical information of objects. And for this case we use CTE's too that got introduced in SQL Server 2005
Database Security (Common-sense Principles)
Blake Wiedman
Lately, database security issues have been flooding the media and Internet news-wires. First with the Slammer worm and most recently criminals accessing over 8 million credit card numbers
The ACID Model
Mike Chapple
The ACID model is one of the oldest and most important concepts of database theory. It sets forward four goals that every database management system must strive to achieve: atomicity, consistency, isolation and durability. No database that fails to meet any of these four goals can be considered reliable
Detecting and Reporting Errors in Stored Procedures - Part 1: SQL Server 2000
Rob Garrison
Detailed error reporting from stored procedures can be extremely valuable when debugging problems in your application. I will share different levels of detail that you can build into your stored procedures. You can choose the level of detail appropriate for your situation
Understand the Flow of Execution Plans
Randy Dyess
In order to make use of execution plans in our work, we need to understand the flow of the execution plan. Whether the execution plan is actual/estimated or graphical/text-based, learning to read execution plans can be a little daunting for some developers when they first start to use execution plans to optimize their code. This is because execution plans are presented and flow in reverse of how Americans read. Americans read from top left to bottom right, while execution plans are presented from the right to the left and from the bottom to the top for each code segment. Remember, a large complex query will usually be broken down into multiple code segments by the optimizer which will then produce an execution plan for each code segment
MSDE: Get More Than You Pay For
Brian Moran
"You get what you pay for" is a common saying. It's often true, but sometimes you can get a free lunch, and that's a good way to think about the value Microsoft SQL Server 2000 Desktop Engine (MSDE) offers. I'm surprised more customers don't consider MSDE a viable option for their production-database needs. Yes, I did use production database and MSDE in the same sentence, and no, I haven't had too much New Year's egg nog
SQL Server 2005 Part 5 - High Availability and Scalability Enhancements
Marcin Policht
In this article, we continue our discussion on high availability and scalability enhancements in SQL Server 2005 Beta 2 release. Features such as clustering, database mirroring, online indexing, fast recovery, database snapshots, and snapshot isolation transaction level have already been covered earlier in this series - now we will concentrate on the remaining features, such as a new method of table and index partitioning, backup and restore improvements, and new hardware support options
Enforcing Referential integrity in Microsoft SQL Server 2000
Nick Duckstein
If one were to take a poll regarding the most common issues raised by the clients of marriage counselors, my guess is that sex and money would show up pretty close to the top, if not 1-2. This data would not make headlines in even the smallest periodical because this has been true for a long time. It is also pretty basic. But just because it is simple and has been this way for a long time, does not mean it is no longer true
Load/Unload images into/from DB table
Maxim Alekseikin
Explains how to load a BLOB data into a DB table and how to get it from a DB table
Generating INSERT statements in SQL Server
Sumit Amar
Stored procedure to generate INSERT..VALUES statements in SQL Server
TOP query with multiple columns
Rudy Limeback
Here is the table I am using. I want query for this. I tried with many queries but in vain
Analysis Services 2005, the Year of BI
Robert Pearl
High atop a New York City office building, several people from diverse backgrounds gathered around a large table in a boardroom like setting for intense discussion. No, it wasn’t another episode of the Apprentice! Instead, folks with titles ranging from CTO, President, Programmer, Manager, Developer and Consultant all converged on the scene for an in-depth first look at SQL Server 2005 Analysis Services
Part 2: AWE, MemToLeave, and Memory; Oh What a Tangled Web We Weave
Larry Chesnut
Picking up from where we left off yesterday, I was asked if this simple restatement was accurate: … in plain English then, this means that data pages (from tables) are the main users of the upper memory, or what we have normally been referring to as AWE memory. The CLR, procedure cache and others are not likely candidates for using this upper memory and in some cases won't ever map to this memory space.
AWE, MemToLeave, and Memory; Oh What a Tangled Web We Weave
Larry Chesnut
Merry Christmas everyone. Its been refreshing to get away from computers for a little while and get reacquainted with my family, but now its back to the ol’ grind stone
Part 3: AWE, MemToLeave, and Memory; Oh What a Tangled Web We Weave
Larry Chesnut
So, with all this good info, what are some of the expected or otherwise typical measurements or proportions we are likely to see from SQL Server 2005? For instance, say a machine with 1 GB RAM, SQL Server starts up and is not executing anything even agent/FTS has been shut down. Since I am using Windows XP, what are the ballpark figures of % memory for each of these areas? Would the following values be in the right ballpark?
Part 4: AWE, MemToLeave, and Memory; Oh What a Tangled Web We Weave
Larry Chesnut
Some might say that although these new DMV’s are nice, just how does one go about breaking up the usage of memory starting from the Performance Monitor (Perf Mon\System Monitor) or Task Manager?
Showplan for non SA or DBO users
Larry Chesnut
I imagine if you are reading this you are just geekie enough to have also spent loads of time with execution plans over the years. We have all come to a comfortable routine using this simple expression to get the ball rolling
How do you change 'max degree of parallelism'?
Larry Chesnut
The other day I had someone tell me they tried running the sp_configure command below on one of their Yukon servers and got the results shown below. The weird thing was they had just ran the same command on a different server that has the same version of Yukon and it worked fine. So they asked me how they could get max degree of parallelism to show up in their sp_configure?
Yukon. Simple Recovery Model, Transaction Logs and SSIS data transfer
Larry Chesnut
Recently, I heard of someone who tried migrating a database using SSIS. Along the way, they encountered something that reminded me an old lesson. When they started out, they had three packages executing with data transfers for 7 tables in the process. Each table had between ~100m – 200m rows, thus there were around 1.1 billion rows that show processed. The row counts displayed equaled the number of rows from the source tables. So at first they thought all went fine, but then they saw the following error in the SQL Error Log
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
@SERVERNAME and SQL Server Instances
Todd Carrico
I recently had an issue automating the creation of SQL Agent Jobs. I need to set the Log File properties of the job steps, and was setting the path to a local share on the SQL Server. No problem you say
TSQL Exception Handling and Deadlocks
Cihangir Biyikoglu
You probably hear about exception handling in TSQL already but here is a neat use of the feature: TSQL exception handling is very close to the top when it comes to popularity of the new TSQL features. The ability to handle exceptions without having to put an IF @@ERROR!=0 is extremely valuable for ease of coding. There is one pattern, however, that I really found extremely helpful with the new TRY … CATCH: the ability to handle deadlocks and implement a retry logic on the server side. Quick sample code with a standard disclaimer. This is not intended to demonstrate any best practices but is purely to demonstrate the ability of the exception handling in TSQL
Java proxy for MS SQL Server Reporting Services
Christian Donner and Ilia Papas
Explore the URL interface of a new contender on the enterprise reporting tool market. Generating high-quality print output from a Web application is often difficult because browsers provide only limited control over a document's layout. Adjusting page margins or positioning document elements at a precise location on the page proves impossible when printing from the browser. When preprinted forms are being used or when page flow must be controlled tightly, you must use a server-based document generation engine. Many such technologies and products are available. A solution should provide good report development productivity, a GUI report designer, be highly scalable, perform well (especially when rendering PDF documents for concurrent sessions), and come with an attractive price tag. We tested and benchmarked several products and settled for Microsoft SQL Server Reporting Services (RS). RS can easily be integrated and deployed in a Microsoft-centric environment, but making it accessible to a Java Web application requires some work. This article provides some guidance in integrating RS with your Java Web application. (2,100 words; January 10, 2005)
Use SET NOCOUNT ON for better trigger performance
Serdar Yegulalp
Triggers make it easy to automatically synchronize the behavior of data between tables and across databases. But their performance can be drastically affected by things that might not be obvious at first glance. Here I'll identify one command to reduce the impact of some unforeseen problems
Creating a trigger to update reservations table
Greg Robidoux and Jeremy Kadlec
I am having a problem with a trigger to automatically update a table. I have a table, reservations: customerid, checkindate, checkoutdate, servicecharge, totalcharge. And I have a table called transactions: transactionid, customerid, mservicecharge, and servicedescription. Now I want a trigger like
Retrieving newly-inserted primary keys in SQL Server 2000
Serdar Yegulalp
When a row is inserted into a table that has a primary key column, whether by a stored procedure or a passed command, there may be circumstances where the user or programmer needs to know the newly-generated primary key right away. This is typically the case where the primary key is used to perform JOINs to other tables, and the rows in those other tables need to be inserted or updated immediately
Frequently used SP wiped out the database
Tony Bain
We have a stored procedure that we run on our MS Transact databases. The stored procedure simply allows us to run dbcc on all the tables at one time, giving an output that lists each table and the percentage of fragmentation. One of our customers called in yesterday complaining of slow response from the SQL Server. We ran exec sp_showtablefragmentation (our stored procedure) and the results showed one line, "dbcc execution completed..etc..contact your system administrator" When we attempted to access our core tables we realized all our information was gone. Table by table we searched, but the database was gone. The system indexes were still intact. We were able to restore from backup but am very concerned as we use this stored procedure often and have never had this occur
Creating a User Defined Aggregate with SQL Server 2005
Andrew Novick
SQL Server doesn't have a Product aggregate function. A recent blog post by Karen Watterson pointed out that Microsoft Knowledge Base article Q89656: Simulating a PRODUCT() Aggregate Function discusses how to achieve the Product aggregate functionality using the POWER function. We e-mailed about it and she challenged me to create a Product aggregate in SQL Server 2005. I decided to accept the challenge
SQLCMD will be getting treated more like OSQL
Larry Chesnut
Have you ever wanted to use the SQLCMD command without having to install YUKON just as we can use OSQL or ISQL by downloading a couple of dlls? Is this even possible? If it is, how do we go about it? Most of us can envision using SQLCMD in more than a thousand different ways, and in many of those occasions, maybe you don’t want to install SQL Server 2005
Playing with 64-bit, the Beginning
Larry Chesnut
Well, here we are again with yet another CTP release of Yukon. This time, December’s CTP has a little more excitement for me because build 981 also is out in a 64-bit flavor that has some new features turned on that were not there in earlier releases (Analysis Services and SQL Server Integration Services [formerly Data Transformation Services]). For me, this is a watershed moment since this is the first time I have had a 64-bit box to play on
Part II: Playing with 64-bit, the Beginning
Larry Chesnut
After I finished celebrating around the office that I finally had my RC1 of 64-bit SP1, I then tried to install Yukon’s December CTP. Well, needless to say the celebrating abruptly stopped
Data Mining. Feature selection in Clustering
DMTeam
Meaning and usage of the MAXIMUM_STATES parameter of the Microsoft_Clustering algorithm. What it does and how to turn it off “I have this one discrete column in my data table with a couple of hundreds of different values, but when I use it in clustering model it models the column with only 100 distinct states plus one of them has unrealistically high probability, and overall the resulting clustering is somehow not what I would expect.”
How to avoid writing SQL for ADO.NET DataAdapter
Dejan Grujic
Automatic creation of SQL for CRUD operations when Strongly Typed DataSets are used
SQL Server 2005. Ranking Functions, TOP and Aggregates
Cihangir Biyikoglu
This is something I came across a few times within the last few weeks so thought I’d share the findings: You probably heard about ranking functions by now. However you may have a missed this great benefit ranking functions bring to easing a complex scenario: Combine TOP functionality with aggregations. Example; getting something like “top 3 most popular songs every day” out of the “requests” table on a jukebox can be challenging on a large table. Details follow: Assume a table with the following schema. This table records every individual requests played on the jukebox
SQL Server Centric .NET Code Generator
Kevin Kline
Looking for a quick-n-dirty way to generate SQL or .NET code from a data model? OlyMars is an interesting freeware, ‘beta’ project released by developer evangelist Pascal Belaud of Microsoft France. In the words of the website, it …”allows instant generation of both SQL and .NET code providing a complete library of stored procedures, .NET classes and ready-to-use Windows/Web form controls (including associated documentation).” That’s quite a powerful set of features for what is, essentially, a free product
Undocumented DBCC Commands
Kevin Kline
If you’ve been a SQL Server DBA for very long, you’ve probably made use of some cool but undocumented DBCC commands. Kalen Delaney, in her series of articles in SQL Server Magazine mentions several very powerful undocumented DBCC commands that are extremely useful for performance tuning, such as DBCC PAGE
Getting a Handle on SQLXML
Kevin Kline
XML is one of those areas where I remain blissfully ignorant. But I have this nagging feeling that I’d better catch up, and fast. A document on the MSDN website that has helped me catch-up is called ‘SQLXML Best Practices for Performance’ and it can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsql2k/html/sqlxml_optimperformance.asp.
Optimizing SQLXML Performance
Carl Perry
How to optimize SQLXML performance for databases, including SQL Server 2000. (12 printed pages)
Database Mirroring and its affect on transaction throughput
Larry Chesnut
While I was doing some testing of database mirroring I wondered to myself what would happen to transaction throughput on the principal server under various stresses and considerations. The point where performance on the principal database has the highest likelihood of being affected is when the mirroring has been setup to provide both the highest degree of protection and availability. In that case you are configured to run the mirror in what is called synchronous mode along with the accompanying FULL transaction safety mode
Set-based logic can improve query performance
Robert L. Bogue
Using some classical mathematical thinking can speed up some of your database code. We'll show you how
MSSQL Server 2000 Reporting Services: Black Belt Administration: Prepare the Execution Log for Reporting
William Pearson
General optimization of RS' performance is, beyond argument, one of the more important functions of the Administrator. In evaluating performance from various perspectives at the Administrative level, one readily useful source of information is the data we can obtain from the logs created by the system itself. Reporting Services generates a number of log files to capture information about server operations, status, and so forth. Within this group of logs, which we will explore individually within prospective articles within our series, the Report Server Execution Log is a great place to start in setting up a basic performance and auditing analysis capability
Yukon. DB Mirroring - just how long does it take before all the magic of the failover process starts?
Larry Chesnut
One of the most popular features about database mirroring is its ability to perform automatic failover. However, to do this several requirements must be in place. The first is that the mirroring session be in synchronous mode and that the mirror is in a state called synchronized. But that is not all, there also has to be a third instance of SQL Server 2005 called a witness server, and this server instance has to be online and able to communicate with the principal and mirror servers. As an important reminder, you should for the sake of reliability have the witness server residing on a third computer rather then on either the principal or mirror server. So if all these conditions are met, then when would an automatic failover happen?
Altering a column on a Replicated Table
Paul Ibison
Sometimes the schema of a replicated table needs altering. There are many reasons this might be the case eg possibly the datatype has been incorrectly chosen, or a default is missing, or we want to rename a column. Attempting to change the table schema directly will result in the error
SQL Server 2005 Recursive Functions
Dan Sullivan
SQL Server 2005 has added a new format for queries called a Common Table Expression or CTE. CTE’s are part of the SQL:1999 Specification and represent further compliance with this specification by SQL Server. This article will cover using one of the many capabilities of CTE’s, implementing recursive functions. A recursive function is a one that iteratively executes itself. Understanding how CTE’s implement recursive functions is the first step to understanding the full capabilities of CTE’s
Show Users Complex Data
Andy Clark
Red Brook Software's WiredNav 2.0 is an excellent tool for displaying data based on complex relationships. It implements a control that examines the properties in your data-bound controls and synchronizes them—no coding is required. The WiredNav control installs in the General section of your VS.Net toolbox. You add WiredNav to a form by dragging and dropping it. WiredNav adds a record browser to your application that is similar to the ADO Data control, but more powerful. It not only supports moving among records, but searching, printing, reporting, record insertion, editing, data validation, and commit/rollback as well. WiredNav implements these features through disconnected recordsets that minimize application impact on your database server (see Figure 1)
NVARCHAR vs. VARCHAR
What is the difference between nvarchar and varchar in SQL Server 2000? SQL Server provides both datatypes to store character information. For the most part the two datatypes are identical in how you would work with them within SQL Server or from an application. The difference is that nvarchar is used to store unicode data, which is used to store multilingual data in your database tables. Other languages have an extended set of character codes that need to be saved and this datatype allows for this extension. If your database will not be storing multilingual data you should use the varchar datatype instead. The reason for this is that nvarchar takes twice as much space as varchar, this is because of the need to store the extended character codes for other languages
15 Seconds : Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
Dina Fleet Berry
There are many times when using SQL Server 2000 Query Analyzer to debug Sql statements is a better choice than debugging in the .NET Visual Studio environment. I generally choose SQL Query Analyzer to debug SQL if the bug is narrowed down to the SQL stored procedure. If you have narrowed down the issue to SQL, there is no reason to bring in the overhead of an application development environment such as Visual Studio. Finding the problem quickly includes not loading down the machine's processing with unnecessary stuff like the calling application. This assumes that whatever permissions you are using can be faked or bypassed so that the security context is the same as the original buggy circumstances in the calling application
A True Tree User Control for Presenting Hierarchical Data
Jayram Tallamraju
The standard TreeView control that is available in .NET is powerful and sufficient in most cases, but there are situations where seeing data in a true tree format is more intuitive vs. seeing data in the TreeView. The focus of this article is to show how to present hierarchical data in a true tree format, as an alternative to using the standard TreeView control
XML Generator Script
Luke Malyurek
This stored procedure will build an XML document containing metadata for a given tablename / parameter. I have placed this in an asp file along with a stylesheet to format the output in our environment. A little tweaking with vbScript for a pull down list of tablenames, and it works well. Now all of our developers can see our column names, types, nullablility, etc. through their web browsers. I have placed this in a stored procedure just for posting the code. Please note that the exlusions of objects with a name like 'meta%' is specific to my current schemas so you will be able to remove these
Understanding "Yukon" Schema Separation
Database-Security.Info
Well it has finally arrived, at least in the Beta version. Microsoft's long awaited latest version of it's SQL Server product has arrived in Beta version and holds promise to be a major and successful revision of this fine product. I have had the Beta version for a few months now and one of the new security items that has intrigued me the most is the separation of users and schemas. I've worked with this form of separation before in Microsoft's chief competitor, but this article is not a comparison of the two products or the way they implement schema separation; it is an article on the basics of user/schema separation for those SQL Server DBAs who may have not worked with separated schema separation before
SQL Server 2005. Database Snapshots
Larry Chesnut
I recently had the chance to review the Database Snapshot module written by Scalability Experts for the SQL Server 2005 project. For those who do not know what a Database Snapshot is in the next version of SQL Server, it is basically a way to utilize an existing database’s data for a read-only, point-in-time copy. This snapshot is accomplished by utilizing the original database’s data pages for the new snapshot database and only creating copies of the data pages if a modification has been made in the original database. This allows for reduced storage space needed for multiple copies of the database for reporting or archival purposes. Just in case you are wondering how this is done, a copy of the unmodified data page is placed in the snapshot database’s sparse file and referenced by the snapshot from that point on. Yes, if you have a heavily modified original database then the snapshot will have to copy numerous data pages over to its sparse file, but usually most database have a large percentage of older data that is not changed. It is this large amount of old data being used by multiple snapshots that the disk savings are gained
Yukon. Adventures in Clustering on 8 Nodes
Larry Chesnut
I imagine there are not too many of you out there who have the where-with-all to test out SQL 2005 Beta 2’s clustering abilities on an 8 node cluster. This is a new feature available to SQL 2005 and only when using Windows 2003 Enterprise or Datacenter editions
SQL Injection: Are Your Web Applications Vulnerable?
SPI Dynamics, Inc.
SQL injection is a technique for exploiting web applications that use client-supplied data in SQL queries without stripping potentially harmful characters first. Despite being remarkably simple to protect against, there is an astonishing number of production systems connected to the Internet that are vulnerable to this type of attack. The objective of this paper is to educate the professional security community on the techniques that can be used to take advantage of a web application that is vulnerable to SQL injection, and to make clear the correct mechanisms that should be put in place to protect against SQL injection and input validation problems in general
Manipulating the Windows Registry using SQL Server Extended Stored Procedures — Part 1: Reading and Writing to the Windows Registry
Gregory A. Larsen
The Windows Registry is a hierarchical structure for storing valuable information about the hardware and software installed on a computer
Replacing and Documenting Obsolete Functions Using T-SQL
Eli Leiba
While developing applications using vendor software packages, you have likely encountered the arrival of a new software version. Although the new version inevitably contains many improvements, it generally includes a vendor announcement that many of the older version’s functions are obsolete and are not to be used in the new version. The vendor provides a replacement function and the programmer is instructed to systematically replace all obsolete function code with the new and improved version
Another Use for Views
Joe Celko
Craig Mullins did an excellent article called “A View Review” on the various uses for VIEWS which applies to SQL, in general, as well as DB2. But he missed another use that has become possible in SQL products as they add more Standard SQL features. Consider a schema for a chain of stores that has three tables, thus
Nulls Nullified
Fabian Pascal
It is not possible to be a proper database practitioner without knowledge of data fundamentals, yet a vast majority of practitioners possess very little such knowledge. What is more, most of what is published in the industry, or taught in academia, is devoid of fundamentals, and not only centers almost exclusively on tools and products, but is more often than not outright wrong, because authors and teachers are not familiar with fundamentals either and, worse, are dismissive of them
On the Trail of the ISO Week
Christoffer Hedgate
The other day, at a Swedish discussion forum that I visit, someone asked why SQL Server regards week 53 as week 1, and how to get around it. My first -- and simple -- answer was of course that this is simply the way they have implemented the week number function (DATEPART(wk, @date)) in SQL Server. In Sweden -- as well as many other countries -- we use the international standard ISO 8601 for defining week numbers, but this is not the case in America. It would of course have been nice of the SQL Server team to supply a function where we could choose which way we want to calculate the week number (as in Oracle and many other RDBMSs that supply both a proprietary implementation as well as others such as ISO 8601), but since they did not we will have to make our own implementation
Setting Matters Straight
Fabian Pascal
The American business culture in general, and the IT industry in particular take pride in requiring and rewarding experience and intuition, preferred over formal education and foundation knowledge. That is a sure way—indeed, the only way—in which practitioners can get things upside down and backwards: by not undergoing an appropriate formal education, but rather drawing their own, usually wrong conclusions from their own trial-and-error practice
Protect databases from SQL injection
Arthur Fuller
Hackers may use SQL injection to attack your web application. Here's some tips on avoiding problems
Trace Messages Part I: Managing Application Sessions
Andrew Novick
The current theme is logging messages so that they get to the proper human. The first two issues for the theme discussed the SQL Server ErrorLog and the SQL Server Agent ErrorLog. Both facilities are places where SQL Server places messages for DBAs and developers. Both can be very useful. But what about messages from user code such as a stored procedure? Where should it go?
One man’s struggles with clustering
Larry Chesnut
Well, here I am, feeling a little relieved, but genuinely frustrated that troubleshooting some install problems are harder than it was with SQL 7.0\2000. However, to be fair, learning how to troubleshoot on 2K was no picnic either
Versioning Controlled Build
Julijan Sribar
A Visual Studio add-in that automates AssemblyVersion control
Building Better BI in SQL Server 2005
Bill Baker
Since its inception, Microsoft's SQL Server Business Intelligence (BI) team has been guided by the overriding goal of making business data usable and accessible to as many people as possible. As the team's general manager, Bill Baker works with the people who design and develop BI tools such as Integration Services (formerly data transformation services—DTS), Analysis Services, and Reporting Services. Baker recently talked with SQL Server Magazine about SQL Server 2005's new BI tools and how they work together to streamline delivery of business-critical information
Adventures in Clustering on 8 Nodes, pt. 2
Larry Chesnut
As I said in the last installment, it is certainly rare at this stage of the game to test certain aspects of Yukon, in particular, clustering and especially when using so many nodes. I for one don’t have those kinds of resources. But, I have done some preliminary testing with two nodes, and that raised one significant question in my mind. Time!
Yukon. Database Mirrors and ?’s about their naming, endpoints, and port numbers
Larry Chesnut
Some interesting experiences have come up lately with mirroring and I thought you might want to be forewarned about some administrative items. I always like to know about prospective pitfalls before I plunge headfirst into things. It can save a lot of time and frustration later
DBCC CHECKDB and Parallelism
Larry Chesnut
Recently I was told about a recurring problem some folks are having when they are using DBCC CHECKDB. It seems that they have figured out the problem lies in the checkdb’s use of parallelism. On SQL Server, the degree of parallelism for DBCC CHECKDB is determined automatically by the query processor in the same way as that of parallel queries. In the case of DBCC CHECKDB, the query processor re-evaluates and automatically adjusts parallelism with each table or batch of tables checked. Their problem comes when the batch of tables (very large + 300 GB) still being worked over by the checkdb hasn’t finished and is going full bore in parallelism, and then other processes need to get started, but are not getting the love they need
Microsoft SQL Server 2005. CLR and its relationship to MemToLeave
Larry Chesnut
I hear about and see first hand on a regular basis how people are faced with a constant problem of trying to make sense of how their SQL Server is using memory and more specifically the region of memory called MemToLeave. Understanding this region of memory is particularly critical on a 32 bit version of SQL Server, because it exists in such a way that MemToLeave cannot be increased simply by adding more physical memory beyond the 4 GB limit. MemToLeave cannot take advantage of AWE memory, so management of the user mode address space can become tricky when consolidating multiple instances of SQL Server onto one box. I could go on talking about the boot.ini file and the /3GB switch and kernel mode and user mode, and that there are many things that contribute to MemToLeave address space usage, but that’s not the point today
Triggers in SQL Server 7.0 and 2000 - The Common Ground
Brian Kelley
This is a two part series on how triggers work in the two latest versions of MS SQL Server. Because there are some pretty significant additions in trigger functionality from 7.0 to 2000, we'll first need to look at what the two versions have in common. The second part to this series will look at the differences between the two MS SQL Server versions
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
Executing Database Commands Asynchronously with ADO.NET 2.0
Thiru Thangarathinam
Microsoft's upcoming ADO.NET 2.0 gives you the ability to execute SQL commands asynchronously, sidestepping the blocking effect of making lengthy database calls and letting you make multiple queries simultaneously, using polling, WaitHandles, or delegate notification to know when query execution completes
DATA PIRACY: THE THREAT FROM WITHIN
Ken Richardson
Much of the typical security budget protects against intrusion. We're prepared for malicious outsiders breaking in, searching for weaknesses in our perimeter firewalls and our multiple layers of security. But it turns out that the biggest threat to our databases doesn't generally come from that direction
Find TCP/IP Sockets Net-Libraries port number used by SQL Server 2000
Muthusamy Anantha Kumar
When a DBA is managing many different SQL Server boxes, it can be a tedious job to find the port numbers used by all of the SQL Servers. In this article, I would like to discuss several methods for finding the Port numbers used by SQL Server
What about Mount Points and Clustering SQL Server 2005
Larry Chesnut
At least once every other week I hear the question asked about mount points or mounted volumes and whether they will be are supported in a SQL Server 2005 cluster. The question is a fair one since DBA's up till now have had to cope with 'clustered' SQL Server 2000 not supporting them, see http://support.microsoft.com/?id=819546
Microsoft SQL Server 2005. How to determine whether a procedure is multi-part
Larry Chesnut
Navigating around in SQL 2005 in beta 2 is a constant adventure, always uncovering something new. It happened to me earlier today. Suppose I create a multi-part stored procedure like
Statement level statistics maintained for cached SQL statements - Sys.dm_exec_query_stats
Larry Chesnut
Here’s an interesting question from a customer we recently received
Microsoft SQL Server 2005. How does Online Indexing Work?
Larry Chesnut
Well, to answer that question would take a book and maybe a miniseries on the local cable access channel. But in the mean time let me describe to you my learning adventure on the subject
Yukon. What has replaced FirstIAM and/or the ability to traverse an object based on disk order allocations?
Larry Chesnut
The SQL Server 2000 FirstIAM hasn't been replaced, it's just been moved and subdivided :) In SQL Server 2005, each partition owned by an object can contain 3 allocation units (AU’s or IAM chains). The start, root, and first IAM in each AU sits’ in storage-engine metadata. Microsoft will not expose the IAM chain page information like they used to in 7.0 and 2000’s sysindexes, but to be fair to them, they do expose the AU’s in sys.allocation_units
Microsoft SQL Server 2005. My first look into row versioning
Larry Chesnut
During my time researching new aspects to SQL Server 2005 one area I have been intrigued with was the mechanics of the snapshot isolation level. One particular question popped into my mind that had me go digging further. The question concerns how SQL versus Oracle implement row versioning which is a vital component for the isolation level
Microsoft SQL Server 2005. The Management Studio GUI and displaying all the rows
Larry Chesnut
One thing that I really miss from the old SQL 2000 and 7.0 SQL Enterprise Managers (SEM) was the ability to right-click a table and then choose Select All... then instantly see (and even update) data in a table. I wish there was a short cut key or a way for me to create a right click option in Management Studio to do the same. There is a way to at least display the rows, albeit a sloppy and completely unintuitive series of steps that I find wholly unacceptable
Yukon. Installation Options, and WMSDE. WMSDE? What's that?
Larry Chesnut
I was digging around the other day, and came across something in the SQL 2005 BOL that describes WMSDE as an edition that cannot be upgraded
Yukon. Dynamic ‘max worker threads’? What does that mean to me?
Larry Chesnut
Have you looked at the sp_configure out put for SQLL 2005 lately? Noticed anything different? Here’s one item, ‘max worker threads’. See how the default setting is now 0 rather than 255? This is an example of another item in SQL going dynamic, much like ‘locks’ or ‘open objects’ made the change back in SQL 7.0 days
Yukon. Do You Suffer from Insufficient Space in TEMPDB?
Larry Chesnut
Sounds almost like a commercial for a health care product. Well, I suppose the health of your tempdb for SQL 2005 will be of paramount interest from here on out. Why? Well, as my good friend Bill Shakespeare is prone to say, "There are more things in heaven and earth, Horatio, than are dreamt of in your philosophy." Recently, I heard about someone having a problem. They said they found a clue in their errorlog

[В начало]

ФОРУМ SQL.RU

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

Новые упражнения на http://sql.ipps.ru
Суррогатные или естественные
Новость No.2 - FTP SQL.RU
Комбобоксы и блокировки.
Рост продаж в процентах в каждом месяце по сравнению с предыдущим
POST и WinHTTP
прошу обсудить шаблон для вложенных хп
Удаленные сервера
Работа с транзакциями в SQL Server - ПРОБЛЕМА !
isql & "козябры"
Ошибка при запуске агента не с системной учетной записью
Дата!
Интеграция на низком уровне для синхронизации с внешней БД
Больше книг хороших и разных!
Хронология данных - ваши комментарии
DTS использует BCP?
Как распорядится дисками?
Индексы: требуется консультация по улучшению производительности.
Проблема с Linked Server
Как в T-SQL обработать возврат в виде набора строк от ХП

[В начало]

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

Дефрагментировать или нет ?
Размещение full-text индекса
Подключение к изолированной БД SQL Server 2000
Кодировка скрипта
Помогите найти OLE DB Provider for DB2
Как проще заменить Enterprise Edition на Standard Edition, сохранив все объекты?
Можно ли выгрузить в текст файл в Unicode в utf-16 big endian(+)

[В начало]

#231<<  #232

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

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

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



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


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

В избранное