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

MS SQL Server

  Все выпуски  

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


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


#181<<  #182

СОДЕРЖАНИЕ

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

СОВЕТЫ

SQL Server 2000 DTS. Часть 7. Задачи DTS Designer: ActiveX Script Task

По материалам статьи Marcin Policht: SQL Server 2000 DTS Part 7 - DTS Designer Tasks: the ActiveX Script task

Если Вы прочли предыдущие статьи о технологии SQL Server DTS, Вы, вероятно, обратили внимание на частое упоминание ActiveX скриптов. Несмотря на то, что создание скриптов не очень популярно среди администраторов баз данных, их возможности стоит изучить, тем более что знакомство с ними необходимо для понимания оставшихся для нашего рассмотрения типов задач. Сегодня мы рассмотрим ActiveX Script task, который активно использует создание скриптов.
Целью ActiveX Script task является исполнение VBScript (который будет использоваться в примерах) или JScript скриптов, как части DTS пакетов (скрипты на других языках также могут использоваться, если они установлены на системе где пакет был создан и там, где он будет исполнен). Чтобы создать эту задачу, выберите опцию ActiveX Script Task в меню Task окна DTS Designer (или используйте соответствующий значок инструментальной панели Task на левой стороне окна). В диалоговом окне ActiveX Script Task Properties Вы можете выбрать язык скрипта. Этим Вы зададите набор используемых функций, соответствующий выбранному языку и отображаемый в списке Functions. Рабочая, текстовая область справой стороны предназначена для ввода кода скрипта. В начале, она содержит определение функции Main, созданное автоматически и состоящие из следующих строк:

'**********************************************************************
'  Visual Basic ActiveX Script
'************************************************************************

Function Main()
 Main = DTSTaskExecResult_Success
End Function

Это определение не вносит в скрипт никаких важных функциональных возможностей, но служит отправной точкой разработки Вашего скрипта. Вы можете для пробы внести в него любые изменения и потом вернуться к исходному состоянию, нажав на кнопку Auto Gen (повторное нажатие этой кнопки приведёт к тому, что все внесённые Вами в начальный код изменения будут утеряны и снова появится представленное выше определение). Так как скрипт может содержать несколько функции, в текстовом поле Entry нужно ввести имя функции, которая должна быть исполнена (по умолчанию - Main). В любой момент Вы можете проверить правильность синтаксиса вашего кода, нажав на кнопку Parse.
Автор предполагает, что Вы знакомы с правилами написания скриптов. Если это не так, Вы можете получить вводную информацию в виде HTML справочника (.CHM) с узла Microsoft: Windows Script.
Однако, даже если Вы имеете опыт в написании скриптов, Вам нужно будет освоить элементы DTS, которые используются в ActiveX скриптах. К счастью, такие элементы легко узнаваемы, так как они всегда начинаются с префикса "DTS" и их название обычно явно указывают на их назначение. Например, сгенерированное автоматически определение, которое было показано выше, включает элемент DTSTaskExecResult_Success. Это имя определяет константу, указывающую на успешное завершение задачи. И наоборот, DTSTaskExecResult_Failure - это константа, указывающая на не успешное завершение задачи. В рамках скрипта, Вы должны определить успешность его исполнения и сигнализировать об этом, присвоив соответствующую константу Main. Например, давайте предположим, что мы хотим убедиться в наличие файла C:\Data\SourceFile.txt. Это можно сделать с помощью следующего скрипта:

Function Main()
 sFile = "C:\Data\SourceFile.txt"
 
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 If oFSO.FileExists(sFile) Then
  MsgBox "The " & sFile & " exists"
  Main = DTSTaskExecResult_Success
       
 Else
  MsgBox "The " & sFile & " does not exists"
  Main = DTSTaskExecResult_Failure
 End If
End Function

Скрипт использует объект Scripting.FileSystemObject, который содержит методы и свойства разрешений операций для файлов и папок. Мы используем метод FileExist, который позволяет определить, существует ли указанный файл. Если он существует, мы выводим в диалоговое окне подтверждение и устанавливаем значение, возвращаемое функцией Main в DTSTaskExecResult_Success. Иначе, мы изменяем выводимое сообщение и возвращаем значение, указывающее на ошибку. Обратите внимание, что вывод окон сообщений в течение исполнения задачи является плохой практикой, так как это приведёт к появлению ошибок при выполнении пакетов по расписанию, потому что они должны выполняться автоматически. Мы используем здесь окна сообщений только в целях демонстрации нашего примера.
С помощью библиотеки Scripting.FileSystemObject Вы также можете удалить DTS журнал, что можно рассматривать в качестве альтернативы решению с ExcecuteProcess, предложенному в предыдущей статье. В упрощённом варианте, ActiveX скрипт имел бы следующий вид:

Function Main()
 sFile = "C:\Logs\dts.log"
 
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 If oFSO.FileExists(sFile) Then
  oFSO.DeleteFile sFile, TRUE
 End If
 Main = DTSTaskExecResult_Success
End Function

Метод DeleteFile объекта Scripting.FileSystemObject удаляет указанный Вами файл. Когда второй, дополнительный параметр этого метода установлен в TRUE, операция будет выполнена, даже если файлу установлен атрибут read-only. Теперь давайте посмотрим, как можно сделать этот скрипт более гибким, включив в него глобальные переменные.
Важно понимать, что для эффективного использования в DTS скриптов нужно быть хорошо знакомым с DTS Object model. Эта модель описывает совокупность объектов (присущие им свойства и методы), используемых для представления различных элементов DTS. В рамках этой модели существует объект Package (точнее Package2, который является следующей версией объекта Package SQL 7.0 для SQL 2000), и который содержит подобъекты: подключения, задачи (есть отдельные объекты для различных типов задач), шаги или глобальные переменные. Список возможных объектов опубликован на сайте MSDN: Creating DTS Packages with the DTS Object Model.
В начале этот список может показаться сложным для понимания, но всё станет более ясным после анализа нескольких типовых скриптов. Вы также должны иметь в виду, что при ссылке на объекты, перечисленные в списке ActiveX скриптов, необходимо добавлять префикс "DTS" (например, для представленного в списке объекта GlobalVariables нужно будет использовать DTSGlobalVariables).
DTSGlobalVariables определяет совокупность всех глобальных переменных пакета. Вы можете обращаться к ним непосредственно из ActiveX скрипта. Например, значение глобальной переменной с именем gVarLogFile может быть получено в скрипте с помощью DTSGlobalVariables("gVarLogFile").Value. Также, Вы можете создать в скрипте новую глобальную переменную, выполнив команду следующего формата (имя переменной и её значение взяты в примере произвольно):

Set DTSGlobalVariables("gVarJustCreated").Value = "Hello World"

Давайте попробуем реализовать первый подход в нашем тестовом скрипте. Мы вручную создадим в пакете глобальную переменную по имени gVarLogFile. Как Вы уже знаете, это можно сделать на закладке Global Variables диалогового окна Properties пакета. Назовём её gVarLogFile и назначим ей значение C:\Logs\dts.log. Далее, изменим код ActiveX задачи на следующий:

Function Main()
 sFile = DTSGlobalVariables("gVarLogFile").Value

 Set oFSO = CreateObject("Scripting.FileSystemObject")
 If oFSO.FileExists(sFile) Then
  oFSO.DeleteFile sFile, TRUE
 End If
 Main = DTSTaskExecResult_Success
End Function

Сохраните пакет с новым именем (например, ActiveX Test) и выполните его. Как и прежде, признаком успешного завершения работы пакета должно быть удаление предварительно созданного файла C:\Logs\dts.log.
Как Вы видите, здесь мы затронули только функциональные возможности по созданию ActiveX скриптов. Возможности задач на основе ActiveX (DTS пакетов на базе скриптов или программирования вообще) практически не ограничены, так как они обеспечивают доступ не только к компонентам DTS (через DTS object model) но также и к другим объектным моделям (например, ADO, WSH, CDO и т.д.). Эти возможности будут использоваться в следующих статьях этой серии.
При работе с задачами ActiveX Script Вы должны иметь в виду два важных момента:

  • Скрипты оперируют на той же системе, где исполняется содержащий их пакет. Этот факт может негативно повлиять на время исполнения пакета, если пакет будет запущен из Enterprise Manager на рабочей станции, а не непосредственно на сервере. Чтобы избежать этого, наметьте исполнение пакета как задание по расписанию в SQL Server Agent или запускайте их непосредственно с консоли SQL Server.
  • Избегите использовать ActiveX Script задач для построчно обработки данных, особенно при больших объёмах информации, так как такие методы имеют тенденцию длительного исполнения и повышенной утилизации процессорных ресурсов. Вместо этого, обрабатывайте такие данные непосредственно на SQL Server (до или после того, как пакет будет исполнен, в зависимости от источника и получателя данных).

Мы продолжим рассмотрение DTS задач в следующих статьях этой серии.

[В начало]

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

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

Использование Microsoft Visual Studio .NET
Гайдар Магдануров
Microsoft Visual Studio на сегодняшний день является одним из лучших средств разработки приложений. С каждой новое версией эта среда приобретает все больше и больше полезных функций, но, при этом, становиться все сложнее и сложнее, тем самым отпугивая начинающих программистов. Даже многие профессионалы не используют всех возможностей, что значительно усложняет работу...
Документация XML в C#
Anson Horton
C# поддерживает создание XML Комментариев, что позволяет разработчикам быстро комментировать и документировать свой исходный код без необходимости прибегать к неудобным и по-разному отформатированным внешним файлам...
Методы построения систем хранения данных
А.К. Лобанов
Выделение средств хранения данных в отдельную подсистему в рамках Вычислительного Комплекса позволит проектировщикам сконцентрироваться на решении проблем обеспечения надежного хранения и доступа к данным в рамках одной подсистемы. Кроме того, это создает предпосылки для оформления системы хранения данных (СХД) в организационно-техническую структуру, что является основой для аутсорсинга услуг по предоставлению средств хранения данных...
Будущие возможности языка программирования C#
Prashant Sridharan
Корпорация Microsoft разрабатывает следующую основную версию языка программирования C#. В этой статье приведена информация, касающаяся четырех новых ключевых возможностей: шаблоны, итераторы, анонимные методы и неполные (partial) типы...
Гостевая книга в intranet сети
Виталий Чужа
ASP: Предположим во внутренней сети предприятия есть корпоративный сайт, разработанный с использованием связки MS SQL Server 2000 и Internet Information Services (IIS). Используемый вид аутентификации - Integrated Windows Authentication (IWA). Необходимо создать гостевую книгу сайта. Рассмотрим несколько способов ...

[В начало]

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

"Cannot connect to web service... " error message when you locate an Office Solution Accelerator for Proposals Web site
BUG:You receive an error message when you copy a large subscription database
Failover cluster resource dependencies in SQL Server
FIX: "Performance Monitor Shared Memory Setup Failed: -1" Error Message When You Start SQL Server
FIX: A Query with a LIKE Comparison Results in a Non-Optimal Query Plan When You Use a Hungarian SQL Server Collation
FIX: An access violation exception may occur when you insert a row in a table that is referenced by indexed views in SQL Server 2000
FIX: You may notice a 17803 error and an access violation when you run a query on an instance of SQL Server 7.0
FIX: You receive an error message when you use the SQL-DMO BulkCopy object to import data into a SQL Server table
Howto import reports from Microsoft Access to Reporting Services
Howto retrieve the descendants of all the members of a dimension at a specific level or a specific distance by using the Descendants function in SQL Server 2000 Analysis Services Service Pack 3
Howto troubleshoot a SQL Server 8198 error
HOWTO: Send E-Mail Without Using SQL Mail in SQL Server
HOWTO: Rebuild or Move MSDTC Used with a SQL Failover Cluster
INF: Object Ownership Chain Checking Across Databases Depends on the Login That Is Mapped to the Object Owners
INF: Order of Installation for SQL Server 7.0 Clustering Setup
INFO: Migrating from Microsoft Office XP Developer
PRB: Error Message: "Unspecified error" Occurs When SQL Server Accesses a Linked Server That Uses Microsoft OLE DB Provider for Jet 4.0

[В начало]

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

The OS: More Important Than You Know
Brian Moran
We database professionals constantly strive to get every last ounce of performance improvement out of our systems. We bend over backwards to make our systems run faster and better. But while we're worrying about tweaks, we sometimes forget about making easy changes that can dramatically improve performance. In his May 2003 editorial, "The OS Factor" (http://www.sqlmag.com/articles/index.cfm?articleid=38440), SQL Server Magazine Senior Technical Editor Michael Otey points out that DBAs often forget about the effect that the OS has on SQL Server. Remember the OS? It's that boring piece of software that our glamorous, exciting database engines run on. Have you considered whether upgrading to Windows Server 2003 might provide a significant performance bang for your buck? According to Otey, the improvement is greater than you might expect
The Database Report - January 2004
Craig S. Mullins
By the time you read this it will be January 2004 and we will be looking back on another eventful year. The database software market was particularly active with acquisitions and attempted acquisitions, new versions of DBMS products being announced and some even delivered. All of this churning and burning around us as not only the size of our databases increased – but also the amount of money we spent on database technology
Top Causes of SQL Server Downtime
Brian Moran
Several dozen readers responded to my call for feedback about the primary causes of planned and unplanned SQL Server outages in their environments. I tallied the results, and the following list presents the reasons in order of how many readers reported them as their primary cause of downtime—not in order of most serious problems. After all, your server is either available or it isn't. Users and employers don't care why they can't get to the database—they simply want the database up and running when they need it. Here's what's causing your SQL Server downtime
Solve Problems, Not Symptoms
Brian Moran
I recently ran across the following question on the Microsoft SQL Server newsgroup: "Which should give better SQL Server performance: a server with a single-processor 1.6GHz Pentium 4 processor with 1GB of RAM or a server with dual 700MHz Pentium III processors with 2GB of memory? The performance of my existing server is slow, and I'm looking to upgrade to a faster machine."
SQL Injection!
Christoffer Hedgate
I am sure most DBAs and developers have heard of SQL injection (at least I would hope so) and may quite possibly have taken adequate steps to secure themselves against it. However, I do know that there are still a lot of vulnerable sites out there, and when I lately was contacted by an old client regarding a security breach I felt that even though there exists some good resources regarding this it is important to keep describing this in texts to make sure as many as possible are reached by this. My client thought that they were protected against SQL injection because they had taken some of the more well-known steps to secure themselves, but apparently they had not done enough
Managing Jobs - Part 1
Andy Warren
Funny how things start out simple and management, then as time goes by you realize you have a lot of stuff to deal with and the original system just isn't working out! Jobs are a place where that can happen before you know it so this week I thought I'd share some ideas on ways to use and manage jobs more effectively
MSSQL Server 2000 Reporting Services: A New Paradigm for Enterprise Reporting
William Pearson
I became a beta-tester of Reporting Services early in its development, and rapidly concluded that this new MSSQL Server 2000 add-on would literally change the face of enterprise reporting, as we know it today. Not only does Reporting Services provide an integrated, end-to-end set of tools for creating, managing, and viewing / delivering reports, but it does so with a scalable engine that supports server-based hosting and processing of reports. This is enterprise reporting at its finest, with several impressive advantages over the current offerings in the enterprise business intelligence arena. Moreover, the potential savings that await the implementing organizations could rank right up there with those promised by the recent fads of outsourcing, among other "follow the leader" activities so prevalent in business today
SQL Server and Collation
Muthusamy Anantha Kumar
Collation refers to a set of rules that determine how data is sorted and compared. Character data is sorted using rules that define the correct character sequence, with options for specifying case-sensitivity, accent marks, kana character types and character width
Introductory Database Access with PHP
James Ervin
This tutorial walks you through using PHP with the various vendor extensions of SQL, including Microsoft SQL Server 2000. 9/24/2003 -- One of PHP’s strongest features as a scripting language for Web applications is its diverse database support: the “What Can PHP Do?” page lists over 20 database platforms that PHP can communicate with. The PHP-MySQL combination powers numerous high-profile Web sites worldwide. However, accessing other database platforms with PHP is occasionally frustrating, since the PHP documentation falters in less traveled areas, leaving it to the extensive user community to fill in the gaps
Snapshot Replication for the Beginner - Part 2
Andy Warren
This is a follow up to an earlier article called Snapshot Replication for the Beginner. This week we'll actually get some data pushed to a subscriber! At the end of the previous article we had completed construction of a publication containing one table, so we'll pick up from there
Initial Installation of the Production Database
Andy Jones
Your software has passed all (your only?!) testing phase(s) and it is time to install your database into production, I will outline below how I accomplish this task. This article is concerned with an evolving system i.e. you will perform an initial installation but subsequent installations may be required for such things as customer change requests (no faults – your testing was perfect! ) while retaining all data inserted since the application began use
ASP.NET State Management Using SQL Server
Eric Charran
One of the primary challenges during Internet development how best to manage state. Because the HTTP protocol is a stateless protocol, each time the user elects an option on the page that causes a POST operation (a server post or postback is a round trip between the client and the server), the page is destroyed and recreated, then sent back to the browser
Undocumented sp_MSforeachdb and sp_MSforeachtable Stored Procedures
Gregory A. Larsen
If youneed to write code that will process a given command against each Microsoft SQL Server database or all tables in a given database, you might consider using a couple of undocumented stored procedures, sp_MSforeachdb and sp_MSforeachtable. Have you been building complicated “cursor while” loops to process through a list of databases or a list of tables? If so, maybe you have been writing too much code. Using the sp_MSforeachdb and sp_MSforeachtable stored procedures (SPs), you can simplify the code you need to process through all databases and/or all tables. Don’t be deceived by the sp_MSforeachtable stored procedure name; this SP can process through other database objects than just tables. This article will discuss how to use these two undocumented stored procedures
Tuning Disk Architectures for Databases
Michael R. Ault
When I began work in the computer industry, RAID (Redundant Array of Inexpensive Disks) technology was still in its infancy and Winchester hard drive technology wasn’t available except in huge frame mounted drives of around 90 megabytes in size that weighed in at a svelte 200 to 300 pounds. Disk technology has progressed far in terms of capacity since those days, and the many controllers and optimizers bobble the imagination. Gone are the days when tuning a disk meant a simple defragmentation and placing frequently accessed files near the outer rim of the disk
DBAzine SQL Server Tip #10: Using xp_fixeddrive Extend Stored Procedure to Review Drive Space
Gregory A. Larsen
Did you ever want to be alerted when SQL Server drive space falls below a specific threshold of available free space? Maybe you wanted to be proactive regarding limited database disk space, before no disk space caused a major database problem. If so, you need to know about the undocumented xp_fixeddrive extended stored procedure
Store and Retrieve XML-based Business Objects with SQL Server and .NET
Evangelos Petroutsos
Combine SQL Server's XML support and .NET XML serialization to simplify your front-end code by moving custom objects rather than DataSets between application layers and into and out of SQL Server. Getting database data into and out of business objects has always been a problem; however, now that SQL Server 2000 supports XML, you can use interesting techniques that capitalize on .NET's object serialization capabilities to retrieve XML-formatted data from SQL Server and transform it into custom class instances
Database Design Thoughts for Packaged Applications
graz
Over the years that I've worked with databases I've worked with many packaged applications. Some were commercial applications and some were open source applications. Typically I'm trying to put data in, get data out or just figure out where the data went. So I've compiled a small list of things I wish developers would do when they build database applications (and a rant of things I wish they wouldn't do). Some are little things and some are big things. All of them will make the life of the DBA that uses your software better. And it's ALL about the DBA!
Leverage your SQL Server 2000 Skills to Learn DB2 UDB v8
Raul Chong
In the world of information technology today, we are constantly bombarded with new information -- new software products, new versions, new features. Leveraging your current knowledge is one way to keep up with this constant change. I'll show you how you can use your current knowledge of Microsoft® SQL Server 2000 to quickly gain skills in DB2 UDB for Linux, UNIX, and Windows Version 8. In this article, I use the term "SQL Server" to refer to Microsoft SQL Server 2000 and "DB2 UDB" to refer to DB2 UDB for Linux, UNIX, and Windows Version 8. The focus of the article will be mainly on the Windows platform
A Grain of Salt
Steve Jones
I heard someone mention this in a seminar recently and it immediately woke me up. A good thing since I was starting to nod off. He was talking about team and change in IT, mostly systems, but also people, culture, etc. The statistic was that 50% of all changes fail
Using Exotic Joins in SQL - Part 2
Chris Cubley
In the previous article, you saw how the BETWEEN operator could be used in joins to solve problems dealing with range-based data. In this article, I will show you how to take joins even further by using multiple criteria in joins as well as using the greater than, less than, and not equals operators in joins
Chapter 1 - Introducing the SQL Server 2000 Resource Kit
Welcome to the Microsoft® SQL Server™ 2000 Resource Kit. This resource kit is designed for people who are already users of SQL Server and who want some helpful tips, advanced techniques, and useful tools or samples to enhance their work with SQL Server 2000
Uses For Derived Tables
Robert Marda
A derived table is a select statement inside parenthesis, with an alias, used as a table in a join. A simple example is
Should you call Microsoft for support?
Steve Jones
Microsoft has great product support, especially for SQL Server. I haven't had to call them many times over the years, at least not relative to many vendors' products, but I have made a dozen or so calls and it has always been informative. I know that people complain that support should be included in the product, and that many of the problems are those that could be avoided with better documentation, but that is the nature of the software industry. Support costs the vendor money (people, training, resources, etc), and they need to charge you after some period of time

[В начало]

ФОРУМ SQL.RU

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

Ваше мнение об упражнениях SELECT на http://sql.ipps.ru
Книга по SQL 2000
Недостатки MSSQL
Разработчикам складских баз: подсчет складских остатков
Почему UPDATE блокирует всю таблицу на чтение?
Интересно, а кто как свои SQL сервера называет?
Столбцы в цикле
Вопрос к аналитикам
Интенсивная запись в базу
Чем прочитать базу MSSQL
Существует ли перевод "Books online" по MSSQL2000 ?
Эскалация блокировок - баг или фича?
Invalid column name При создании публикации
Странный GETDATE()
хп + DTS
Проблема с запросом больше 128 символов
СРОЧНО НУЖНА ПОМОЩЬ !!!!!!!
Журнал изменений
Можно ли MSDE использовать как
Как правильно бэкапить базу?

[В начало]

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

Приведенный к н.у. расход природного газа.
Репликация транзакцией , изменение collation. Как настроить репликацию без инициализации стркутуры и данных?
DTS работает, Job не работает
DTS работает, Job не работает
Бэкап странно работает в SQL 6.5
EXEC sp_attach_db @dbname
Reporting Services
FAQ: Import xls-файла ячеек с длиной больше 255
LEFT JOIN медленнее чем FULL JOIN
доступ к данным в SQL 2000 из VB
Настройка алерта
Переход 2000 SQL в новую Active Directory.Проблемы будут?(+)
Оффтоп: грамотный дизайн human interface
Too many column in the partition???
Спорные вопросы по 228
Не стартует SQL Server
insert в Linked - как ускорить?

[В начало]


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

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

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




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

В избранное