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

MS SQL Server

  Все выпуски  

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


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


#183<<  #184

СОДЕРЖАНИЕ

1.СЕМИНАР
1.1.Обзор новшеств SQL Server Yukon Beta 1
2.СОВЕТЫ
2.1.SQL Server 2000 DTS. Часть 9. Задачи DTS Designer: Transform Data Task
3.ССЫЛКИ НА СТАТЬИ
3.1.Статьи на русском языке
3.2.Новые и обновлённые технические статьи Microsoft
3.3.Англоязычные статьи
4.ФОРУМ SQL.RU
4.1.Самые популярные темы недели
4.2.Вопросы остались без ответа

СЕМИНАР

Обзор новшеств SQL Server Yukon Beta 1

Дата: 02.03.2004г. 18:00
Место: г. Москва. Чапаевский пер., 14. Представительство Microsoft в России и СНГ.
Доклады:
1. Database Mirroring в Yukon. Либерман Ян.
2. Служба посредника (Service Broker). Нуралиев Заур.
3. Секционирование таблиц и индексов. Некошнов Георгий.

    Аннотация
    В данной презентации рассматривается секционирование таблиц, как средство решения основных проблем, возникающих в процесе проектирования, разработки и эксплуатации сверхболь-ших баз данных (VLDB). Дается рабочее определение VLDB, описаны возможные проблемы. Да-лее рассматривается ,что такое секционированние таблиц и индексов, и определяются цели сек-ционирования. Дается краткий озор средств секционирования в существующих версиях MS SQL Server и подробно рассказывается о новых механизмах секционирования в Yukon. В зависимости от целей рассматриваются различные сценарии секционирования таблиц, Каждый сценарий вклю-чает проектирование, реализацию, использование и сопровождение. К каждому сценарию приво-дятся с примеры исходных кодов. Акцентируется внимание на ситуациях, которые неразрешимы иными способами, а так же на ограничения, которые накладываются на используемые объекты. Дополнительно описывается секционирование индексов.

4. Внутренняя реализация репликации в Юкон. Сердюк Владимир
    Аннотация
    1) Transactional publication
    2) Transactional publication with updatable subscriptions
    3) Merge publication

    Обзор внутренних механизмов репликации в Юкон. Обзор реализации на уровне внутренних процедур.
  • Кодо-генерация репликационных объектов в Юкон.
  • Логика обновлений изменений.
  • Логика разрешения конфликтов.
  • Описание системных таблиц и внутренних процедур ответственных за репликацию.
  • Сравнение с SQL server 8.0.

Для участия в семинаре, Вам необходимо прислать на адрес mssqlhelp@pisem.net письмо - заявку, в свободной форме, с обязательным указанием Ф.И.О. При себе необходимо иметь документ, удостоверяющий личность.

Внимание! Количество мест ограничено, поэтому прошу Вас не откладывать регистрацию. В случае успешной регистрации, за день до даты проведения семинара Вам придёт подтверждение по электронной почте.

Карта проезда в представительство Microsoft:

СОВЕТЫ

SQL Server 2000 DTS. Часть 9. Задачи DTS Designer: Transform Data Task

По материалам статьи Marcin Policht: SQL Server 2000 DTS Part 9 - DTS Designer Tasks

В нашей предыдущей статье, мы начали рассмотрение основных принципов и возможностей задачи Transform Data Task. Мы продолжаем эту тему, сосредоточившись на её более "тонких" особенностях. Мы уже описали цели четырех закладок Transform Data Task Properties, реализующих наиболее распространённые сценарии использования этой задачи, не обращаясь к теме использования многопроходной, стадийной обработки данных.
Последняя закладка окна Transform Data Task Properties называется Options, и содержит несколько параметров, управляющих обработкой ошибок и более гибким преобразованием данных. Ошибки могут быть зарегистрированы в файле исключений, расположенном в произвольном месте и с любым именем. Его тип может быть совместимым с SQL Server 7.0 (в случае, если Вы используете парсер, написанный для этой версии) или его можно выбрать как отдельные файлы для сообщений об ошибках, ошибках источника и ошибок адресата (с расширениями .source и .dest, соответственно). В любом случае, Вы можете указать детали форматирования, например, используемые для разделителей строк и полей символы, а так же обрамление текстовых строк (кавычки). В средней секции закладки Options определяются параметры перемещения данных, например, максимальное число возможных ошибок до окончания исполнения задачи, размер промежуточного буфера (число записей, выгружаемых из источника единовременно), номер начальной и последней записи (это позволяет ограничить размер области преобразования, пропустить заголовки или колонтитулы и возобновлять передачу в случае отказов). Наконец, последняя секция на закладке Options применима только к трансформации данных SQL Server, и позволяет ускорить загрузку данных (она рекомендуется для повышения производительности, хотя и создаёт угрозу целостности данных и должна выполняться после полного резервирования). После соответствующей настройки, можно сформировать множество подвариантов, таких как передача NULL значений в виде значений по умолчанию, реализация проверки ограничений, блокировка таблиц или вставка идентификаторов. Также Вы можете предписать обработку данных пакетами. Назначение параметра размера пакета в указании числа строк, которые будут использоваться как одна единица (когда он установлен в 0, все данные будут загружены одним пакетом). Давайте коротко рассмотрим назначение этого параметра.
Главное преимущество использования SQL Server 2000 Transform Data Task по сравнению с его предшественником SQL 7.0 - это степень детализации. Полный процесс преобразования данных может быть разделен на несколько стадий. Однако, по умолчанию, эти функциональные возможности скрыты. Чтобы воспользоваться ими, нужно вернуться в SQL Server Enterprise Manager и выбрать пункт Properties в контекстном меню папки Data Transformation Services. Вы увидите окно Package Properties, и в секции Designer нужно пометить чекбокс "Show multi-phase pump in DTS Designer. Обратите также внимание на другие параметры этого окна (хоть они и не связаны непосредственно с задачами, но могут быть полезны в других ситуациях). В частности Вы можете включить кэширование, чтобы ускорить процесс создания и открытия пакетов в DTS Designer (это обеспечит кэширование DTS задач, провайдеров OLEDB и трансформации, зарегистрированных на SQL Server, так что они не будут перезагружаться каждый раз при запуске DTS Designer). Имейте в виду, что если Вы пометите этот чекбокс, придётся использовать кнопку Refresh Cache (или повторно запускать DTS Designer), чтобы сделать доступными новых провайдеров. Предоставление возможности использования отладки упрощает поиск неисправностей в ActiveX скриптах, для чего задействуется используемый по умолчанию в операционной системе Windows отладчик. И наконец, Вы можете разрешить сохранение пакетов средствами Meta Data Services, который мы рассмотрим в следующих статьях этого цикла.
Пометьте чекбокс "Show multi-phase pump in DTS Designer" и нажмите кнопку OK, откройте папку Local Packages и потом пакет, который мы создали перед этим (для получения информации о создании этого пакета, обратитесь к предыдущей статье этого цикла). Откройте диалоговое окно Data Transform Task Properties этого пакета и убедитесь, что закладка Source содержит следующий SQL запрос:


SELECT Shippers.ShipperID, Shippers.CompanyName, Shippers.Phone, COUNT(OrderID) AS Orders
FROM Shippers
INNER JOIN Orders
ON ShipVia = ShipperID
GROUP BY Shippers.ShipperID, Shippers.CompanyName, Shippers.Phone

Так как мы используем в качестве получателя данных базу tempdb, вероятно Вам потребуется обновить таблицу - адресат данных (иначе Вы получите сообщение об ошибке, указывающее на то, что получающая данные таблица не существует). Чтобы проверить так ли обстоит дело, посмотрите содержание закладки Destination. Если структура таблицы не указана, нажмите кнопку Create..., и вставьте следующий SQL скрипт:


CREATE TABLE [ShippersOrders] (
[ShipperID] int NOT NULL, 
[CompanyName] nvarchar (40) NOT NULL, 
[Phone] nvarchar (24) NULL,
[Orders] int)

Далее, перейдите на закладку Transformations и обратите внимание на то, что появилось новое поле со списком "Phases filter", в котором по умолчанию, указано значение "Row transform", так как это было единственно возможным значением в SQL Server 7.0. Вы можете легко проверить, что этот список содержит много других значений, соответствующих всем возможным стадиям (и подстадиям) Transform Data Task. Чтобы исследовать максимум функциональных возможностей многофазной трансформации данных, мы будем использовать ActiveX скрипт, так что удалите все уже существующие преобразования с помощью кнопки Delete. Нажмите кнопку New и убедитесь, что выбрано значение ActiveX Script для создания нового преобразования, и подтвердите Ваш выбор. В диалоговом окне Transformation Options, вызываемом кнопкой Edit, Вы увидите дополнительную закладку с именем Phases. На ней Вы можете определить какие стадии (и подстадии) будут использоваться в преобразовании. Как говорилось раньше, была установлена функция Row transform, и Мы её можем довольно просто изменить. Настройте содержание закладок Source и Destination так, чтобы все имеющиеся поля были внесены в список отбора полей. Перейдите опять на закладку General окна Transformation Options и нажмите кнопку Properties .... Вы увидите диалоговое окно ActiveX Script Transformation Properties, со всеми стадиями, внесенными в список на закладке Phases (новая закладка должна появиться в нижней - левой части диалогового окна). Отметьте все чекбоксы с левой стороны окна, и автоматически сгенерируйте код, нажав кнопку Auto Gen. Как только Вы это сделаете, код появится в правой части окна.
Как Вы можете видеть в этом окне, многофазная обработка данных разделена на следующие стадии и подстадии:

  • Pre Source Data - первая стадия, выполняемая в задаче только один раз, перед первой выборкой данных из источника. Эта стадия может использоваться, например, для создания файла системного журнала, калибровки данных или записи заголовков.
  • Row Transform - вторая стадия, которая полностью реализует функциональные возможности задачи Transform Data в SQL Server 7.0, и она исполняется тогда, когда новая запись получается из источника данных и записывается получателем данных.
  • Post Row Transform - третья стадия, которая осуществляет дополнительную обработку в зависимости от результата исполнения второй стадии. Этот результат определяет, какая из подстадий (Insert Success, Insert Failure или Transform Failure) будет выбрана. Подстадия Insert Success будет вызвана если не было ошибок, Insert Failure указывает на проблемы с получением данных (например, вставки NULL значений в не допускающие такие значения поля), а Transform Failure обычно появляется в результате ошибок преобразования типов (например, символьный тип в целое число). Post Row Transform обычно выполняется после стадии Row Transform, выполняющей выборку данных из источника, хотя этот порядок может зависеть от нескольких факторов. Если точнее, то Transform Failure и Insert Failure могут привести к преждевременному завершению задачи, если предыдущая стадия критична для результата или (см. выше) был установлен параметр максимального числа допустимых ошибок (закладка Options в Transform Data Task Properties). Из других возможностей можно отметить включение стадии Batch Complete, когда был достигнут заданный размер блока (его мы рассмотрим чуть ниже) и стадия Post Source, когда последние данные были обработаны.
  • Batch Complete - четвертая стадия, выполняется один раз после завершения обработки каждого блока данных (который задаётся описанным ранее параметром и определяет число вставляемых одним блоком записей, задать его также можно на закладке Options в Transform Data Task Properties). С помощью этой функции, Вы можете разделить выгрузку данных на меньшие части и управлять очисткой и сохранением данных отдельно для каждого такого блока.
  • Pump Complete - эта стадия выполняется после того, когда последние данные были обработаны. Так как действия, выполняемые на этой стадии, не осуществляют никакого доступа к источнику или адресату данных, эта стадия типична для независимых от данных операций (например, очистка промежуточных результатов, манипуляция с глобальными переменными или подсчёт ошибок).
  • Post Source Data - заключительная стадия задачи, которая обеспечивает доступ к данным. Она часто используется для записи нижних колонтитулов (хотя и может включить множество вариантов других действий, например, очистки глобальных переменных).

Разделение обработки на стадии обеспечивает несколько преимуществ. Вы получаете больше контроля над манипуляцией данными и возможность обработки ошибок с восстановлением. Преобразование может быть повторно начато с места сбоя, без повторной загрузки уже обработанных данных.
Давайте рассмотрим образец ActiveX скрипта, демонстрирующего многофазную обработку в Transform Data Task. Для примера, давайте предполагать, что мы будем использовать существующее преобразование, заполняя таблицу базирующуюся на Shippers с подсчётом общего количеством заказов для каждого ShipperID. Разобьём данные на два пакета и будем записывать информацию о процессинге в текстовый файл (название которого храниться в глобальной переменной "LogFile"), включающий такую информацию как: "TotalBatches", "TotalRows" и "FailedRows". Сейчас, автоматически сгенерированный код нашего основанного на ActiveX скрипте преобразования должен иметь следующий вид (Function Main выполняется на стадии Row Transform):


Function PreSourceMain()
 PreSourceMain = DTSTransformstat_OK
End Function

Function Main()
 DTSDestination("Orders") = DTSSource("Orders")
 DTSDestination("Phone") = DTSSource("Phone")
 DTSDestination("CompanyName") = DTSSource("CompanyName")
 DTSDestination("ShipperID") = DTSSource("ShipperID")
 Main = DTSTransformStat_OK
End Function

Function TransFailureMain()
 TransFailureMain = DTSTransformstat_OK
End Function

Function InsertSuccessMain()
 InsertSuccessMain = DTSTransformstat_OK
End Function

Function InsertFailureMain()
 InsertFailureMain = DTSTransformstat_OK
End Function

Function BatchCompleteMain()
 BatchCompleteMain = DTSTransformstat_OK
End Function

Function PumpCompleteMain()
 PumpCompleteMain = DTSTransformstat_OK
End Function

Function PostSourceMain()
 PostSourceMain = DTSTransformstat_OK
End Function

Вначале, создадим глобальную переменную DTS пакета с именем "LogFile", перейдя в диалоговое окно Package Properties (как это делается, описывалось в одной из предыдущих статей) и выбрав тип "строка" с каким - либо значением (например, "d:\logs\MPDPump.log" - который нужно предварительно создать). После этого, измените ActiveX скрипт, следующим образом:


'  Copy each source column to the destination column
Function PreSourceMain()
 Const Overwrite = TRUE
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 Set oLogFile = oFSO.CreateTextFile(DTSGlobalVariables("LogFile").Value, Overwrite)
 DTSGlobalVariables("TotalBatches").Value = 0
 DTSGlobalVariables("TotalRows").Value = 0
 oLogFile.Close
 Set oFSO = Nothing
 PreSourceMain = DTSTransformstat_OK
End Function

'  Copy each source column to the destination column
Function Main()
 DTSDestination("Orders") = DTSSource("Orders")
 DTSDestination("Phone") = DTSSource("Phone")
 DTSDestination("CompanyName") = DTSSource("CompanyName")
 DTSDestination("ShipperID") = DTSSource("ShipperID")
 DTSGlobalVariables("TotalRows").Value = _
  DTSGlobalVariables("TotalRows").Value + 1
 MsgBox "Row #: " & DTSGlobalVariables("TotalRows").Value
 Main = DTSTransformStat_OK
End Function

Function TransFailureMain()
 TransFailureMain = DTSTransformstat_OK
End Function

Function InsertSuccessMain()
 InsertSuccessMain = DTSTransformstat_OK
End Function

Function InsertFailureMain()
 InsertFailureMain = DTSTransformstat_OK
End Function

Function BatchCompleteMain()
 DTSGlobalVariables("TotalBatches").Value = _
  DTSGlobalVariables("TotalBatches").Value + 1
 MsgBox "Batch #: " & DTSGlobalVariables("TotalBatches").Value 
 BatchCompleteMain = DTSTransformstat_OK
End Function

Function PumpCompleteMain()
 Const ForReading = 1, ForWriting = 2, ForAppending = 8
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 Set oLogFile = oFSO.OpenTextFile(DTSGlobalVariables("LogFile").Value, ForWriting)
 oLogFile.WriteLine "Total Rows:"  & vbTab & DTSGlobalVariables("TotalRows").Value
 oLogFile.WriteLine "Total Batches:"  & vbTab & DTSGlobalVariables("TotalBatches").Value
 oLogFile.Close
 Set oFSO = Nothing
 PumpCompleteMain = DTSTransformstat_OK
End Function

Function PostSourceMain()
 PostSourceMain = DTSTransformstat_OK
End Function

Этот простой пример демонстрирует разделение записей на блоки, и сохранение общего числа блоков и записей в файл журнала. Он призван помочь Вам создавать свои, более сложные пакеты. Также, Вы можете изучить главу Phased Transformation Samples в SQL Server 2000 Books Online для получения дополнительной информации на эту тему (Вы найдете там примеры, демонстрирующие TransformFailed и InsertFailed). В следующей статье, мы рассмотрим ещё две задачи DTS.

[В начало]

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

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

Data Mining - добыча данных
BaseGroup Labs©
Доступность методов записи и хранения данных привели к бурному росту объемов хранимых данных. Объемы данных настолько внушительны, что человеку просто не по силам проанализировать их. Хотя необходимость проведения такого анализа вполне очевидна, ведь в этих 'сырых данных' заключены знания, которые могут быть использованы при принятии решений. Для того, чтобы провести автоматический анализ данных, используется Data Mining...

[В начало]

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

BUG: You cannot start the SQL Server Agent Service for an instance of SQL Server or the SQL Server 2000 Desktop Engine that has the same instance name as the instance name of a previously uninstalled instance of the SQL Server 2000 Desktop Engine (Windows
FIX: Calculated members may return incorrect results for dynamic formulas
FIX: MDAC: Patch Available for Script Injection with XML Tag and Unchecked Buffer in SQLXML ISAPI Extension Vulnerabilities
FIX: MDX queries on a cube that contains a virtual dimension may not reflect changes after the incremental update on the virtual dimension
FIX: Patch Available for Script Injection with XML Tag and Unchecked Buffer in SQLXML ISAPI Extension Vulnerabilities
FIX: Replication Agent Startup Step Name Shows "Log Reader Agent startup message"
FIX: Some cubes are not processed by the process database operation
FIX: The initialization phase of Analysis Services Database Processing takes several hours to complete
FIX: When you run an MDX query on a write-enabled cube, the query returns #Err, or the query fails and you receive an "Unable to open cellset..." error message in SQL Server 2000 Analysis Services
FIX: You cannot insert explicit values in an IDENTITY column of a SQL Server table by using the SQLBulkOperations function or the SQLSetPos ODBC function in SQL Server 2000
FIX: You receive an error message when you use the SQL-DMO BulkCopy object to import data into a SQL Server table
How to import reports from Microsoft Access to Reporting Services
How to use static and dynamic port allocation in SQL Server 2000
INF: Frequently Asked Questions - SQL Server 2000 - Setup
MBS: Client DPA Setup Error "Cannot Modify Registry Error - 1"
TechNet Support WebCast: Administering and maintaining the tempdb system database in Microsoft SQL Server
Transactional replication performance tuning and optimization (white paper)
You may receive error messages when you use the CREATE DATABASE statement to create a SQL Server database

[В начало]

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

Lack of 'compelling features' will slow Yukon adoption Sam Varghese
Adoption of, and migration to, the next version of Microsoft SQL Server, codenamed Yukon, will be slowed down by a lack of compelling features for any single customer segment, and also by the Enterprise Agreement/Software Assurance licensing issues, a commentary by the technology research firm Gartner says
Review of Transact SQL Desk Reference
Bruce Szabo
Can you have books online (BOL) on your bookshelf? Well not quite but if you put The Transact –SQL Desk Reference by Daec Lancaster on your shelf it may be pretty close. This book is a reference book for the DBA who wants to have a lot of information at his or her fingertips without having to access books online. The book’s preface discusses the desire to be able to bring books online to ones bookshelf while illuminating the ANSI SQL-92 features of Microsoft SQL Server 2000. The book did a great job of meeting these goals but if I was new to Transact-SQL and was looking for a first book I doubt that this would be it Y2K Strikes Again
Steve Jones
For me at least. I'm sure the rest of you are ok, but I got bitten by a bug just this morning that I hadn't seen or expected since just after the Y2K fiasco. It's a software bug, one totally introduced by me, but one which I have run with for the over a year without noticing
Reuse SQL Code Easily With UDFs
Roman Rehak
Use one of SQL Server 2000's newer features to write efficient and reusable SQL code
Microsoft Hones Its Security Strategy
Paul Thurrott
At its annual Worldwide Partner Conference in New Orleans last week, Microsoft executives described changes to the company's security strategy, including a new "Secure the Perimeter" process that's part of its wider Trustworthy Computing initiative. Does Microsoft finally get security?
Is Microsoft to Blame for SQL Slammer?
Peter Galli and Anne Chen
DALLAS—Microsoft Corp. and its customers need to take joint responsibility for security issues such as the SQL Slammer worm, which brought down systems all across the world earlier this year, several large enterprises said here at the TechEd conference on Monday
Reusing Identities
Dinesh Priyankara
In most table designs, Identity columns are used to maintain the uniqueness of records. There is no problem with insertion and modification of data using an identity column. With deletions though, gaps can occur between identity values. There are several ways to reuse these deleted (removed) identity values
Review of ApexSQL Log
Brian Kelley
ApexSQL Log is a new product from ApexSQL, formerly LockwoodTech Software. ApexSQL Log provides the capability to passively review the contents of database transaction logs and transaction log backups. For databases prepared beforehand (more on this under installation), ApexSQL Log gives the DBA the capability to audit what activity has occurred without the use of triggers and other mechanisms which require overhead. The current version is ApexSQL Log 1.1. ApexSQL Log was formerly known as Log Navigator
Introduction to MSSQL Server 2000 Analysis Services: Reporting Options for Analysis Services Cubes: ProClarity Part II
William Pearson
In Part I of this article, we returned to the objectives of an earlier subseries, Reporting Options for Analysis Services Cubes. As we stated in that set of articles, our focus was to respond to a constant request from readers: to explore options beyond the Analysis Manager / Sample Application interfaces for analyzing and reporting data in MSAS cubes. I began an examination of another such option, ProClarity, based upon a suggestion I received from a reader, and upon my own favorable experiences with this outstanding tool in recent months
DBA Call to Action: Zeroing in on Performance Problems
James Koopmann
Have you ever been asked to help with the evaluation of a database that is not performing optimally? Here is a quick guide to help you if you just do not know where to start
Monitor Event Viewer on Multiple SQL Servers
Muthusamy Anantha Kumar aka The MAK
In the typical IT department, an un-avoidable task is to monitor the Event Log on all of the servers. It is tedious to go through all the logs one by one, on a daily basis. In this article, the methods presented will help in monitoring the Event Viewer on many servers from a single place. In addition, I am going to discuss three different ways to monitor Event Log on a list of servers and store the output either in a .CSV file or on a database table. These methods fetch all of those errors and warnings that occurred in the last 24 hours
SQL Server 2000 DTS Part 9 - DTS Designer Tasks
Marcin Policht
In our previous article, we started discussing basic principles and applications of the Transform Data task. We will continue this topic here, focusing on its more advanced features. So far, we have described the purpose of four of the tabs of the Transform Data Task Properties dialog box in the most basic scenario, without resorting to the use of multiple processing phases
Creating an ADO.NET Universal Data Wrapper
Jayram Tallamraju
ADO.NET is equipped with many providers -- OLEDB, SqlClient, OracleClient and OdbcClient. Database vendors also supply providers, i.e Oracle's ODP.NET. Applications usually target a specific database with hard-coded provider-specific ADO.NET calls. However, there are many cases where it would be ideal to write a single reusable class that utilizes a variety of ADO.NET providers without code duplication. In these cases, the code knows which ADO.NET provider to use at runtime. Writing a single ADO.NET class that can support any ADO.NET provider at runtime is the focus of this article
Returning Multiple Tables into a DataSet
Karl Moore
One of the big new features of the DataSet over the old Recordset is its ability to hold multiple tables of data at a time. But, how many developers take advantage of this feature? How many still use multiple DataSet objects to hold multiple tables?
Create a .NET-J2EE Shared Database
Simon Guest
Create a shared database to provide interoperability between .NET and J2EE platforms, then extend data sharing by adding a notification level between platforms
Checking Whether SQL Server Is Available
Karl Moore
When you're designing applications that work with databases over the Internet, perhaps the largest problem you face is ensuring that everything can actually connect to everything else. You need to ensure that your users have a valid connection to the Net, and you need to ensure that your database server is up and running
CLR Proc Container
The CLR Proc Container is free software that enhances the capabilities of SQL Server stored procedures by opening a door to the .NET world. Code written in any .NET language can be invoked from stored procedures, providing stored procedures all the functionality of the full .NET runtime. Named procedures can be defined in .NET, dynamic procedures can be created and run, and binary objects passed between stored procedure code and the .NET object
Worst Practice - Adding a Column Without Thinking!
Andy Warren
It's funny how the smallest things can trip you up. Stop and think for a minute - if one of your developers requests a column be added to a table, how much effort do you (or should you) expend to make sure it won't break anything? Some things you might consider
Logins, Users, and Roles - Getting Started
Andy Warren
A few weeks ago we had a request in our DMO discussion form for some help with adding logins and users to a database using DMO. I posted the code sample below as part of that answer. But that discussion really brought two good (though perhaps obvious) points - you have to know how SQL works to use DMO effectively, and I think you need to consider which is the right tool - DMO, T-SQL, or Enterprise Manager. In this article I'd like to talk for a few minutes about how logins and users work, then move into a discussion of which tool might be best for adding logins and users
UDF for getting a column list for INSERT statements
Baya
If you've ever been in an environment where you're unfamiliar with the database schema, you know how tedious it is to write stored procedures that populate tables using the INSERT statement. This is particularly true if your tables have dozens of columns -- don't laugh, I've seen complex applications that have a few hundred columns per table
A quick UNION ALL trick
Dipak Padhy
Let's say that you have two tables that have columns of the datatype TEXT...
The Microsoft SQL Server MVP Program - An Interview with Stephen Dybing
Contributing Editor: Ron Talmage
Stephen Dybing, Microsoft SQL Server MVP Lead, recently explained the MVP program for PASS members
When the Lights Go Out -- SQL Server Business Continuity Planning
Contributing Editor: Richard Quimet
As the sun disappears over the western horizon, you suddenly realize that you have spent the entire afternoon in meetings with key managers of your growing company. The age-old topic was “business continuity”, or commonly known as “disaster recovery”. The discussion identified many action items centered on database and database server recovery in the event of unexpected future events that could make your life a living nightmare. As the DBA Manager and technical lead, you were reminded by senior management several times during the marathon meeting that times had changed, disasters and terrorist threats were real, and that you must defend the armada of SQL Servers at all costs. Of course, you knew that the term “all costs” was stated very candidly, and this unwavering financial support may disappear as more pressing tactical projects took a priority position in the long list of projects that must get done to sustain revenue goals during these tough economic times. Regardless, you had to come up with a plan over the next two weeks before the next scheduled business continuity meeting of the minds
A Lookup Strategy Defined
David Sumlin
Most databases designs nowadays seem to have at least a few if not many lookup or reference tables. (I’ll use these two terms interchangeably) These tables are those small tables that you maintain your list of States, or CustomerTypes or JobStatus or any number of valid domain values used to maintain data integrity within your application. These reference tables usually have simple 2 -4 columns with the naming convention usually following along the lines of ID, Value, and Description, and maybe Active. (e.g. CustomerTypeID, CustomerTypeValue, CustomerTypeDesc, CustomerTypeActive) I have seen database designs that have hundreds of these reference tables
Dynamisches SQL : Fluch und Segen
Erland Sommarskog, SQL Server MVP
Wenn Sie die verschiedenen Newsgroups uber Microsoft SQL Server verfolgen, wird es Ihnen auffallen, dass oftmals Fragen gestellt werden, warum die Statements
The Curse and Blessings of Dynamic SQL
Erland Sommarskog, SQL Server MVP.
Thanks to ASP MVP Jongshin Kim, this article is also aviailable in Korean. Frank Kalis has provided a translation in German
Arrays and Lists in SQL Server
Erland Sommarskog, SQL Server MVP.
In the public forums for SQL Server, you often see people asking How do I use arrays in SQL Server? Or Why does SELECT * FROM tbl WHERE col IN (@list) not work? This text describes several methods to do this, both good and bad ones. I also present data from performance tests of the various methods
Dynamic Search Conditions in T-SQL
Erland Sommarskog, SQL Server MVP.
A very common requirement in an information system is to have a function (or several functions) where the users may search the data by selecting freely among many possible search criterias. This is a tough challenge, because not only must you produce the desired output, but you must also keep the response times with in acceptable limits, at least for common searches. And on top of all, the code must be maintainable, so it can meet new needs and requirements
Implementing Error Handling with Stored Procedures
Erland Sommarskog, SQL Server MVP.
This is one of two articles about error handling in SQL Server. This article gives you recommendations for how you should implement error handling when you write stored procedures, including when you call them from ADO. The other article, Error Handling in SQL Server – a Background, gives a deeper description of the idiosyncrasies with error handling in SQL Server and ADO. That article is in some sense part one in the series. However, you can read this article without reading the background article first, and if you are not a very experienced user of SQL Server, I recommend you to start here. In places there are links to the background article, if you want more information about a certain issue
Error Handling in SQL Server – a Background
Erland Sommarskog, SQL Server MVP.
This is one of two articles about error handling in SQL Server. This article focuses on how SQL Server – and to some extent ADO – behave when an error occurs. The other article, Implementing Error Handling with Stored Procedures, gives advice for how you should check for errors when you write stored procedures. Logically, this article is part one, and Implementing... is part two. However, you can read the articles in any order, and if you are relatively new to SQL Server, I recommend that you start with Implementing.... The article here gives a deeper background and may answer more advanced users' questions about error handling in SQL Server
How to share data between stored procedures
Erland Sommarskog, SQL Server MVP.
Questions you often see in newsgroups about MS SQL Server are: How can I use the result set from one stored procedure in another or How can I use the result set from a stored procedure in a SELECT statement?
Connecting to MS SQL Server from Unix
Erland Sommarskog, SQL Server MVP
I've written this page as I keep getting questions on how to access MS SQL Server from Unix. I have never had any reason talk to SQL Server from Unix myself, but since people kept asking me how to do it, I decided to compile an web page with the tiny fragments of information and I have. The main focus is on Perl programming, but users of other langauges may find useful information too
Microsoft Accelerates Reporting Services For SQL Server
Barbara Darrow
In a change of plans, Microsoft now aims to roll out reporting services for the current SQL Server database release
SQL Injection - Part 1
Randy Dyess
It seems sometimes that every time you turn around you see a new article concerning SQL Injection. Recently when I was brushing up on my ASP to create www.Database-Security.Info, I found out why SQL Injection seems to be a reoccurring problem within ASP pages. Most of the basic examples found on the web and in books during my studies would lead any beginning ASP programmer to create pages just ripe for SQL Injection. It was this problem of overly simplified examples that lead me to create this two-part series to give web developers a chance to look at another way of lessening the threat of SQL Injection; parameterized stored procedures. Keep in mind that both of these articles are using ASP with SQL Server 2000 as the back-end, but you should be able to apply the basic concepts to any back-end platform that has the ability to parameterize its stored procedures. Also keep in mind that many of the articles advocate validating any data received from users before utilizing that data in your processes, you should still perform validation on any user input data even if you are utilizing parameterized stored procedures. This series of articles will explain the basic of using parameterized stored procedures to show you that even if you missed something during your input cleanup, you can still protect yourself by using stored procedures
MDX in Analysis Services: Optimizing MDX: Caching and Other Considerations
William Pearson
In our last tutorial, More on Location, and the Importance of Arrangement, we returned to our three-part mini-series, Optimizing MDX. We continued our focus from the first article of the series, Control Location of Processing, exploring the use of control of location as a primary intervention type for MDX query optimization. We performed a practice exercise to reinforce the concepts exposed, and then extended our considerations of additional types of intervention to include the optimization of set operations and syntax arrangement considerations. Within our exploration of the optimization of set operations, we undertook practice examples that illustrated some ways we can rearrange queries to enhance performance, often significantly
Microsoft SQL Server 2000 command line utilities (Part 1)
Alexzander Nepomnjashiy
This first article in a series of two, discusses how to use the Microsoft SQL Server 2000 command line utilities, and what are they used for
Microsoft SQL Server Survival Guide
Gregory A. Larsen
I don't know if you are like me but I like to have document and coding examples to help me manage applications and Microsoft SQL Server. I am not sure what I would do without good documentation and a few code examples to help me maintain my SQL Server environment. Microsoft has done a great job of providing both documentation and coding examples for SQL Server
Worst Practice - Triggering External Events
Steve Jones
Andy Warren started his worst practice series some time ago with the intention of looking at the worst things you can do. Given that we may not always be able to implement the best practices, at least we can try to avoid doing things harm the system or decrease performance
What is the difference between SET and SELECT when assigning values to variables, in T-SQL?
Narayana Vyas Kondreddi
Traditionally, SQL Server database developers are accustomed to using SELECT for assigning values to variables. This was fine and a perfectly valid practice right until SQL Server 6.5. Microsoft released SQL Server 7.0 in 1999. SQL Server 7.0 introduced the new SET statement for initializing and assigning values to variables. SQL Server 7.0 Books Online also stated: "It is recommended that SET @local_variable be used for variable assignment rather than SELECT @local_variable."
Saving Space To Increase Performance
Neil Boyle
It’s easy to become complacent about saving disk space when hard disk sizes keep growing and disk prices keep on dropping, but saving a few bytes here and there can help improve SQL Server performance considerably

[В начало]

ФОРУМ SQL.RU

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

Tool Вы знаете что твориться на ваших 10-30+ серверах ?
Книга по SQL 2000
Почему запрос не выдает ни одной записи? Access/SQL
Интересный (?) вопрос. Нормализация данных.
Ещёраз про AD
Failed to enumerate changes in the filtered articles
Проблема при подключении нового скл-сервера
почему не преобразовывается
влияние collation на distributed transaction?
Advanced Transact-Sql For Sql Server 2000 [Itzik Ben-Gan]
Покупаем SQL Server
Тест для мозгов и компьютеров
tree
А никто не переводил хранение данных от по датам на диапазоны дат?
Типы данных, константы и переменные в T-SQL
Увеличение скорости FETCH
Траблы с OPENDATASOURCE
Количество строк в таблице
Unknown token received from SQL Server
SQL Server 2000 для осликов [Itzik Mamaev]

[В начало]

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

MS Analysis Manager + InterBase 7
Большая просьба к Glory
Граббер
Не могу прочитать данные в таблицах MS SQL SERVER .
Сдаю экзамен. Требуется помощь зала.
Тип поля МЕМО
Delphi7+MSSQL7+SDAC. TSQL batch separator
Добавление и удалений полей в репликации???
где найти help на русском
Ограничения полнотекстового индекса
Ограничение на експорт в текстовый файл
Ктинить юзает SQL LiteSpeed
sp vizivaet DTS
sp vizivaet DTS + resenie mozet komu nado!
сорри! Проблемы с подключением к серверам!
Спецификация БД
Ау, Crimean !
SQLMail проблемы
почему проц не используется?
Howto: Insert Unicode chars in table???

[В начало]


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

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

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




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

В избранное