Ошибка sqlsetconnectattr для драйвера
SQL Server Error - Driver's SQLSetConnectAttr failed
- Mark as New
- Bookmark
- Subscribe
- Mute
- Email to a Friend
Hey all, need a little expert advice. I haven't used SQL Server all that much, so I'm hoping this is a simple fix. I've built a workflow that copies data from some Access DB tables and loads it into a SQL Server that is located on the same machine. I'm using the scheduler, also on the same local machine, to run this overnight, but I keep getting this error:
"Error SQLDriverConnect: [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "EOLUS" requested by the login. The login failed.[Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed."
The workflow runs fine when I do it manually. Ideas?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Email to a Friend
@danrh Based on the error message provided and the behavior you describe my guess is that you SQL Server connection string is using SSPI (Windows Authentication) and when running via scheduler the workflow isn't able to authenticate with your database server. Scheduler by default will run the workflow using the computers 'Local System' account. In most cases this account will not have access to any network resources that require windows credentials. This includes file shares and database servers. To work around this you can setup the 'Run As' credentials in the Alteryx System Settings. This will allow the scheduled job to impersonate the provided user when running the workflow instead of running it as the Local System account. As long as the Run As user credentials have access to the database this should resolve your issue. You can find information on setting up the Run As user in the following KB article.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Email to a Friend
Took a fair amount of trouble shooting, but we finally got it working. We ended up moving it to the server and running it from there with user credentials. Thanks for pointing me in the right direction!
IM006 сбой SQLSetConnectAttr драйвер [Microsoft] [Диспетчер драйверов ODBC]
Это может происходить, если выполняются все следующие условия:
С помощью API-интерфейса ODBC драйвер помощью SQLConnect создания подключения с именем источника данных (DSN).
Одно из свойств источника данных (например, вариант использования ANSI значения NULL, шаблоны и предупреждения ) по умолчанию отключено.
Пул соединений включен для дескриптора среды.
После открытия подключения с помощью помощью SQLConnect устанавливается атрибут уровня изоляции транзакции подключения.
Выполнить транзакцию базы данных.
Временное решение
Чтобы обойти эту проблему, выполните следующие действия.
Отключите параметр для подключения ODBC пула подключений.
Примечание. Отключение пула подключений может повлиять на производительность приложения.
После фиксации транзакции, не включить параметр auto commit.
Чтобы установите уровень изоляции транзакций перед открытием подключения ODBC.
Используйте соединения вместо получения подключения ODBC DSN.
Решение
Существует исправление от корпорации Майкрософт. Однако данное исправление предназначено для устранения только проблемы, описанной в этой статье. Применяйте данное исправление только в тех системах, которые имеют данную проблему.
Если исправление доступно для скачивания, имеется раздел "Пакет исправлений доступен для скачивания" в верхней части этой статьи базы знаний. Если этого раздела нет, отправьте запрос в службу технической поддержки для получения исправления.
Примечание. Если наблюдаются другие проблемы или необходимо устранить неполадки, вам может понадобиться создать отдельный запрос на обслуживание. Стандартная оплата за поддержку будет взиматься только за дополнительные вопросы и проблемы, которые не соответствуют требованиям конкретного исправления. Полный список телефонов поддержки и обслуживания клиентов корпорации Майкрософт или создать отдельный запрос на обслуживание посетите следующий веб-узел корпорации Майкрософт:
http://support.microsoft.com/contactus/?ws=supportПримечание. В форме "Пакет исправлений доступен для скачивания" отображаются языки, для которых доступно исправление. Если нужный язык не отображается, значит исправление для данного языка отсутствует. Английская версия данного исправления содержит атрибуты файла (или более поздней версии), приведенные в следующей таблице. Дата и время для этих файлов указаны в формате общего скоординированного времени (UTC). При просмотре сведений о файле, он преобразуется в локальное время. Чтобы узнать разницу между временем по Гринвичу и местным временем, следует использовать
Часовой пояс вкладка «Дата и время» панели управления.
Date Time Version Size File name
--------------------------------------------------------
13-Oct-2002 19:24 90,112 Dahotfix.exe
03-Jul-2003 04:09 2000.81.9031.51 372,736 Sqlsrv32.dll
Date Time Version Size File name
--------------------------------------------------------
31-Mar-2004 16:44 2000.85.1040.0 24,576 Odbcbcp.dll
31-Mar-2004 16:43 2000.85.1040.0 401,408 Sqlsrv32.dll
Примечание. Список всех доступных исправлений для компонентов MDAC 2.8 щелкните следующий номер статьи базы знаний Майкрософт:
Статус
Корпорация Майкрософт подтвердила, что это является проблемой в продуктах Майкрософт, перечисленных в разделе «Относится к». Эта ошибка была исправлена в Microsoft Access компонент 2.7 Пакет обновления 1 обновление данных и компоненты доступа к данным MDAC 2.8.
Дополнительные сведения
Возникает проблема, описанное в разделе «Проблема» данной статьи, только при наличии доступа к данным компонента (MDAC) 2.7 на компьютере установлен Пакет обновления 1.
Summary
SQLSetConnectAttr sets attributes that govern aspects of connections.
For more information about what the Driver Manager maps this function to when an ODBC 3*.x* application is working with an ODBC 2*.x* driver, see Mapping Replacement Functions for Backward Compatibility of Applications.
Syntax
Arguments
ConnectionHandle
[Input] Connection handle.
Attribute
[Input] Attribute to set, listed in "Comments."
ValuePtr
[Input] Pointer to the value to be associated with Attribute. Depending on the value of Attribute, ValuePtr will be an unsigned integer value or will point to a null-terminated character string. Note that the integral type of the Attribute argument may not be fixed length, see the Comments section for detail.
StringLength
[Input] If Attribute is an ODBC-defined attribute and ValuePtr points to a character string or a binary buffer, this argument should be the length of *ValuePtr. For character string data, this argument should contain the number of bytes in the string.
If Attribute is an ODBC-defined attribute and ValuePtr is an integer, StringLength is ignored.
If Attribute is a driver-defined attribute, the application indicates the nature of the attribute to the Driver Manager by setting the StringLength argument. StringLength can have the following values:
If ValuePtr is a pointer to a character string, then StringLength is the length of the string or SQL_NTS.
If ValuePtr is a pointer to a binary buffer, then the application places the result of the SQL_LEN_BINARY_ATTR(length) macro in StringLength. This places a negative value in StringLength.
If ValuePtr is a pointer to a value other than a character string or a binary string, then StringLength should have the value SQL_IS_POINTER.
If ValuePtr contains a fixed-length value, then StringLength is either SQL_IS_INTEGER or SQL_IS_UINTEGER, as appropriate.
Returns
SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, SQL_INVALID_HANDLE, or SQL_STILL_EXECUTING.
Diagnostics
When SQLSetConnectAttr returns SQL_ERROR or SQL_SUCCESS_WITH_INFO, an associated SQLSTATE value can be obtained by calling SQLGetDiagRec with a HandleType of SQL_HANDLE_DBC and a Handle of ConnectionHandle. The following table lists the SQLSTATE values commonly returned by SQLSetConnectAttr and explains each one in the context of this function; the notation "(DM)" precedes the descriptions of SQLSTATEs returned by the Driver Manager. The return code associated with each SQLSTATE value is SQL_ERROR, unless noted otherwise.
The driver can return SQL_SUCCESS_WITH_INFO to provide information about the result of setting an option.
A connection is already enlisted in a DTC.
(DM) An asynchronously executing function (not this one) was called for the ConnectionHandle and was still executing when this function was called.
(DM) SQLExecute, SQLExecDirect, or SQLMoreResults was called for one of the statement handles associated with the ConnectionHandle and returned SQL_PARAM_DATA_AVAILABLE. This function was called before data was retrieved for all streamed parameters.
(DM) SQLExecute, SQLExecDirect, SQLBulkOperations, or SQLSetPos was called for a StatementHandle associated with the ConnectionHandle and returned SQL_NEED_DATA. This function was called before data was sent for all data-at-execution parameters or columns.
When Attribute is a statement attribute, SQLSetConnectAttr can return any SQLSTATEs returned by SQLSetStmtAttr.
Comments
For general information about connection attributes, see Connection Attributes.
The currently defined attributes and the version of ODBC in which they were introduced are shown in the table later in this section; it is expected that more attributes will be defined to take advantage of different data sources. A range of attributes is reserved by ODBC; driver developers must reserve values for their own driver-specific use from Open Group.
The ability to set statement attributes at the connection level by calling SQLSetConnectAttr has been deprecated in ODBC 3*.x*. ODBC 3*.x* applications should never set statement attributes at the connection level. ODBC 3*.x* statement attributes cannot be set at the connection level, with the exception of the SQL_ATTR_METADATA_ID and SQL_ATTR_ASYNC_ENABLE attributes, which are both connection attributes and statement attributes and can be set at either the connection level or the statement level.
ODBC 3*.x* drivers need only support this functionality if they should work with ODBC 2*.x* applications that set ODBC 2*.x* statement options at the connection level. For more information, see SQLSetConnectOption Mapping in Appendix G: Driver Guidelines for Backward Compatibility.
An application can call SQLSetConnectAttr at any time between the time the connection is allocated and freed. All connection and statement attributes successfully set by the application for the connection persist until SQLFreeHandle is called on the connection. For example, if an application calls SQLSetConnectAttr before connecting to a data source, the attribute persists even if SQLSetConnectAttr fails in the driver when the application connects to the data source; if an application sets a driver-specific attribute, the attribute persists even if the application connects to a different driver on the connection.
Some connection attributes can be set only before a connection has been made; others can be set only after a connection has been made. The following table indicates those connection attributes that must be set either before or after a connection has been made. Either indicates that the attribute can be set either before or after connection.
Attribute | Set before or after connection? |
---|---|
SQL_ATTR_ACCESS_MODE | Either[1] |
SQL_ATTR_ASYNC_DBC_EVENT | Either |
SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE | Either[4] |
SQL_ATTR_ASYNC_DBC_PCALLBACK | Either |
SQL_ATTR_ASYNC_DBC_PCONTEXT | Either |
SQL_ATTR_ASYNC_ENABLE | Either[2] |
SQL_ATTR_AUTO_IPD | Either |
SQL_ATTR_AUTOCOMMIT | Either[5] |
SQL_ATTR_CONNECTION_DEAD | After |
SQL_ATTR_CONNECTION_TIMEOUT | Either |
SQL_ATTR_CURRENT_CATALOG | Either[1] |
SQL_ATTR_DBC_INFO_TOKEN | After |
SQL_ATTR_ENLIST_IN_DTC | After |
SQL_ATTR_LOGIN_TIMEOUT | Before |
SQL_ATTR_METADATA_ID | Either |
SQL_ATTR_ODBC_CURSORS | Before |
SQL_ATTR_PACKET_SIZE | Before |
SQL_ATTR_QUIET_MODE | Either |
SQL_ATTR_TRACE | Either |
SQL_ATTR_TRACEFILE | Either |
SQL_ATTR_TRANSLATE_LIB | After |
SQL_ATTR_TRANSLATE_OPTION | After |
SQL_ATTR_TXN_ISOLATION | Either[3] |
[1] SQL_ATTR_ACCESS_MODE and SQL_ATTR_CURRENT_CATALOG can be set before or after connecting, depending on the driver. However, interoperable applications set them before connecting because some drivers do not support changing these after connecting.
[2] SQL_ATTR_ASYNC_ENABLE must be set before there is an active statement.
[3] SQL_ATTR_TXN_ISOLATION can be set only if there are no open transactions on the connection. Some connection attributes support substitution of a similar value if the data source does not support the value specified in *ValuePtr. In such cases, the driver returns SQL_SUCCESS_WITH_INFO and SQLSTATE 01S02 (Option value changed). For example, if Attribute is SQL_ATTR_PACKET_SIZE and *ValuePtr exceeds the maximum packet size, the driver substitutes the maximum size. To determine the substituted value, an application calls SQLGetConnectAttr.
[4] If SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE is set before a connection is open, the Driver Manager will set the driver's attribute when the driver is loaded during a call to SQLBrowseConnect, SQLConnect, or SQLDriverConnect. Before a call to SQLBrowseConnect, SQLConnect, or SQLDriverConnect, the Driver Manager does not know which driver to connect to and does not know whether the driver supports asynchronous connection operations. Therefore, the Driver Manager always returns SQL_SUCCESS. But, in case the driver does not support asynchronous connection operations, the call to SQLBrowseConnect, SQLConnect, or SQLDriverConnect will fail.
[5] When SQL_ATTR_AUTOCOMMIT is set to FALSE, applications should call SQLEndTran(SQL_ROLLBACK) if any API returns SQL_ERROR to ensure transactional consistency.
The format of information set in the *ValuePtr buffer depends on the specified Attribute. SQLSetConnectAttr will accept attribute information in one of two different formats: a null-terminated character string or an integer value. The format of each is noted in the attribute's description. Character strings pointed to by the ValuePtr argument of SQLSetConnectAttr have a length of StringLength bytes.
The StringLength argument is ignored if the length is defined by the attribute, as is the case for all attributes introduced in ODBC 2*.x* or earlier.
SQL_ASYNC_DBC_ENABLE_ON = Enable asynchronous operation for specified connection-related functions.
SQL_ASYNC_DBC_ENABLE_OFF = (Default) Disable asynchronous operation for specified connection-related functions.
Setting SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE is always synchronous (that is, it will never return SQL_STILL_EXECUTING).
SQL_ASYNC_ENABLE_OFF = Disable connection level asynchronous execution support for statement operations (the default).
SQL_ASYNC_ENABLE_ON = Enable connection level asynchronous execution support for statement operations.
SQL_TRUE = Automatic population of the IPD after a call to SQLPrepare is supported by the driver.
SQL_FALSE = Automatic population of the IPD after a call to SQLPrepare is not supported by the driver. Servers that do not support prepared statements will not be able to populate the IPD automatically.
If SQL_TRUE is returned for the SQL_ATTR_AUTO_IPD connection attribute, the statement attribute SQL_ATTR_ENABLE_AUTO_IPD can be set to turn automatic population of the IPD on or off. If SQL_ATTR_AUTO_IPD is SQL_FALSE, SQL_ATTR_ENABLE_AUTO_IPD cannot be set to SQL_TRUE. The default value of SQL_ATTR_ENABLE_AUTO_IPD is equal to the value of SQL_ATTR_AUTO_IPD.
SQL_AUTOCOMMIT_OFF = The driver uses manual-commit mode, and the application must explicitly commit or roll back transactions with SQLEndTran.
SQL_AUTOCOMMIT_ON = The driver uses autocommit mode. Each statement is committed immediately after it is executed. This is the default. Any open transactions on the connection are committed when SQL_ATTR_AUTOCOMMIT is set to SQL_AUTOCOMMIT_ON to change from manual-commit mode to autocommit mode.
For more information, see Commit Mode. Important: Some data sources delete the access plans and close the cursors for all statements on a connection each time a statement is committed; autocommit mode can cause this to happen after each nonquery statement is executed or when the cursor is closed for a query. For more information, see the SQL_CURSOR_COMMIT_BEHAVIOR and SQL_CURSOR_ROLLBACK_BEHAVIOR information types in SQLGetInfo and Effect of Transactions on Cursors and Prepared Statements.
SQL_ATTR_DBC_INFO_TOKEN is set-only. It is not possible to use SQLGetConnectAttr or SQLGetConnectOption to retrieve this value. The Driver Manager's SQLSetConnectAttr will not accept SQL_ATTR_DBC_INFO_TOKEN, since an application should not set this attribute.
Pass a DTC OLE transaction object that specifies the transaction to export to SQL Server, or SQL_DTC_DONE to end the connection's DTC association.
If SQL_TRUE, the string argument of catalog functions are treated as identifiers. The case is not significant. For nondelimited strings, the driver removes any trailing spaces and the string is folded to uppercase. For delimited strings, the driver removes any leading or trailing spaces and takes literally whatever is between the delimiters. If one of these arguments is set to a null pointer, the function returns SQL_ERROR and SQLSTATE HY009 (Invalid use of null pointer).
If SQL_FALSE, the string arguments of catalog functions are not treated as identifiers. The case is significant. They can either contain a string search pattern or not, depending on the argument.
The default value is SQL_FALSE.
The TableType argument of SQLTables, which takes a list of values, is not affected by this attribute.
SQL_ATTR_METADATA_ID can also be set on the statement level. (It is the only connection attribute that is also a statement attribute.)
SQL_CUR_USE_IF_NEEDED = The Driver Manager uses the ODBC cursor library only if it is needed. If the driver supports the SQL_FETCH_PRIOR option in SQLFetchScroll, the Driver Manager uses the scrolling capabilities of the driver. Otherwise, it uses the ODBC cursor library.
SQL_CUR_USE_ODBC = The Driver Manager uses the ODBC cursor library.
SQL_CUR_USE_DRIVER = The Driver Manager uses the scrolling capabilities of the driver. This is the default setting.
If the specified size exceeds the maximum packet size or is smaller than the minimum packet size, the driver substitutes that value and returns SQLSTATE 01S02 (Option value changed).
If the window handle is a null pointer, the driver does not display any dialog boxes.
SQL_OPT_TRACE_OFF = Tracing off (the default)
SQL_OPT_TRACE_ON = Tracing on
When tracing is on, the Driver Manager writes each ODBC function call to the trace file. Note: When tracing is on, the Driver Manager can return SQLSTATE IM013 (Trace file error) from any function.
An application specifies a trace file with the SQL_ATTR_TRACEFILE option. If the file already exists, the Driver Manager appends to the file. Otherwise, it creates the file. If tracing is on and no trace file has been specified, the Driver Manager writes to the file SQL.LOG in the root directory.
An application can set the variable ODBCSharedTraceFlag to enable tracing dynamically. Tracing is then enabled for all ODBC applications currently running. If an application turns tracing off, it is turned off only for that application.
If the Trace keyword in the system information is set to 1 when an application calls SQLAllocHandle with a HandleType of SQL_HANDLE_ENV, tracing is enabled for all handles. It is enabled only for the application that called SQLAllocHandle.
The default value of the SQL_ATTR_TRACEFILE attribute is specified with the TraceFile keyword in the system information. For more information, see ODBC Subkey.
The valid values for ValuePtr can be determined by calling SQLGetInfo with InfoType equal to SQL_TXN_ISOLATION_OPTIONS.
[1] These functions can be called asynchronously only if the descriptor is an implementation descriptor, not an application descriptor.
Сводка
SQLSetConnectAttr задает атрибуты, управляющие аспектами соединений.
Дополнительные сведения о том, как диспетчер драйверов сопоставляет эту функцию, когда приложение ODBC 3 . x работает с драйвером ODBC 2 . x , см. в разделе Сопоставление функций замены для обратной совместимости приложений.
Синтаксис
Аргументы
коннектионхандле
[Input] Дескриптор подключения
Если атрибут Attribute является атрибутом, ОПРЕДЕЛЯЕМым ODBC, а ValuePtr — целым числом, StringLength игнорируется.
Если атрибут является атрибутом, определяемым драйвером, приложение указывает природу атрибута для диспетчера драйверов, задавая аргумент StringLength . StringLength могут иметь следующие значения:
Если ValuePtr является указателем на символьную строку, StringLength — это длина строки или SQL_NTS.
Если ValuePtr является указателем на двоичный буфер, приложение помещает результат макроса SQL_LEN_BINARY_ATTR (length) в StringLength. Это помещает отрицательное значение в StringLength.
Если ValuePtr является указателем на значение, отличное от символьной строки или двоичной строки, StringLength должно иметь значение SQL_IS_POINTER.
Если ValuePtr содержит значение фиксированной длины, то StringLength либо SQL_IS_INTEGER, либо SQL_IS_UINTEGER, соответственно.
Возвращаемое значение
SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_ERROR, SQL_INVALID_HANDLE или SQL_STILL_EXECUTING.
Диагностика
Когда SQLSetConnectAttr возвращает SQL_ERROR или SQL_SUCCESS_WITH_INFO, связанное значение SQLSTATE может быть получено путем вызова SQLGetDiagRec с параметром handletype SQL_HANDLE_DBC и маркером коннектионхандле. В следующей таблице перечислены значения SQLSTATE, обычно возвращаемые функцией SQLSetConnectAttr , и объясняется каждый из них в контексте этой функции. Нотация "(DM)" предшествует описаниям SQLSTATE, возвращаемым диспетчером драйверов. Код возврата, связанный с каждым значением SQLSTATE, имеет SQL_ERROR, если не указано иное.
Драйвер может возвращать SQL_SUCCESS_WITH_INFO, чтобы предоставить сведения о результате установки параметра.
Подключение уже прикреплено к DTC.
(DM) вызывается асинхронно исполняемая функция (не эта одна) для коннектионхандле и все еще выполнялась при вызове этой функции.
(DM) SQLExecute, SQLExecDirect или SQLMoreResults были вызваны для одного из дескрипторов инструкций, связанных с коннектионхандле и возвращаемых SQL_PARAM_DATA_AVAILABLE. Эта функция была вызвана до получения данных для всех потоковых параметров.
(DM) SQLExecute, SQLExecDirect, SQLBulkOperations или SQLSetPos были вызваны для статеменсандле , связанного с коннектионхандле , и возвращены SQL_NEED_DATA. Эта функция была вызвана перед отправкой данных для всех параметров или столбцов данных, выполняемых во время выполнения.
Если атрибут является атрибутом инструкции, SQLSetConnectAttr может возвращать любой SQLSTATE, возвращенный SQLSetStmtAttr.
Комментарии
Общие сведения об атрибутах соединения см. в разделе атрибуты соединения.
Определенные в настоящее время атрибуты и версия ODBC, в которой они были представлены, показаны в таблице далее в этом разделе. Ожидается, что для использования преимуществ различных источников данных будут определены дополнительные атрибуты. Диапазон атрибутов зарезервирован ODBC; Разработчики драйверов должны зарезервировать значения для собственного использования драйвера из Open Group.
Возможность установки атрибутов инструкций на уровне соединения путем вызова SQLSetConnectAttr является устаревшей в ODBC 3 . x. Приложения ODBC 3 . x никогда не должны задавать атрибуты инструкций на уровне соединения. Атрибуты инструкций ODBC 3 . x не могут быть установлены на уровне соединения, за исключением атрибутов SQL_ATTR_METADATA_ID и SQL_ATTR_ASYNC_ENABLE, которые являются атрибутами соединения и атрибутами инструкции и могут быть установлены на уровне соединения или инструкции.
Драйверы ODBC 3 . x должны поддерживать эту функцию только в том случае, если они должны работать с приложениями ODBC 2 . x , которые задают параметры инструкции ODBC 2 . x на уровне соединения. Дополнительные сведения см. в разделе сопоставление SQLSetConnectOption в приложении G: рекомендации по драйверу для обеспечения обратной совместимости.
Приложение может вызывать SQLSetConnectAttr в любое время между выделением и освобождением подключения. Все атрибуты соединения и инструкции, установленные приложением для соединения, сохраняются до тех пор, пока для соединения не будет вызван SQLFreeHandle . Например, если приложение вызывает SQLSetConnectAttr перед подключением к источнику данных, атрибут сохраняется даже в случае сбоя SQLSetConnectAttr в драйвере при подключении приложения к источнику данных. Если приложение устанавливает атрибут для конкретного драйвера, атрибут сохраняется даже в том случае, если приложение подключается к другому драйверу в соединении.
Некоторые атрибуты соединения можно задать только до установки соединения. другие можно задать только после установки соединения. В следующей таблице указаны атрибуты соединения, которые должны быть установлены до или после установки соединения. Либо указывает, что атрибут можно задать до или после соединения.
attribute | Задать до или после подключения? |
---|---|
SQL_ATTR_ACCESS_MODE | Либо [1] |
SQL_ATTR_ASYNC_DBC_EVENT | Можно использовать |
SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE | Либо [4] |
SQL_ATTR_ASYNC_DBC_PCALLBACK | Можно использовать |
SQL_ATTR_ASYNC_DBC_PCONTEXT | Можно использовать |
SQL_ATTR_ASYNC_ENABLE | Либо [2] |
SQL_ATTR_AUTO_IPD | Можно использовать |
SQL_ATTR_AUTOCOMMIT | Либо [5] |
SQL_ATTR_CONNECTION_DEAD | После |
SQL_ATTR_CONNECTION_TIMEOUT | Можно использовать |
SQL_ATTR_CURRENT_CATALOG | Либо [1] |
SQL_ATTR_DBC_INFO_TOKEN | После |
SQL_ATTR_ENLIST_IN_DTC | После |
SQL_ATTR_LOGIN_TIMEOUT | До |
SQL_ATTR_METADATA_ID | Можно использовать |
SQL_ATTR_ODBC_CURSORS | До |
SQL_ATTR_PACKET_SIZE | До |
SQL_ATTR_QUIET_MODE | Можно использовать |
SQL_ATTR_TRACE | Можно использовать |
SQL_ATTR_TRACEFILE | Можно использовать |
SQL_ATTR_TRANSLATE_LIB | После |
SQL_ATTR_TRANSLATE_OPTION | После |
SQL_ATTR_TXN_ISOLATION | Либо [3] |
[1] SQL_ATTR_ACCESS_MODE и SQL_ATTR_CURRENT_CATALOG можно задать до или после подключения, в зависимости от драйвера. Однако взаимодействующие приложения устанавливают их перед подключением, так как некоторые драйверы не поддерживают их изменение после подключения.
[2] SQL_ATTR_ASYNC_ENABLE необходимо задать перед выполнением активного оператора.
[3] SQL_ATTR_TXN_ISOLATION можно задать только в том случае, если в соединении нет открытых транзакций. Некоторые атрибуты соединения поддерживают подстановку аналогичного значения, если источник данных не поддерживает значение, указанное в * ValuePtr. В таких случаях драйвер возвращает SQL_SUCCESS_WITH_INFO и SQLSTATE 01S02 (значение параметра изменено). Например, если атрибут имеет значение SQL_ATTR_PACKET_SIZE и * ValuePtr превышает максимальный размер пакета, драйвер подставляет максимальный размер. Чтобы определить заменяющее значение, приложение вызывает SQLGetConnectAttr.
[4] Если SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE задан до открытия соединения, диспетчер драйверов установит атрибут драйвера при загрузке драйвера во время вызова SQLBrowseConnect, SQLConnect или SQLDriverConnect. Перед вызовом SQLBrowseConnect, SQLConnect или SQLDriverConnect диспетчер драйверов не знает, к какому драйверу подключаться, и не знает, поддерживает ли драйвер асинхронные операции подключения. Таким образом, диспетчер драйверов всегда возвращает SQL_SUCCESS. Но если драйвер не поддерживает асинхронные операции подключения, вызов SQLBrowseConnect, SQLConnect или SQLDriverConnect завершится ошибкой.
[5] Если SQL_ATTR_AUTOCOMMIT имеет значение FALSE, приложения должны вызывать SQLEndTran (SQL_ROLLBACK), если любой API возвращает SQL_ERROR для обеспечения согласованности транзакций.
Формат набора данных в * буфере ValuePtr зависит от указанного атрибута. SQLSetConnectAttr будет принимать сведения об атрибутах в одном из двух разных форматов: строку символов, завершающуюся нулем, или целочисленное значение. Формат каждого из них отмечен в описании атрибута. Символьные строки, на которые указывает аргумент ValuePtr параметра SQLSetConnectAttr , имеют длину StringLength байтов.
Аргумент StringLength игнорируется, если длина определяется атрибутом, как и в случае всех атрибутов, введенных в ODBC 2 . x или более ранней версии.
SQL_ASYNC_DBC_ENABLE_ON = включить асинхронную операцию для указанных функций, связанных с соединением.
SQL_ASYNC_DBC_ENABLE_OFF = (по умолчанию) отключить асинхронную операцию для указанных функций, связанных с соединением.
Параметр SQL_ATTR_ASYNC_DBC_FUNCTIONS_ENABLE всегда является синхронным (то есть он никогда не будет возвращать SQL_STILL_EXECUTING).
SQL_ASYNC_ENABLE_OFF = отключить поддержку асинхронного выполнения на уровне соединения для операций с инструкциями (по умолчанию).
SQL_ASYNC_ENABLE_ON = включить поддержку асинхронного выполнения на уровне соединения для операций с инструкциями.
SQL_TRUE = автоматическое заполнение IPD после вызова SQLPrepare поддерживается драйвером.
SQL_FALSE = автоматическое заполнение IPD после вызова SQLPrepare не поддерживается драйвером. Серверы, не поддерживающие подготовленные инструкции, не смогут автоматически заполнять IPD.
Если для атрибута соединения SQL_ATTR_AUTO_IPD возвращается SQL_TRUE, атрибут инструкции SQL_ATTR_ENABLE_AUTO_IPD можно задать, чтобы включить или отключить автоматическое заполнение IPD. Если SQL_ATTR_AUTO_IPD имеет SQL_FALSE, SQL_ATTR_ENABLE_AUTO_IPD нельзя установить в SQL_TRUE. Значение по умолчанию SQL_ATTR_ENABLE_AUTO_IPD равно значению SQL_ATTR_AUTO_IPD.
SQL_AUTOCOMMIT_OFF = драйвер использует режим фиксации вручную, и приложение должно явно зафиксировать или откатить транзакции с помощью SQLEndTran.
SQL_AUTOCOMMIT_ON = драйвер использует режим автоматической фиксации. Каждый оператор фиксируется сразу же после выполнения. Это значение по умолчанию. Все открытые транзакции в соединении фиксируются, когда SQL_ATTR_AUTOCOMMIT имеет значение SQL_AUTOCOMMIT_ON, чтобы переходить от режима ручной фиксации к режиму автоматической фиксации.
Дополнительные сведения см. в разделе режим фиксации. Важно. Некоторые источники данных удаляют планы доступа и закрывают курсоры для всех инструкций в соединении каждый раз при фиксации инструкции; режим автоматической фиксации может привести к тому, что это произойдет после выполнения каждой незапросной инструкции или закрытия курсора для запроса. Дополнительные сведения см. в статьях типы сведений SQL_CURSOR_COMMIT_BEHAVIOR и SQL_CURSOR_ROLLBACK_BEHAVIOR в SQLGetInfo и воздействие транзакций на курсоры и подготовленные инструкции.
SQL_ATTR_DBC_INFO_TOKEN только задано. Невозможно использовать SQLGetConnectAttr или SQLGetConnectOption для получения этого значения. SQLSetConnectAttr диспетчера драйверов не будет принимать SQL_ATTR_DBC_INFO_TOKEN, так как приложение не должно устанавливать этот атрибут.
передайте объект транзакции DTC OLE, указывающий транзакцию для экспорта в SQL Server, или SQL_DTC_DONE для завершения связи DTC подключения.
Если SQL_TRUE, строковый аргумент функций каталога рассматривается как идентификаторы. Регистр не имеет значения. Для строк без разделителей драйвер удаляет все конечные пробелы, а строка выводится в верхний регистр. Для строк с разделителями драйвер удаляет все начальные или конечные пробелы и принимает буквальное значение между разделителями. Если для одного из этих аргументов задан пустой указатель, функция возвращает SQL_ERROR и SQLSTATE HY009 (недопустимое использование пустого указателя).
Если SQL_FALSE, строковые аргументы функций каталога не рассматриваются как идентификаторы. Регистр важен. Они могут содержать шаблон поиска строки или нет, в зависимости от аргумента.
Значение по умолчанию — SQL_FALSE.
Аргумент TableType объекта SQLTables, который принимает список значений, не затрагивается этим атрибутом.
SQL_ATTR_METADATA_ID также можно задать на уровне инструкции. (Это единственный атрибут соединения, который также является атрибутом инструкции.)
SQL_CUR_USE_IF_NEEDED = диспетчер драйверов использует библиотеку курсоров ODBC, только если это необходимо. Если драйвер поддерживает параметр SQL_FETCH_PRIOR в SQLFetchScroll, диспетчер драйверов использует возможности прокрутки драйвера. В противном случае используется библиотека курсоров ODBC.
SQL_CUR_USE_ODBC = диспетчер драйверов использует библиотеку курсоров ODBC.
SQL_CUR_USE_DRIVER = диспетчер драйверов использует возможности прокрутки драйвера. Это параметр по умолчанию.
Если указанный размер превышает максимальный размер пакета или меньше, чем минимальный размер пакета, драйвер подставляет это значение и возвращает значение SQLSTATE 01S02 (изменение значения параметра).
Если указатель окна является пустым указателем, драйвер не отображает никаких диалоговых окон.
SQL_OPT_TRACE_OFF = трассировка отключена (по умолчанию)
SQL_OPT_TRACE_ON = трассировка вкл.
Когда трассировка включена, диспетчер драйверов записывает каждый вызов функции ODBC в файл трассировки. Примечание. Когда трассировка включена, диспетчер драйверов может возвращать значение SQLSTATE IM013 (ошибка файла трассировки) из любой функции.
Приложение задает файл трассировки с параметром SQL_ATTR_TRACEFILE. Если файл уже существует, диспетчер драйверов добавляет его к файлу. В противном случае он создает файл. Если трассировка включена и файл трассировки не указан, диспетчер драйверов записывает данные в файл SQL. Войдите в корневой каталог.
Приложение может установить переменную одбкшаредтрацефлаг , чтобы включить трассировку динамически. Затем трассировка включается для всех приложений ODBC, работающих в данный момент. Если приложение отключает трассировку, оно отключено только для этого приложения.
Если ключевое слово Trace в сведениях о системе имеет значение 1, когда приложение вызывает функцию sqlallochandle с параметром handletype SQL_HANDLE_ENV, трассировка включается для всех дескрипторов. Он включен только для приложения, которое вызвало функцию SQLAllocHandle.
Значение по умолчанию атрибута SQL_ATTR_TRACEFILE указывается с помощью ключевого слова TRACEFILE в сведениях о системе. Дополнительные сведения см. в разделе подраздела ODBC.
Допустимые значения для ValuePtr можно определить с помощью вызова SQLGetInfo с инфотипе , равным SQL_TXN_ISOLATION_OPTIONS.
[1] эти функции можно вызывать асинхронно, только если дескриптор является дескриптором реализации, а не дескриптором приложения.
I have some DTS packages that ALL fail when scheduled as jobs. I KNOW for a fact that it is not a permissions issue like the majority of DTS Job Failures out there. The specific DTS Jobs that are failing all have one thing in common: they all access different Oracle sources.
I made sure that the Oracle client tools are installed ont he SQL Server 2000 already and also the ODBC connections are there, but I am still receiving the following error:
Error = -2147467259 (80004005)
Error string: [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed
Error source: Microsoft OLE DB Provider for ODBC Drivers
Error Detail Records:
Error: -2147467259 (80004005); Provider Error: 0 (0)
Error string: [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed
Error source: Microsoft OLE DB Provider for ODBC Drivers
Error: -2147467259 (80004005); Provider Error: 12154 (2F7A)
Error string: [Microsoft][ODBC driver for Oracle][Oracle]ORA-12154: TNS:cou. Process Exit Code 1. The step failed.
I am seeking assistance here because I have tried and searched all over the place for the solution (MS Site, Tek-Tips, and other forums), but no luck. Can anyone please tell me what is occurring here? It seems to be that the ODBC connections are not set on that machine, correct? Or is it something else? Just to make sure, I reconfigured those ODBC connections and the machine and then tried the Jobs again but they failed! Should I have restarted SQL Server after these simple ODBC changes?
I would greatly appreciate any help.
March 4, 2004 at 3:11 pm
First, I don't know the answer specifically.
Some ruminations. SQL Server has the ability to communicate (send/receive data) via serveral communications links. I.e. TCP/Ip, Named pipes, etc.
For a given server, you define what communications links that SQL server is going to support. Normally communication links not needed are not supported.
A client is in some ways similiar. Meaning you define on a client what communication links are going to be supported to SQL Server.
Is it possible that there is a mis-match on what communication link is being supported between the client and server?
March 4, 2004 at 3:18 pm
How did you tested the ODBC DSN ?
March 4, 2004 at 3:19 pm
I don't think this is the problem since the client (my workstation) has the same Oracle Client Tools and ODBCs (communication links) as the server does. Is this what you mean by 'communication links'? My links are the ODBCs I have set.
March 4, 2004 at 3:24 pm
Try doing a link server to the oracle server, see if you can get there from there. Could be a RPC issue
March 4, 2004 at 3:24 pm
Excuse my ignorance, but how I can test the ODBC DSNs I have set for Oracle to make sure they do indeed work from the server?
March 4, 2004 at 3:28 pm
1. Make sure they are set up as System DSN not User DSN
2. Create a linked server as expressed above by John Zacharkan
3. see if you can connect
March 5, 2004 at 2:44 pm
I am getting the same error message
(Error string: Error Code: 0 Error Source= Microsoft OLE DB Provider for Oracle Error Description: Error while trying to retrieve text for error ORA-12154 Help context: 4500 Error: -2147467259 (80004005);Provider Error: 12154 (2F7A)).
The DTS packages will run when executed from the design window. But not when run as a job. I have defined SYSTEM Data Sources Not User Data Sources.
March 5, 2004 at 2:54 pm
The data sources need to be set up on the server when run as a job. When running from the designer, the job processes on the local machine (where the designer is running).
March 5, 2004 at 4:09 pm
Thanks to everyone that has participated in this discussion in trying to solve my problem. I am a bit astonished as to the lack of documentation on setting linked servers via SQL Server to Oracle sources. I have perused numerous URLs and forums since early yesterday morning, and still can't seem to find a proper solution. I also have 3 MS Press books and one other one on SQL Server and all of these skim the subject of linked servers!
This is what I do know and have done (hopefully it'll help you experts out more in assisting me):
1. On my client PC's EM, I can successfully run DTS jobs that query both of my Oracle sources with no problems.
2. On my PC, with MS Access, I can successfully link to those Oracle sources via ODBC after I installed Oracle Client Tools. This is utilizing the driver Oracle73 , version 2.05.03.01, company Oracle Corporation and file SQL32_73.DLL.
3. Once the jobs are scheduled, the jobs fail on the SQL Server because what is listed below (I believe):
4. I recently installed the same Oracle Client Tools and ODBCs onto the SQL Server, but haven't rebooted yet (will do this tonight). Is rebooting necessary for SQL Server to recognize the new Oracle installations? None of my references say to do this, but I read in one place on the web, thus I will try this.
5. On the server's EM, I picked the Linked Servers node and chose New Linked Server with the following settings:
a. Linked Server: DATA1.ORACLE
b. Provider name: Oracle Provider for OLE DB (is this correct??)
c. Product name: Oracle 7.3
d. Data source: I picked the same name that was located in the TNS.ORA file by the SID attribute, e.g. DATA123
e. Provider string: . don't know what exactly goes here; I have seen tons of examples, but don't know how to access this data; I have also heard of aliases for this attribute and don't know exactly what to do?
I have tried different combinations of attributes but nothing seems to work. I believe it is the Provider Name I am picking. Will rebooting the system have Oracle73 in the drop-down? How about the Provider String?
I would like to thank everyone who has taken the time to look at this thread and their attempt at assisting me. I greatly appreciate everyone's help.
Читайте также: