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

MS SQL Server

  Все выпуски  

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


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


#178<<  #179

СОДЕРЖАНИЕ

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

СОВЕТЫ

SQL Server 2000 DTS. Часть 4. Задачи в DTS Designer

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

В предыдущей статье о SQL Server 2000 Data Transformation Services мы рассмотрели первый основной компонент DTS пакета - Подключение. Теперь пришло время изучить другой критически-важный компонент - Задача (Task), которая предназначена для процессинга данных, полученных через Подключение. Задачи помечены разными значками в окне DTS Designer с названием Tasks и могут быть легко добавлены к пакету, путём простого перемещая их курсором мыши в окно пакета. Большинство из задач требуют наличия уже существующего в пакете подключения или нескольких подключений, если это необходимо.
В SQL Server 2000 DTS существует 17 предопределённых задач разной степени сложности. В этой статье мы рассмотрим 11 относительно простых задач, а описание остальных будет продолжено в следующей статье:

1. Bulk Insert task - исполняет функцию "обёртки" для T-SQL команды BULK INSERT, и её целью является быстрый импорт данных из текстового файла с разделителями полей в таблицу базы данных SQL Server. При настройке параметров этой задачи Вы можете указать разделители строки и полей или формат файла. Главный недостаток этой задачи - её слабая гибкость. В частности, во время импорта нельзя выполнять трансформацию данных (если это необходимо, Вы можете использовать Transform Data task, который мы рассмотрим позже). Кроме того, нельзя повлиять на отображение полей, т.е. порядок и тип полей в текстовом файле и в таблице должны совпадать. Передача данных может быть выполнена только из текстового файла в SQL Server. Используя закладку Options диалогового окна Bulk Insert Task Properties, которое вызывается двойным щелчком по значку задачи, Вы можете установить несколько дополнительных T-SQL параметров для BULK INSERT, например: проверка ограничений (CHECK_CONSTRAINTS), разрешение вставки значений identity (KEEPIDENTITY), число копируемых строк (FIRSTROW и LASTROW), тип файла данных (DATAFILETYPE) или размер блока (BATCHSIZE).

2. Copy SQL Server Objects task - выполняет копирование объектов между двумя базами данных, например: таблиц (включая данные), представлений, хранимых процедур, ограничений, триггеров, индексов, пользователей, ролей, логинов, первичных и внешних ключей, а так же разрешений этих объектов. Не стоит использовать эту задачу только для того, чтобы копировать данные, т.к. для этого более эффективен Transform Data task. Кроме того, если нужно копировать всю базу данных, лучше использовать Copy Database Wizard или Transfer Databases task (который мы рассмотрим позже). Не смотря на то, что исходная база данных не должна быть доступна пользователям во время операции копирования (в отличие от Copy SQL Server Objects task), эта задача хороша тем, что работает очень быстро.

3. Execute Process task - выполняет указанную Win32 - программу или пакетный файл. Для них Вы можете определить параметры запуска, время блокировки (по истечении которого процесс будет прерван) и код возврата (целочисленное значение, указывающее на успешность исполнения). Процесс выполняется в контексте безопасности учетной записи, под которой был запущен DTS пакет.

4. Execute SQL task - исполняет SQL запрос (включая хранимые процедуры). Запрос может быть разделён на пакеты, разделённые командой GO. Диалоговое окно свойств Execute SQL Task позволяет устанавливать время блокировки, по истечении которого соответствующая задача будет прервана. SQL запрос может быть проверен на правильность его синтаксиса, в нём доступны параметры ввода - вывода и глобальные переменные.

  • Глобальные переменные используются для хранения данных, которые могут быть доступны нескольким компонентам одного пакета или переданы другим пакетам. Так как глобальные переменные пакета хранятся в одном месте, и они могут динамически изменятся в течение исполнения пакета, их использование очень упрощает обслуживание и настройку пакета. Более подробно мы обсудим глобальные переменные в одной из следующих статей.
  • Входные параметры включаются в SQL запрос как вопросительные знаки, после чего их можно привязать к глобальным параметрам в последовательности появления их в запросе, как Parameter 1, Parameter 2 и т.д. Делается это на закладке Input Parameters диалогового окна Parameter Mapping (вызываемого кнопкой Parameters command в диалоговом окне Execute SQL Task Properties). Записи в разделе Parameter Mapping (расположенном на той же самой закладке) определяют, как входные параметры будут отображены на глобальные переменные. Точно так же на вкладке Output Parameters Вы можете задать отображение глобальных переменных на выходные параметры SQL запроса. Выходной параметр может состоять из одной строки или из нескольких строк (rowset), если ваш запрос возвращает множество строк.

Execute SQL task часто применяется после задач выполняющих импорт данных (например, чтобы пересоздать индексы или обновить статистику).

5. File Transfer Protocol task - помогает решать распространённые задачи в смешанных или распределённых системах, где данные должны быть переданы по File Transfer Protocol. В предыдущих версиях SQL Server, это можно было сделать с помощью программ третьих фирм (или специализированными, встраиваемыми решениями). SQL Server 2000 DTS имеет для этого собственные встроенные функциональные возможности.
File Transfer Protocol task создаёт FTP сеанс между Internet (intranet) сайтом или каталогом на сервере и локальной файловой системой. Параметры подключения (имя пользователя, пароль и количество попыток подключения) устанавливаются на закладке Location диалогового окна File Transfer Protocol Properties. На этой же закладке, можно задать путь к каталогу адресата. Как только будет проверено существование получающего данные ресурса и прав доступа к нему, можно перейти на закладку Files и указать файлы, которые необходимо передавать. Пометив чек-бокс Overwrite, Вы можете определить, могут ли файлы быть перезаписаны, если они уже существуют.

6. Send Mail task - позволяет посылать сообщения электронной почты из DTS пакета. Это обычно используется для оповещения о результатах выполнения пакета. Результаты могут быть помещены в тело письма или в прикреплённый к письму файл. До использования этой задачи, на сервер исполнения пакета должен быть настроен профиль для MAPI клиента (например, Outlook). С этим часто возникает путаница, т.к. такой профиль, возможно, должен быть создан для разных учетных записей, в зависимости от того, где пакет будет исполнятся. Это может быть ваша учетная запись, если Вы сами запускаете пакет в интерактивном режиме, но чаще это учётная запись, стартующая службу SQL Server Agent (если запуск пакета осуществляется заданием по расписанию). В последнем случае, зарегистрировавшись на компьютере где установлен SQL Server 2000 под учетной записью SQL Server Agent, нужно указать в свойствах агента соответствующий e-mail профиль.
Создать профили можно в Control Panel, дважды щелкнув по значку Mail. Параметры профиля зависят от типа почтового сервера (например, Microsoft Exchange или Lotus Notes). После создания профиля он появится в диалоговом окне Send Mail Task Properties в списке Profile name. В том же окне, Вы сможете указать получателей сообщения, тему сообщения, текст письма и дополнительные вложения.
Обратите внимание, что то же самое можно сделать в ActiveX Script task (который мы рассмотрим в следующей статье) в комбинации с методами и свойствами Collaboration Data Object model. Главное преимущество такого подхода в отсутствии необходимости иметь локальный MAPI профиль.

7. Transfer Databases task - передаёт базу данных из SQL Server 7.0/2000 на другой SQL Server 2000. Вы можете выбрать, будет ли база данных скопирована или перемещена. Для нового местоположения базы данных Вы можете указать размещение файлов данных и журналов (используя параметры на закладке File Locations диалогового окна Transfer Database Properties). Невозможно передавать таким образом системные базы данных или уже существующие на сервере назначения базы. Эта задача встроена в Copy Database Wizard, который мы уже рассмотрели в предыдущих статьях.

8. Transfer Error Messages task - выполняет специализированную задачу по копированию определяемых пользователем сообщений об ошибках между двумя SQL серверами (включая передачу ошибок из SQL Server 7.0 в SQL Server 2000). Такие сообщения сохраняются в таблицу sysmessages базы данных master и могут добавляться с помощью хранимой процедуры sp_addmessage. Вы имеете возможность копирования всех таких ошибок или только избранных. Задача умеет не копировать те сообщения, которые уже существуют в получающей ошибки базе. Эта задача тоже используется в Copy Database Wizard.

9. Transfer Jobs task - копирует Задания с серверов SQL Server 7.0/ 2000 (хранимые в нескольких таблицах базы данных msdb) на другой SQL 2000 Server. Эта задача настраивается аналогично Transfer Error Message task, описанному выше (Вы можете передавать все или избранные Задания), и так же эта задача используется в Copy Database Wizard.

10. Transfer Logins task - копирует логины SQL Server 7.0/2000 на другой SQL 2000 Server, аналогично предыдущим двум задачам. Она можете копировать все логины или относящиеся только к избранным базам данных, к которым имеющиеся логины имеют доступ. Это означает то, что если Вы выбираете несколько баз данных, то все логины сопоставленные любым ролям в этих базах данных автоматически будут добавлены в список копируемых. Как и предыдущие задачи, эта задача задействована в Copy Database Wizard.

11. Transfer Master Stored Procedures task - передаёт пользовательские хранимые процедуры из базы master SQL Server 7.0/2000 на другой SQL Server 2000. Здесь также Вы можете передавать все или только избранные процедуры. Для предотвращения конфликтов имён, эта задача не будет перезаписывать уже существующие на получающем сервере хранимые процедуры.

Помимо упомянутых выше, SQL Server 2000 DTS предлагает более сложные задачи, например: Execute Package, Dynamic Properties, ActiveX Script, Transform Data, Data Driven Query, и Message Queue. Мы рассмотрим их в следующей статье.

[В начало]

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

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

Выбор системы бюджетирования: основные требования
Intersoft Lab
OLAP: Рано или поздно настанет пора сменить имеющееся программное обеспечение (ПО) для бюджетирования. Какой должна быть новая система? Сводя десятки, а то и сотни электронных таблиц в один основной бюджет, мы рискуем сделать процесс бюджетирования и планирования чрезвычайно трудоемким и подверженным многим ошибкам: обычно эта задача выполняется раз в год и ее результаты могут устареть к тому моменту, когда бюджет будет наконец-то утвержден...
Развитие рынка ПО для бюджетирования
Intersoft Lab
OLAP: В основе современного рынка программного обеспечения (ПО) для планирования и бюджетирования лежат такие новые направления, как: стратегическое планирование методом <сверху-вниз>, мероприятия по масштабному сбору и интеграции данных, <основанные на допущениях> (assumption-driven) аналитические инструменты. В статье рассказывается об использовании передовых технологий этого рынка для принятия своевременных решений в быстро развивающихся компаниях...
Основы создания серверных элементов управления. События.
Дмитрий Руденко
ASP: В прошлой статье я попытался рассказать, как нужно рисовать собственные ASP.NET серверные элементы управления. И обещал продолжить рассказ о создании элемента управления. И хоть и прошло уже очень много времени, но обещания нужно выполнять, что я и попытаюсь сделать :). В этой статье разговор пойдет о создании событий в серверном элементе управления, генерации постбека и вызове обработчиков событий...

[В начало]

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

FIX: A Query That Uses a Large Search String in the CONTAINS Clause May Fail with Error Message 7607
How to configure an Analysis server computer to use Kerberos authentication
HOW TO: Implement a SQL Server 2000 Desktop Engine Callback Function and Example
HOW TO: Log Data Transformation Services Package Execution to a Text File
HOW TO: Manage the SQL Server Desktop Engine (MSDE 2000) by Using the Osql Utility
HOW TO: Move Databases Between Computers That Are Running SQL Server
HOW TO: Prebuild a Database in SQL Server CE
HOW TO: Resolve "The Maximum Connection Limit Has Been Reached" Error Message
HOW TO: Retrieve a Table or Rows from Database or Transaction Log Backups
HOW TO: Return Multiple Columns in a DTS Lookup Query
HOW TO: Set Up SQL Server with Proxy Server
INF: Information That PSS Needs to Troubleshoot SQL Server Replication
INF: Microsoft SQL Server MegaServers: Achieving Software Scale-Out (White Paper)
PRB: You may receive error 7619 when you run a full-text query that contains many OR operators in the search string
TechNet Support WebCast: Administering and maintaining the tempdb system database in Microsoft SQL Server
TechNet Support WebCast: An introduction to Microsoft SQL Server 2000 Reporting Services

[В начало]

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

SQL Server Statistical Functions
David Poole
When we talk about statistics what we are talking about is a means to evaluate an outcome or potential outcome against a model. The model is unlikely to provide and absolute answer but should be robust enough to give a good indicator of behaviour in the real world. The purpose of this article is to provide some thoughts on the use of statistical functions provided by SQL Server and what they actually mean
Sending Alerts Via a Custom SMTP procedure
Chris Kempster
The following article shows, through code, how to enable SQL Agent alerts and using a simple stored procedure and DLL, send emails via an SMTP server rather than using SQL Mail. We will cover these items
MDX Essentials: Basic Set Functions: The EXCEPT() Function
William Pearson
In this lesson, we will focus our attention on a function that behaves in a manner that is dramatically different from the INTERSECT() function. Instead of returning the common members of two sets, EXCEPT() returns the difference between two sets. Duplicate handling is managed through the use of a flag, as we shall see, similar to the manner we have exposed for other functions in previous articles
T-SQL Programming Part 5 - Using the CASE Function
Gregory A. Larsen
The CASE function is a very useful T-SQL function. With this function you can replace a column value with a different value based on the original column value. An example of where this function might come in handy is where you have a table that contains a column named SexCode, where 0 stands for female, 1 for male, etc., and you want to return the value "female" when the column value is 0, or "male" when the column value is 1, etc.. This article will discuss using the CASE function in a T-SQL SELECT statement
Linked Severs on MS SQL Part 4, Oracle
Don Schlichting
In previous articles, we created Linked Servers to Excel, Access and MS SQL. Several stored procedures were introduced for creating links, and the security profiles that accompany them. For this article, sp_AddLinkedServer and sp_AddLinkedSrvLogin should be familiar. Several different access methods have been introduced, primarily Open Query and Direct Access, as well as the different security configurations used to connect with them such as Windows Integrated Security and SQL security
Actual Technologies Delivers Client-Side SQL Server Driver for OS X
The Actual SQL Server ODBC Driver lets you access your company's Microsoft SQL Server database from within Microsoft Excel. You can connect to any database you are authorized to use, and work with the data just like your Windows-using co-workers
Database Wars: Microsoft vs. DB2
By Vincent Ryan
Microsoft is moving up from the space, and IBM is trying to move down from the large-scale customer base. The competition is sparking innovation, and customers in every size company will benefit. But do either of these vendors have what it takes to successfully raid the other one's stronghold?
DBAs strive for code of ethics
Robert Westervelt
Database administrators, placed charge of the integrity and security of some of the most vital information kept by large organizations, have only recently begun discussing professional ethics, according to Richard Hackathorn, president of IT consulting firm Bolder Technology, Inc.
Home-grown Data Mining in SQL Server
Drew Georgopulos
You need certain data values to complete a database-programming job, but you don't know where they're located. What can you do? Follow this 10-Minute Solution to navigate through an unfamiliar database, and locate and extract the table and column names that house your values
Use Dynamic Properties to Control Resources
Keyur Shah
Learn how to map properties to a key in the configuration file using dynamic properties. Microsoft has introduced a feature called dynamic properties in its Visual Studio .NET integrated and rapid application development environment. You can use this feature to control the location of resources (such as Web services and databases) that your application uses
Upgrading Database Improves Performance
John Zipperer
Careful planning helped ensure a manufacturing site's smooth transfer from an aging system to Windows Advanced Server and SQL Server. In some projects, time is the central factor; it is involved in the problem, the solution, and the challenge along the way. For computer hard drive manufacturer Western Digital, several months of work would go into a server switchover that could take no longer than 48 hours (see Executive Summary). That was the total amount of time the company was willing to spare in the manufacturing process. But the main reason for making the switch in the first place was that the company's existing server setup was introducing a time lag that was about five times longer than the acceptable speed. With production in its overseas plants expected to increase further, that time lag would be a real and increasing problem
Getting the Right Data with SQL Joins
Susan Sales Harkins and Patricia E. O' Connor
Associating tables in SQL is usually a breeze. But what happens when you find yourself looking at the completely wrong set of records and you don't know why? Find out how correctly applying joins can help you understand and avoid these mysterious data returns
Build Data-Driven Web Services with Updated XML Support for SQL Server 2000
Christian Thilmany
SUMMARY XML is becoming the ubiquitous data format on the Web, and XML support in SQL Server is evolving to meet the additional demand. Using XML, SOAP, HTTP, and SQL Server, you can now build powerful Web Services easily. To show just how simple it is with SQLXML 3.0, this article walks the reader through the process step by step, from setting up a virtual directory enabling data access via HTTP to executing queries and building Web Services. Finally, the author illustrates the creation of two Web Services clients—one with C# that works with the Microsoft .NET Framework and one with the SOAP Toolkit 2.0 for anyone still using earlier development tools
Building a Web-Based Analysis System
Mark Scott, John Lynn
A real-world look at using the Analysis Services Thin Web Client Browser. When working with analytical databases, analysts organize data into common groups and try to determine what would happen if things were different
Auditing Through Triggers
Robert Marda
In this article I will give code examples for a few triggers. For an excellent explanation about triggers in general and how they work in SQL Server 7.0 and SQL Server 2000 please see the following articles written by Brian Kelley: Triggers in SQL Server 7.0 and 2000 - The Common Ground and Triggers in SQL Server 7.0 and 2000 - What's New The first article will explain the special tables called inserted and deleted
SQL Server Security Part 1
Chris Kempster
Undeniably, security is a critical task for small business to enterprise computing environments but still remains a mystical science for many computer professionals. In this series of articles, I will discuss some of the finer aspects of SQL Server security and also touch on OS, physical and application security to open up this science for general discussion
Version Control in SQL Server
John Paul Cook
Database source code control is a proven technique for maintaining system stability, but it is all too often overlooked or treated as an afterthought. Although database backups provide a means of recovering database source code found in stored procedures, triggers, and user defined functions, they aren’t suitable for providing true source code control. Effective source code control is more than just having a repository for source code. Microsoft’s Visual SourceSafe (VSS) provides the version control features needed for enterprise-level code maintenance activities. To get the most out of SourceSafe, you have to know what it can do for you. Some underutilized, but quite useful, features in SourceSafe are keyword expansion and keyword comments. It’s not immediately obvious how to take advantage of these features, so this article shows you how. You will also be provided some suggestions on best practices using VSS
Thinking in Aggregates
Joe Celko
Set theory was one of the major advances in mathematics. Before Gregor Cantor invented set theory, collections of numbers were handled as sequences. A set is a completed whole with properties that belong the set, but not always to each individual element of the set. This is a big conceptual leap
SQL Server 2000 size maintenance
Baya Pavliashvili
Database size maintenance is among the "boring" tasks that DBAs have to perform. Even though storage space is becoming cheaper each day, disk drives still have limits. If you allow your databases to grow without ever managing their size you're very likely to get in trouble. Regardless of how large your disk drives are, once your database and log files grow large enough, not managing them closely will cause your pager to go off frequently
Building a Demo Server
Steve Jones
Ahh, the demo server. If your company is selling things, you probably will get asked to setup a system that allows the sales people to demonstrate your products without affecting live or production systems. Sort of a playground where salespeople and customers can make changes, try out the system and simulate any customizations you offer for potential customers or clients
SQL Server 2000 Replication 101: Terminology, Types, and Configuration
Ron Talmage
It's wise to make sure you have a clear understanding of replication terminology, types of replication, and exactly what is occurring when you install and configure replication. Replication figures as one of the more prominent features of SQL Server 2000. Replication is a complex application that uses a combination of stored procedures and executables to distribute and copy data between SQL Server databases. If you take care not to get lost in the details and confused by occasionally misleading terms, replication can be an important component in the database architecture of a SQL Server application. In this article, you'll learn about the terminology surrounding replication, the types of replication available in SQL Server, and how to configure (that is, install) replication
Debugging MSDTC Issues
Chris Kempster
Recently we experienced a range of MSDTC errors on upgrading to Windows 2003, running separate web and database servers. The DTC would run fine to Windows 2000 servers and locally (to itself), but no between Win2003 servers. The following items summarize the checks made to finally resolve our issues
Who Needs Change Management?
Greg Robidoux
You’ve spent thousands of dollars on that cool technology; clustering, redundant controllers, redundant disks, redundant power supplies, redundant NIC cards, multiple network drops, fancy tape backup devices and the latest and greatest tape technology. You’re all set. There’s no way your going to have downtime
Troubleshooting OLAP Problems
Alexander Chigrik
Should you have problems with Analysis Services, review this troubleshooting checklist to find potential solutions
Getting Ready to Replicate
Andy Warren
In October I wrote Snapshot Replication to discuss why snapshots are an option worth considering even though they are a brute force solution compared to transactional or merge replication. From what I've seen replication tends to be under used and viewed as 'magic'. My hope is that by looking at what goes on behind the scenes we can dispel the appearance of magic and once you see how and why it works, the chances of using it to solve problems increases. Replication (or at least the replication built into SQL) isn't the right answer for problems, sometimes DTS or a custom replication scheme will make sense
Worst Practices - Making On-The-Fly Changes
Steve Jones
This is another of those "everyone has done it" items that is a worst practice. It is a practice that is also extremely difficult to break people of once they have had some success with it. However, sooner or later, this practice will come back to haunt you, usually once you have started to work with a large scale or mission critical project
Is it time to say goodbye to SQL?
Phil Howard, Bloor Research
Although it may seem a no-brainer today, SQL took some time to get established with by no means all vendors subscribing to the notion of a common database query language as a useful thing. That, remember, is what SQL was originally designed to do - provide set-based query processing - the fact that it was soon appreciated that it could be used for other purposes, such as writing stored procedures, was a bonus
Forensic Log Parsing with Microsoft's LogParser
Mark Burnett
Investigating a web-based intrusion can be a daunting task, especially when you have no information other than knowing it was web-based. It is easy to waste precious time digging through megabytes, perhaps even gigabytes, of log files trying to locate suspicious activity. Often this search turns up little useful evidence

[В начало]

ФОРУМ SQL.RU

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

Tool Вы знаете что твориться на ваших 10-30+ серверах ?
книга "The Guru's Guide to SQL Server Stored Procedures, XML, and HTML"
Нынче понебу правильно солнце идет
Триггер
Книга по SQL 2000
Можно ли в SQL Server 2000 зашифровать поля, чтобы никто не видел значений? (номера кредитных карт)
Проблемы с OPENDATASOURCE
Является ли MSSQL объектно ориентированной СУБД
Недостатки MSSQL
Интересно, а кто как свои SQL сервера называет?
Проблемы с датой
Еще раз про OPENQUERY
SP and Exel
relationship
Что-то не понятное с базой!!!!
Primary Key с Identity
IF @@TRANCOUNT > 0 ROLLBACK TRAN
Одновременный Insert
BCP выводит только часть столбцов в файл
Как вы решаете такую задачу - найти все id, связянные со всеми id2 из списка

[В начало]

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

Программы анализатора безопасности
Сортировка в 6.5 и 7.0
Re Replication
Можно ли повязать электронную рассылку
Сдаюсь, помогите удалить.
И мне книжечку плиз!
такой вот интересный глюк был в EM...
SQL70-KB815495
Linked Server to mdb
DTS:Excel -> SQL - есть проблема с импортом РАЗНЫХ файлов
Требуется помощь
присоединение Бд
присоединение БД
Перенос БД с компа на комп
Full-Text Indexing Problem
Помогите с Log Shipping
картинка в Crystal Reports
MS DTS. Ошибка при создании CustomTask.
sysprocesses.Status=sleeping
Фильтр реплики по полю с названием [From]

[В начало]


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

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

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




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

В избранное