Monday, 16 October 2017

01000 Binary Options


Testimonios de robot de opción binaria. 01000. (856) 21 215877. (856) 21 219857. mailmpt. gov. la. Las mejores opciones binarias de las opciones corredores Gobierno corporativo es el Vertreten durch den Vorstand: Dieter Zetsche (Vorsitzender), Wolfgang Bernhard, Renata Jungo Br252ngger, Ola K228llenius, Wilfried Porth, Hubertus Troska, Bodo Uebber 8230 Gobierno corporativo bezeichnet den rechtlichen und faktischen Ordnungsrahmen f252r die Leitung Und 220berwachung eines Unternehmens. Dazu geh246rt die 8230 Verterten durch den Vorstand: Dieter Zetsche (Vorsitzender), Wolfgang Bernhard, Renata Jungo Binary To Ones Calculadora de Complementos Bin228re Optionen Keine Kaution Opciones Binarias No 8230 One Click Trading, MT4 8230 Guller Lahr Agosto 2008. forex deposit calculator 183 forex al Alcance de todos 8230 8230 forex ea generador Opciones trading calculadora excel naveen opciones binarias 8230 cómo los sitios seguros corredor lo hacen con un especialista de una especialidad opciones binarias 8230 Related Posts HomeApplied Optics Nueva familia de matrices binarias para la imagen de apertura codificada Resumen Introduzco una nueva familia De conjuntos binarios para uso en la formación de imágenes de apertura codificada que se prevé que tienen propiedades y sensibilidad (SNR) igual a la de la red uniformemente redundante (URA). Las nuevas matrices, denominadas MRAs (URA modificadas), tienen coeficientes de decodificación que son todos unimodulares, dando como resultado una imagen reconstruida con términos de ruido completamente independientes de la estructura de la fuente de imágenes. Aunque los nuevos arrays se derivan de residuos cuadráticos, no pertenecen al conjunto de diferencias cíclicas o conjunto de secuencias pseudonoise y, por consiguiente, son constructibles en configuraciones prohibidas a dichos diseños, proporcionando así al usuario una selección más amplia de patrones de apertura para que se adapten a su particular necesariamente. Con la adición de MURA a la familia de matrices binarias, todos los números primos ahora se pueden utilizar para hacer aperturas óptimas codificadas, aumentando el número de patrones cuadrados disponibles por más de un factor de 3. Copia 1989 Optical Society of America Referencias Usted no Tienen acceso de suscripción a esta revista. Las listas de citas con enlaces de citas salientes están disponibles solo para los suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Citado por Usted no tiene acceso de suscripción a esta revista. Los enlaces citados sólo están disponibles para suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Figuras (5) No tiene acceso de suscripción a esta revista. Los archivos de figuras sólo están disponibles para suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Tablas (3) No tiene acceso de suscripción a esta revista. Las tablas de artículos sólo están disponibles para suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Ecuaciones (36) No tiene acceso de suscripción a esta revista. Las ecuaciones sólo están disponibles para los suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Métricas No tiene acceso de suscripción a esta revista. Las métricas de nivel de artículo están disponibles únicamente para los suscriptores. Puede suscribirse como miembro de la OSA o como usuario autorizado de su institución. Introducción Una Interfaz de Programación de Aplicación (API) es una definición del conjunto de funciones que una aplicación puede usar para acceder a un recurso del sistema. Utilización de ODBC con Microsoft SQL Server. ODBC es una API de base de datos basada en la API de CLI (Interfaz de Llamada), la cual es publicada por las organizaciones de estándares X / Open e ISO / CAE. Las aplicaciones ODBC pueden acceder a datos en muchos de los sistemas de gestión de bases de datos (DBMS) más importantes de hoy mediante el uso de controladores ODBC escritos para acceder a dichos DBMS. La aplicación llama a las funciones de la API de ODBC utilizando una sintaxis estándar de SQL de ODBC, el controlador ODBC realiza las traducciones necesarias para enviar la sentencia al DBMS y presenta los resultados de nuevo a la aplicación. En este artículo se describe cómo los programadores de aplicaciones que utilizan la API de ODBC pueden optimizar el acceso a Microsoft SQL Server al utilizar el controlador ODBC de Microsoft SQL Server. El documento también analiza los problemas comúnmente planteados por los clientes que han llamado a soporte técnico de Microsoft para obtener ayuda con el controlador ODBC de SQL Server. Este documento no es un tutorial sobre la programación ODBC en general, ni es una discusión exhaustiva sobre el ajuste de rendimiento en SQL Server. Asume que el lector ya está familiarizado con la programación ODBC y el uso de SQL Server. Para obtener más información acerca de ODBC, vea Microsoft ODBC 2.0 programadores de referencia y SDK Guía disponible en MSDN y de Microsoft Press y ODBC interior de Kyle Geiger, también disponible en Microsoft Press. Para obtener más información acerca de SQL Server, consulte la documentación de SQL Server. Excepto donde se indica, los usuarios deben asumir que este documento está discutiendo el funcionamiento de Microsoft SQL Server versión 6.5 y su versión asociada 2.65 controlador ODBC. Este artículo utiliza las funciones de la versión 2.5 de ODBC versión porque la versión 2.5 es la versión utilizada por la mayoría de las aplicaciones existentes y también es la versión del ODBC SDK que se incluye con Microsoft SQL Server Workstation versión 6.5. Los programadores que escriben aplicaciones ODBC 3.0 deben referirse al Microsoft ODBC 3.0 Software Development Kit y Programmers Reference. Los lectores principalmente interesados ​​en problemas relacionados con el rendimiento encontrarán la mayor parte de la información útil en las secciones siguientes de este documento: General Buenas Prácticas Selección de una opción de cursor SQLExecDirect vs. SQLPrepare / SQLExecute Llamadas de procedimiento por lotes Arquitectura de datos de texto e imagen El controlador ODBC de Microsoft SQL Server Utiliza los componentes estándar de SQL Server para comunicarse desde una aplicación cliente al servidor de base de datos. En lugar de implementarse como una nueva capa sobre los servidores SQL anteriores API nativa, DB-Library, el controlador ODBC escribe directamente en la misma capa de biblioteca de red (biblioteca de red) utilizada por DB-Library. El controlador ODBC se implementa como una API nativa a SQL Server y es un reemplazo funcional de la DLL de DB-Library. Los componentes implicados en el acceso a SQL Server desde una aplicación ODBC se describen en las siguientes secciones. Aplicación La aplicación realiza llamadas a la API de ODBC utilizando sentencias de SQL escritas en la sintaxis de ODBC SQL o en la sintaxis de SQL Server Transact-SQL. Administrador de controladores ODBC El gestor de controladores ODBC es una capa muy delgada que gestiona las comunicaciones entre la aplicación y los controladores ODBC con los que funciona la aplicación. El gestor de controladores carga principalmente los módulos que componen el controlador y luego pasa todas las solicitudes ODBC al controlador. Hay versiones de interfaz de programación de aplicaciones Win32 y Win16 del administrador de controladores. El gestor de controladores Win32 es Odbc32.dll el gestor de controladores Win16 es Odbc. dll. Controlador de ODBC de SQL Server El controlador ODBC de SQL Server es un DLL único que responde a todas las llamadas que hace la aplicación a la API de ODBC. Si las sentencias SQL de la aplicación contienen una sintaxis de SQL ANSI o ODBC que no es compatible con SQL Server, el controlador traduce las sentencias en sintaxis de Transact-SQL (la cantidad de traducción es generalmente mínima) y luego pasa la sentencia al servidor. El controlador también presenta todos los resultados de nuevo a la aplicación. El controlador de ODBC de SQL Server de Win32 es Sqlsrv32.dll el controlador de Win16 es Sqlsrvr. dll. Biblioteca de red de cliente de SQL Server El controlador se comunica con el servidor a través de las bibliotecas de red de SQL Server utilizando el protocolo de nivel de aplicación de SQL Server denominado TDS (Tabular Data Stream). El protocolo TDS de SQL Server es un protocolo half-duplex con conjuntos de resultados autónomos (que contienen tanto metadatos como datos) optimizados para el acceso a la base de datos. Hay una biblioteca de red diferente para cada protocolo compatible con SQL Server. El trabajo de la biblioteca de red es procesar paquetes TDS desde el controlador mientras aislan al controlador de detalles de la pila de protocolo subyacente. Una biblioteca de red de SQL Server accede a un protocolo de red llamando a una API de red admitida por la pila de protocolos. Las bibliotecas de red proporcionadas por SQL Server para su uso por las aplicaciones de cliente de SQL Server se enumeran en la tabla siguiente. Pila de protocolos de red La pila de protocolos de red transporta los paquetes TDS entre el cliente y el servidor. La pila de protocolos tiene componentes tanto en el cliente como en el servidor. Server Net-Library El servidor Net-Libraries trabaja en el servidor, pasando los paquetes TDS de un lado a otro entre SQL Server y sus clientes. Cada SQL Server puede funcionar simultáneamente con cualquiera de las bibliotecas de red del servidor instaladas en el servidor. Open Data Services Open Data Services admite una API definida para escribir aplicaciones de servidor. Una aplicación de Open Data Services puede ser un servidor que acepta conexiones y procesa consultas (como SQL Server o una puerta de enlace a otro DBMS) o puede ser un procedimiento almacenado extendido que permite ejecutar DLL escritas en la API de Open Data Services Como procedimientos almacenados en SQL Server. Open Data Services recibe los paquetes TDS de las Bibliotecas de red subyacentes y, a continuación, pasa la información a SQL Server llamando a funciones de devolución de llamada de Open Data Services específicas implementadas en el código de SQL Server. También encapsula los resultados que vuelven del servidor en paquetes TDS que la biblioteca de red envía de vuelta al cliente. SQL Server SQL Server es el motor de servidor que procesa todas las consultas de clientes de SQL Server. Arquitectura general de ODBC y SQL Server La siguiente ilustración muestra la arquitectura general de ODBC y SQL Server. Muestra un cliente Win16 que utiliza TCP / IP y un cliente Win32 que utiliza Novell que se conecta al mismo servidor. Rendimiento de ODBC como una API nativa Uno de los rumores persistentes sobre ODBC es que es inherentemente más lento que una API de DBMS nativa. Este razonamiento se basa en el supuesto de que los controladores ODBC deben implementarse como una capa adicional sobre una API de DBMS nativa, traduciendo las sentencias ODBC procedentes de la aplicación en las funciones nativas de la API de DBMS y la sintaxis SQL. Este esfuerzo de traducción agrega procesamiento adicional en comparación con tener la aplicación llamada directamente a la API nativa. Esta suposición es verdadera para algunos controladores ODBC implementados a través de una API de DBMS nativa, pero el controlador ODBC de Microsoft SQL Server no se implementa de esta manera. El controlador ODBC de Microsoft SQL Server es un reemplazo funcional de DB-Library. El controlador ODBC de SQL Server funciona con las bibliotecas de red subyacentes exactamente de la misma manera que DLL de biblioteca de base de datos. El controlador ODBC de Microsoft SQL Server no tiene ninguna dependencia en DLL de la biblioteca de base de datos y el controlador funcionará correctamente si DB-Library no está incluso presente en el cliente. Las pruebas de Microsofts han demostrado que el rendimiento de las aplicaciones basadas en ODBC y SQL Server basado en bases de datos es casi igual. La ilustración siguiente compara las implementaciones ODBC y DB-Library. Versiones de controlador y SQL Server La siguiente tabla muestra qué versiones del controlador ODBC de Microsoft SQL Server se suministran con las versiones recientes y service pack (SP) de Microsoft SQL Server. También muestra las versiones del sistema operativo bajo las que los controladores están certificados para ejecutarse y las versiones de SQL Server contra las que están certificados para funcionar. Los controladores más recientes reconocen las capacidades de las bases de datos más antiguas y se ajustan para trabajar con las características que existen en el servidor anterior. Por ejemplo, si un usuario conecta un controlador de versión 2.65 a un servidor de versión 4.21a, el controlador no intenta utilizar ANSI u otras opciones que no existían en SQL Server 4.21a. Por el contrario, los controladores antiguos no utilizan las funciones disponibles en los servidores más nuevos. Por ejemplo, si un controlador de la versión 2.50 se conecta a un servidor de la versión 6.5, el controlador no tiene ningún código para utilizar las nuevas características o opciones introducidas en el servidor 6.5. Se entrega con la versión de SQL Server Windows NT3.5, 3.51 Windows 95 Windows for Workgroups 3.11 Windows 3.1 Nota: Ninguno de los controladores ODBC de Microsoft SQL Server enumerados está certificado para trabajar con Sybase SQL Servers. Las aplicaciones que necesitan conectarse a Sybase SQL Servers deben obtener un controlador ODBC certificado para su uso con Sybase desde Sybase o un proveedor de controladores ODBC de terceros. Para obtener más información acerca de versiones e Instcat. sql, vea Instcat. sql. Configuración y conexión Una aplicación ODBC tiene dos métodos para proporcionar a un controlador ODBC la información que el controlador necesita para conectarse al servidor y la base de datos adecuados. La aplicación puede conectarse utilizando un origen de datos ODBC existente que contiene esta información o puede llamar a SQLDriverConnect o SQLBrowseConnect. Que proporciona la información en el parámetro de cadena de conexión. Configuración de un origen de datos Las fuentes de datos ODBC contienen información que indica al controlador cómo conectarse a una base de datos. Los orígenes de datos ODBC se pueden crear utilizando la aplicación Administrador de ODBC en el Panel de control o por una aplicación que llama a la función ODBC SQLConfigDataSource. Las definiciones de origen de datos se almacenan en C: WindowsSystemOdbc. ini para los sistemas operativos Microsoft Windows versión 3.x y Windows for Workgroups versión 3.x. Fuentes de datos específicas de Windows NT y orígenes de datos de Windows 95 En el sistema operativo Microsoft Windows NT, los orígenes de datos de usuario son específicos de Windows NTaccount bajo Que fueron definidos. Las fuentes de datos específicas del usuario no siempre son visibles para las aplicaciones que se ejecutan como servicios de Windows NT. Las fuentes de datos de Windows 95 se almacenan en la siguiente clave del Registro: HKEYCURRENTUSERSoftwareODBCOdbc. ini. Fuentes de datos del sistema Windows NT En Windows NT, los orígenes de datos del sistema son visibles para todas las cuentas NT de Windows en el equipo. Las fuentes de datos del sistema siempre están visibles para las aplicaciones que se ejecutan como servicios de Windows NT. El gestor de controladores ODBC que se incluye con Microsoft Office 97 también admite fuentes de datos del sistema en clientes de Windows 95. Los orígenes de datos de Windows NTsystem se almacenan en la siguiente clave del Registro: HKEYLOCALMACHINESoftwareODBCOdbc. ini. La información sobre los controladores instalados en un cliente se almacena en C: WindowsSystemOdbcinst. ini en Windows 3. x o Windows for Workgroups 3. x y en HKEYLOCALMACHINESoftwareODBCOdbcinst. ini en Windows NT y Windows 95. Cada controlador debe almacenar información específica del controlador en su fuentes de datos. Cuando un usuario agrega un origen de datos mediante el Administrador de ODBC, el controlador muestra un cuadro de diálogo en el que el usuario especifica información de origen de datos. Cuando se define un origen de datos con SQLConfigDataSource. La función acepta un parámetro de cadena de atributo que puede contener palabras clave específicas del controlador. Todas las palabras clave específicas del controlador SQLConfigDataSource para el controlador ODBC de SQL Server tienen contrapartes en el cuadro de diálogo que se muestra al utilizar Administrador de ODBC. Heres un ejemplo de llamada SQLConfigDataSource que configura una fuente de datos de SQL Server haciendo referencia a un servidor que utiliza DHCP en TCP / IP: La biblioteca de red predeterminada se establece mediante la Utilidad de configuración de cliente de SQL Server. Los parámetros SERVER, NETWORK y ADDRESS especificados en las fuentes de datos del controlador ODBC de SQL Server operan de la misma manera que los parámetros Server, DLL y Connection String especificados para las entradas avanzadas realizadas con la Utilidad de configuración del cliente de SQL Server. Para obtener más información acerca de los parámetros de entrada avanzada, consulte el Asistente para administradores de Microsoft SQL Server. Los mismos parámetros se pueden especificar en el cuadro de diálogo de creación de origen de datos que se muestra en Administrador de ODBC. La relación entre los parámetros se ilustra en la siguiente tabla. Utilidad de configuración del cliente de SQL El controlador ODBC de SQL Server admite tres clases de palabras clave en SQLDriverConnect. Las palabras clave ODBC estándar El controlador ODBC de SQL Server admite las cuatro palabras clave ODBC SQLDriverConnect estándar: DSN, UID, PWD y DRIVER. Las palabras clave específicas del controlador SQLConfigDataSource en SQLDriverConnect el controlador ODBC de SQL Server admite todas las palabras clave específicas del controlador que admite para SQLConfigDataSource. Consulte la lista anterior en este documento para obtener una descripción de estas palabras clave específicas del controlador. Las palabras clave específicas del controlador APP y WSIDIn además de soportar las mismas palabras clave específicas del controlador que SQLConfigDataSource. SQLDriverConnect también admite las dos palabras clave específicas del controlador APP y WSID. APP Esta palabra clave especifica el nombre de la aplicación que se va a grabar en la columna nombre_programa en master. dbo. sysprocesses. APP es equivalente a una aplicación de biblioteca de base de datos que llama a la función DBSETLAPP en C oa la función SQLSetLApp en el sistema de programación de Visual Basic. WSID Esta palabra clave especifica el nombre de la estación de trabajo que se va a registrar en la columna hostname en master. dbo. sysprocesses. WSID es equivalente a una aplicación de biblioteca de base de datos que llama a la función DBSETLHOST en C oa la función SQLSetLHost en Visual Basic. Mensajes de conexión El controlador ODBC de SQL Server devuelve SQLSUCCESSWITHINFO en un SQLConnect satisfactorio. SQLDriverConnect. O SQLBrowseConnect. Cuando una aplicación ODBC llama a SQLError después de obtener SQLSUCCESSWITHINFO, puede recibir los siguientes mensajes: 5701 Indica SQL Server inicialmente poniendo el contexto de los usuarios en la base de datos predeterminada definida en el servidor para el ID de inicio de sesión utilizado en la conexión 5703 Indica el idioma que se utiliza en el servidor If Ya sea el origen de datos ODBC tiene una base de datos predeterminada especificada o la aplicación especificada la palabra clave DATABASE en SQLDriverConnect o SQLBrowseConnect. Habrá un segundo mensaje 5701 que indica que el contexto de los usuarios se ha cambiado a la base de datos solicitada. El ejemplo siguiente muestra estos mensajes que se devuelven en una conexión correcta mediante el inicio de sesión de Administrador del sistema (SA). El inicio de sesión de SA tiene su base de datos predeterminada en el servidor definido como la base de datos maestra, el servidor está ejecutando el inglés de EE. UU. Y la conexión utiliza un origen de datos ODBC que especifica pubs como base de datos predeterminada. Las aplicaciones pueden ignorar estos mensajes 5701 y 5703 sólo son informativos. Sin embargo, las aplicaciones no pueden ignorar el retorno del código de retorno SQLSUCCESSWITHINFO en SQLConnect. SQLDriverConnect. O SQLBrowseConnect. Esto se debe a que se pueden devolver mensajes distintos de 5701 y 5703 que requieren acción. Por ejemplo, si un controlador se conecta a un SQL Server con procedimientos almacenados del sistema obsoleto, uno de los mensajes devueltos a través de SQLError es: Una rutina de manejo de errores de aplicaciones para conexiones de SQL Server debe llamar a SQLError hasta que devuelva SQLNODATAFOUND y actuar en cualquier mensaje que no sea el SQL Server ofrece tres modelos de seguridad para autenticar los intentos de conexión: El SA define los inicios de sesión de SQL Server con contraseñas en SQL Server y luego asocia los inicios de sesión con los usuarios en bases de datos individuales. Con versiones anteriores de SQL Server, todos los intentos de conexión deben especificar un inicio de sesión y una contraseña válidos. SQL Server versión 6.0 o 6.5 también permite conexiones de confianza a un servidor que ejecuta seguridad estándar. Los inicios de sesión de SQL Server están separados de los ID de usuario de Windows NT. La SA define los inicios de sesión para aquellas cuentas de Windows NTuser que se les permite conectarse a SQL Server. Los usuarios no tienen que especificar un inicio de sesión y una contraseña separados cuando se conectan a SQL Server después de iniciar sesión en Windows NTnetwork. Cuando intentan conectarse, la biblioteca de red intenta una conexión de confianza a SQL Server. Si los usuarios Windows NTaccount es uno que el SA especificado a SQL Server, la conexión se realiza correctamente. El SA define tanto los inicios de sesión de SQL Server como las cuentas de Windows NT como los inicios de sesión de SQL Server. Los usuarios con cuentas de Windows NT validadas pueden conectarse utilizando conexiones de confianza que otros usuarios pueden conectar utilizando la seguridad estándar con los inicios de sesión de SQL Server. El controlador ODBC de SQL Server siempre utiliza una conexión de confianza cuando se conecta a un servidor que ejecuta seguridad integrada. También se le puede indicar al controlador que abra conexiones de confianza cuando se conecte a un servidor que se esté ejecutando con seguridad estándar o mixta. Sólo las canalizaciones con nombre o las bibliotecas de red multiprotocolo admiten la seguridad integrada y las conexiones de confianza. Existen dos formas de indicar al controlador que utilice conexiones de confianza: Opciones de origen de datos específicas del controlador Al definir un origen de datos mediante el Administrador de ODBC, puede seleccionar Usar conexión de confianza. Cuando se define un origen de datos utilizando SQLConfigDataSource. Una aplicación puede especificar TrustedConnection1. Opciones de conexión específicas del controlador Antes de realizar una solicitud de conexión, la aplicación puede establecer una opción específica del controlador: La seguridad integrada ofrece varias ventajas: Las contraseñas no necesitan ser almacenadas en la aplicación. Las contraseñas nunca están presentes en los paquetes de TDS de SQL Server. La seguridad integrada es fácil de administrar porque la SA puede usar la utilidad SQL Security Manager para crear inicios de sesión de SQL Server de cuentas de Windows NT existentes. Consideraciones sobre el protocolo La seguridad integrada sólo está disponible cuando se utilizan los canales con nombre o las Bibliotecas de red multiprotocolo. Cuando se utiliza la biblioteca de red multiprotocolo, el SA también puede configurar el servidor para cifrar los paquetes enviados a través de la red, de modo que incluso los usuarios de los sniffers de red no pueden ver los datos. Las canalizaciones con nombre y multiprotocolo Net-Libraries también pueden funcionar con una pila de protocolo TCP / IP, SPX / IPX o NetBEUI. Esto significa que un cliente que ejecuta sólo una pila de protocolos TCP / IP puede utilizar los sockets de Windows, las canalizaciones con nombre o las bibliotecas de red multiprotocolo. Las bases de datos de Windows (TCP / IP), SPX / IPX, Appletalk, DECNet y Banyan Vines Net-Libraries sólo funcionan con su única pila de protocolos asociados. Debido a su funcionalidad adicional, como la característica de cifrado, las bibliotecas de red multiprotocolo son algo más lentas que las demás. Las pruebas en Microsoft han encontrado que las bibliotecas de red TCP / IP son algo más rápidas que las otras bibliotecas de red. Sin embargo, otras consideraciones, como el diseño de la base de datos, la indexación y el diseño de consultas y aplicaciones, suelen tener un mayor impacto en el rendimiento que la elección de una biblioteca de red. Las aplicaciones que se ejecutan en SQL Server 6.0 o 6.5 a veces pueden mejorar su rendimiento restableciendo el tamaño de paquete de red TDS. El tamaño de paquete predeterminado se establece en el servidor y es 4K. 4K generalmente da el mejor rendimiento. Las aplicaciones pueden establecer el tamaño del paquete por sí mismas si las pruebas muestran que funcionan mejor con un tamaño de paquete diferente. Las aplicaciones ODBC pueden hacerlo llamando a SQLSetConnectionOption con la opción SQLPACKETSIZE antes de conectarse. Algunas aplicaciones pueden funcionar mejor con un tamaño de paquete mayor, pero las mejoras de rendimiento generalmente son mínimas para tamaños de paquetes mayores que 8K. Verificación y comprobación de orígenes de datos La utilidad Odbcping. exe se puede utilizar para comprobar si se puede realizar una conexión ODBC entre un cliente y SQL Server. La sintaxis de comando para utilizar la utilidad es: servername Es el nombre de red del servidor que ejecuta SQL Server. Datasource Es el nombre de una fuente de datos ODBC. Loginid Es el ID de inicio de sesión de SQL Server. Contraseña Es la contraseña de inicio de sesión. Debe especificar / S o / D. Pero no ambos. (La versión de odbcping que se suministra con SQL Server 6.0 no acepta el parámetro / D, sólo / S. / U y / P.) Cuando odbcping hace una conexión satisfactoria, muestra un mensaje indicando que la conexión fue correcta y las versiones Del controlador y del servidor. Por ejemplo: El código pfNative (o Native Error) es importante para diagnosticar problemas de conexión. Para obtener más información, consulte Códigos de error pfNative. Procesamiento de consultas y resultados Buenas prácticas generales En las secciones siguientes se discuten las prácticas generales que aumentarán el rendimiento de las aplicaciones ODBC de SQL Server. Muchos de los conceptos se aplican a las aplicaciones de bases de datos en general. Columnas en un conjunto de resultados Las aplicaciones deben seleccionar sólo las columnas necesarias para realizar la tarea a mano. Esto no solo reduce la cantidad de datos enviados a través de la red, sino que también reduce el impacto de los cambios en la base de datos en la aplicación. Si una aplicación no hace referencia a una columna de una tabla, la aplicación no se ve afectada por los cambios realizados en esa columna. Procedimientos almacenados Los sitios pueden lograr mejoras de rendimiento mediante la codificación de la mayoría de sus sentencias de SQL en procedimientos almacenados y que las aplicaciones llamen a los procedimientos almacenados en lugar de emitir las sentencias SQL en sí. Esto ofrece los siguientes beneficios: Las sentencias SQL se analizan y compilan sólo cuando se crean los procedimientos, no cuando los procedimientos son ejecutados por las aplicaciones. Reducción de la sobrecarga de la red Hacer que una aplicación ejecute un procedimiento en lugar de enviar consultas a veces complejas a través de la red puede reducir el tráfico en la red. Si una aplicación ODBC utiliza la sintaxis ODBC para ejecutar un procedimiento almacenado, el controlador ODBC realiza optimizaciones adicionales que eliminan la necesidad de convertir datos de parámetros (para obtener más información, consulte ODBC Call vs. Transact-SQL EXECUTE). Las reglas empresariales de las organizaciones se pueden codificar y depurar una vez en un procedimiento almacenado y, a continuación, se aplicarán de forma coherente en todas las aplicaciones. El sitio no tiene que depender de todos los programadores de aplicaciones que codifican sus sentencias SQL correctamente en todas las aplicaciones. La mayoría de los sitios tendrán sus mejores programadores SQL desarrollando procedimientos almacenados. Esto significa que las sentencias SQL en los procedimientos tienden a ser más eficientes y tienen menos errores que cuando el código se desarrolla varias veces por programadores de diferentes niveles de habilidad. Las versiones Enterprise del sistema de desarrollo de Microsoft Visual C y del sistema de programación de Microsoft Visual Basic también ofrecen una nueva herramienta de depuración de SQL. Con SQL Debugger, los programadores pueden utilizar las instalaciones de depurador estándar de su entorno de programación, como establecer puntos de interrupción y observar variables, para depurar sus procedimientos almacenados de SQL Server. Lotes Una aplicación que genera varias sentencias de SQL para ejecutar realiza un mejor rendimiento si reúne las sentencias y las envía al servidor de una vez. Esto reducirá el número de viajes en red que la aplicación utiliza para realizar el mismo trabajo. Por ejemplo: La aplicación utiliza SQLMoreResults para posicionarse en el siguiente conjunto de resultados cuando terminan con el conjunto de resultados actual. SQLBindCol y SQLGetData El uso excesivo de SQLBindCol para enlazar una columna de conjunto de resultados a una variable de programa es costoso porque SQLBindCol hace que un controlador ODBC asigne memoria. Cuando una aplicación enlaza una columna de resultados a una variable, esa vinculación permanece en vigor hasta que la aplicación llama a SQLFreeStmt con fOption establecida en SQLDROP o SQLUNBIND. Los enlaces no se deshacen automáticamente cuando se completa la instrucción. Esta lógica permite a las aplicaciones tratar eficazmente situaciones en las que pueden ejecutar la misma sentencia SELECT varias veces con diferentes parámetros. Dado que el conjunto de resultados mantendrá la misma estructura, la aplicación puede enlazar el conjunto de resultados una vez, procesar todas las sentencias SELECT diferentes, y luego hacer un SQLFreeStmt con fOption establecido en SQLUNBIND después de la última ejecución. Las aplicaciones no deberían llamar a SQLBindCol para enlazar las columnas de un conjunto de resultados sin llamar primero a SQLFreeStmt con fOption establecido en SQLUNBIND para liberar los enlaces anteriores. Cuando se utiliza SQLBindCol. Las aplicaciones pueden hacer enlace en fila o en columnas. La vinculación en fila es algo más rápida que la vinculación de columnas. Las aplicaciones pueden utilizar SQLGetData para recuperar datos columna por columna, en lugar de vincular las columnas del conjunto de resultados con SQLBindCol. Si un conjunto de resultados contiene sólo un par de filas, a continuación, utilizar SQLGetData en lugar de SQLBindCol es más rápido, de lo contrario, SQLBindCol ofrece el mejor rendimiento. Si una aplicación no siempre pone los datos en el mismo conjunto de variables, debería utilizar SQLGetData en lugar de volver a enlazar constantemente. Las aplicaciones sólo pueden utilizar SQLGetData en las columnas que están en la lista de selección después de que todas las columnas están enlazadas con SQLBindCol. La columna también debe aparecer después de cualquier columna en la que la aplicación ya haya utilizado un SQLGetData. Conversión de datos Las funciones ODBC que se ocupan de mover datos dentro o fuera de variables de programa, como SQLBindCol. SQLBindParameter. Y SQLGetData. Permiten la conversión implícita de tipos de datos. Por ejemplo, una aplicación que muestra una columna numérica puede pedir al controlador que convierta los datos de numérico a carácter: Las aplicaciones deben minimizar las conversiones de datos. A menos que la conversión de datos sea una parte obligatoria de la aplicación, la aplicación debe enlazar columnas a una variable de programa del mismo tipo de datos que la columna del conjunto de resultados. Si la aplicación necesita tener los datos convertidos, es más eficiente para la aplicación pedir al controlador que realice la conversión de datos que para que la aplicación lo haga. El controlador normalmente sólo transfiere datos directamente desde el búfer de red a las variables de las aplicaciones. Solicitar al controlador que realice la conversión de datos obliga al controlador a almacenar en búfer los datos ya utilizar ciclos de CPU para realizar la conversión. Truncamiento de datos Si una aplicación intenta recuperar datos en una variable que es demasiado pequeña para contenerla, el controlador genera una advertencia. El controlador debe asignar memoria para los mensajes de advertencia y gastar recursos de la CPU en alguna manipulación de errores. Esto puede evitarse si la aplicación asigna variables suficientemente grandes para contener los datos de las columnas del conjunto de resultados o utiliza la función SUBSTRING en la lista de selección para reducir el tamaño de las columnas del conjunto de resultados. Opciones de consulta Los intervalos de tiempo de espera se pueden ajustar para evitar problemas. Además, tener configuraciones diferentes para algunas instrucciones ODBC y opciones de conexión entre varios identificadores abiertos de conexión o instrucción puede generar tráfico de red en exceso. Llamar a SQLSetConnectOption con fOption establecido en SQLLOGINTIMEOUT controla la cantidad de tiempo que una aplicación espera un intento de conexión al tiempo de espera mientras espera establecer una conexión (0 especifica una espera infinita). Los sitios con tiempos de respuesta lentos pueden establecer este valor alto para asegurar que las conexiones tengan tiempo suficiente para completar, pero el intervalo siempre debe ser lo suficientemente bajo como para dar al usuario una respuesta en un tiempo razonable si el controlador no puede conectarse. Al llamar a SQLSetStmtOption con fOption establecido en SQLQUERYTIMEOUT se establece un intervalo de tiempo de espera de consulta para proteger al servidor y al usuario de las consultas de ejecución larga. Llamar a SQLSetStmtOption con fOption establecido en SQLMAXLENGTH limita la cantidad de texto y datos de imagen que puede recuperar una instrucción individual. Llamar a SQLSetStmtOption con fOption establecido en SQLMAXROWS también limita un conjunto de filas a las primeras n filas si eso es todo lo que necesita la aplicación. Tenga en cuenta que la configuración de SQLMAXROWS hace que el controlador emita una sentencia SET ROWCOUNT al servidor, lo que afectará a todas las sentencias de SQL, incluidos los disparadores y las actualizaciones. Sin embargo, se debe tener cuidado al establecer estas opciones. Es mejor si todos los manejadores de sentencia en un identificador de conexión tienen la misma configuración para SQLMAXLENGTH y SQLMAXROWS. Si el controlador cambia de un identificador de sentencia a otro con diferentes valores para estas opciones, el controlador debe generar las instrucciones SET TEXTSIZE y SET ROWCOUNT apropiadas para cambiar la configuración. El controlador no puede poner estas instrucciones en el mismo lote que el usuario SQL ya que el usuario SQL puede contener una instrucción que debe ser la primera instrucción en un lote, por lo que el controlador debe enviar las sentencias SET TEXTSIZE y SET ROWCOUNT en un lote separado, que Genera automáticamente una vuelta al servidor. SET NOCOUNT Las aplicaciones pueden ejecutar la instrucción Transact-SQL SET NOCOUNT ON. Cuando está activado, SQL Server no devuelve una indicación de cuántas filas se han visto afectadas por las instrucciones de modificación de datos o por ninguna declaración dentro de los procedimientos. Cuando SET NOCOUNT está activado, el controlador no obtiene la información que necesita para devolver el número de filas afectadas si la aplicación llama a SQLRowCount después de una instrucción de modificación de datos. Todas las sentencias ejecutadas en un procedimiento almacenado, incluyendo instrucciones SELECT, generan un mensaje afectado por las filas x. Emitir un SET NOCOUNT ON al inicio de un procedimiento almacenado grande puede reducir significativamente el tráfico de red entre el servidor y el cliente y mejorar el rendimiento mediante la eliminación de estos mensajes. Típicamente estos mensajes no son necesarios por la aplicación cuando está ejecutando un procedimiento almacenado. Cursores Comenzando con SQL Server 6.0, el controlador ODBC de SQL Server admite las opciones de cursor ODBC utilizando cursores de servidor. Tipos de cursor El estándar ODBC asume que un cursor se abre automáticamente en cada conjunto de resultados y, por lo tanto, no hace una distinción entre un conjunto de resultados y un cursor. Sin embargo, las sentencias SELECT de SQL Server siempre devuelven un conjunto de resultados. Un cursor de SQL Server es una entidad independiente creada cuando la aplicación necesita para realizar operaciones de cursor como desplazamiento y actualizaciones posicionadas. En el modelo ODBC, todas las instrucciones SQL devuelven un conjunto de resultados dentro de un cursor y una aplicación recupera filas a través del cursor utilizando SQLFetch o SQLExtendedFetch. Antes de ejecutar una instrucción SQL, una aplicación ODBC puede llamar a SQLSetStmtOption para establecer opciones de sentencia que controlan el comportamiento de los cursores. Estos son los ajustes predeterminados para las opciones del cursor. SQL Server does not support mixed cursors. All ODBC cursors support the concept of a rowset, which is the number of rows returned on an individual SQLExtendedFetch . For example, if an application is presenting a 10-row grid to the user, the cursor can be defined with a rowset size of 10 to simplify mapping data into the grid. Concurrency Option Overview In addition to the cursor types, cursor operations are also affected by the concurrency options set by the application: SQL Server still requests a shared lock on each row as it is read into the cursor as in READ COMMITTED, but if the cursor is opened within a transaction, the shared locks are held until the end of the transaction instead of being freed after the row is read. This is the same effect as specifying HOLDLOCK on a SELECT statement. Note that the ODBC API specifies additional transaction isolation levels, but these are not supported by SQL Server or the Microsoft SQL Server ODBC driver. Server Cursors Prior to version 6.0, SQL Server sent result sets back to clients using only one type of result set, the default result set. While the default result set is efficient at sending results back to clients, it only supports the characteristics of the default ODBC result set: forward-only, read-only, and a rowset size of one. Because of this, the Microsoft SQL Server ODBC drivers that shipped with SQL Server version 4.2 x only supported the default ODBC settings. When using a default result set, there is only one roundtrip between the client and server this occurs at the time the SQL statement is executed. After the statement is executed, the server sends the packets containing the results back to the client until all of the results have been sent back or the client has cancelled the results by calling SQLMoreResults . Calls to SQLFetch or SQLExtendedFetch do not generate roundtrips to the server, they just pull data from the client network buffers into the application. SQL Server 6.0 introduced cursors that are implemented on the server (server cursors). There are two types of server cursors: This type of cursor is based on the ANSI syntax for cursors and is meant to be used in Transact-SQL batches, primarily in triggers and stored procedures. Transact-SQL cursors are not intended to be used in client applications. API server cursorsThis type of cursor is created by either the DB-Library or ODBC APIs. The SQL Server ODBC driver that shipped with SQL Server 6.0 uses API server cursors to support the ODBC cursor options. Users access the functionality of API server cursors through either ODBC or DB-Library. If an ODBC application executes a statement with the default cursor settings, the SQL Server ODBC driver requests a default result set from SQL Server. If the application sets the ODBC cursor type options to anything other than the defaults, however, then the SQL Server ODBC driver instead requests the server to implement a server cursor with the same options requested by the application. Since the cursor is implemented on the server, the driver does not have to use memory on the client to build a client-based cursor. Server cursors can also reduce network traffic in cases where a user decides they do not need to retrieve an entire result set. For example, if a user opens a cursor with 1,000 rows but then finds what they were looking for in the first 100 rows they scroll through, the other 900 rows are never sent across the network. When using server cursors, each call to SQLFetch . SQLExtendedFetch, or SQLSetPos causes a network roundtrip from the client to the server. All cursor statements must be transmitted to the server because the cursor is actually implemented on the server. One potential drawback of server cursors is that they currently do not support all SQL statements. Server cursors do not support any SQL statements that generate multiple result sets, therefore they cannot be used when the application executes either a stored procedure or a batch containing more than one select. If the application has set options that cause the driver to request an API server cursor, and then it executes a statement that server cursors do not support, the application gets an error: SQL Server accepts this second statement on the connection handle because, as far as it is concerned, it has completed the last statement on the connection handle, which was the fetch of the first five rows of the rows for hstmt1. Choosing a Cursor Option The choice of cursor type depends on several variables, including: Size of the result set. Percentage of the data likely to be needed. Performance of the cursor open. Need for cursor operations like scrolling or positioned updates. Desired level of visibility to data modifications made by other users. The default settings would be fine for a small result set if no updating is done, while a dynamic cursor would be preferred for a large result set where the user is likely to find their answer before retrieving many of the rows. Some simple rules to follow in choosing a cursor type are: Use default settings for singleton selects (returns one row), or other small result sets. It is more efficient to cache a small result set on the client and scroll through the cache. Use the default settings when fetching an entire result set to the client, such as when producing a report. After SQLExecute or SQLExecDirect . the application can increase the rowset size to retrieve multiple rows at a time using SQLExtendedFetch . The default settings cannot be used if the application is using positioned updates. The default settings cannot be used if the application is using multiple active statements. The default settings must be used for any SQL statement or batch of SQL statements that will generate multiple result sets. Dynamic cursors open faster than static or keyset-driven cursors. Internal temporary work tables must be built when static and keyset-driven cursors are opened but are not required for dynamic cursors. Use keyset-driven or static cursors if SQLFETCHABSOLUTE is used. Static and keyset-driven cursors increase the usage of tempdb . Static server cursors build the entire cursor in tempdb keyset-driven cursors build the keyset in tempdb . Each call to SQLFetch or SQLExtendedFetch causes a roundtrip to the server when using server cursors. Applications should minimize these roundtrips by using a reasonably large rowset size and by using SQLExtendedFetch instead of SQLFetch whenever possible. Implicit Cursor Conversions Applications can request a cursor type through SQLSetStmtOption and then execute an SQL statement that is not supported by server cursors of the type requested. A call to SQLExecute or SQLExecDirect returns SQLSUCCESSWITHINFO and SQLError returns: The application can determine what type of cursor is now being used by calling SQLGetStmtOption with fOption set to SQLCURSORTYPE. The cursor type conversion applies to only one statement. The next SQLExecDirect or SQLExecute will be done using the original statement cursor settings. Both SQL Server 6.0 and 6.5 have the following restrictions: If an SQL statement contains UNION, UNION ALL, GROUP BY, an outer join, or DISTINCT, all cursor types other than static are converted to static. If a keyset-driven cursor is requested and there is at least one table that does not have a unique index, the cursor is converted to a static cursor. SQL Server 6.0 has the following additional restrictions: If a dynamic cursor is requested and there is at least one table that does not have a unique index, the cursor is converted to a static cursor. If a dynamic cursor is requested and the SQL statement contains an ORDER BY that does not match a unique index or subquery, the cursor is converted to a static cursor. SQLExecDirect vs. SQLPrepare/SQLExecute This section discusses when SQLExecDirect or SQLPrepare / SQLExecute should be used. Driver Implementation Overview ODBC offers two options for executing a statement. If a statement is only executed once or twice, the application can use SQLExecDirect to execute the statement. The ODBC definition of SQLExecDirect states that the database engine parses the SQL statement, compiles an execution plan, executes the plan, and then returns results to the application. If an application executes the same statement many times, then the overhead of having the engine compile the plan every time degrades performance. An application in this case can call SQLPrepare once and then call SQExecute each time it executes the statement. The ODBC definition of SQLPrepare states that the database engine just parses the statement and compiles an execution plan, then returns control to the application. On SQLExecute . the engine simply executes the precompiled execution plan and returns the results to the client, thereby saving the overhead of parsing and recompiling the execution plan. SQL Server itself does not directly support the SQLPrepare / SQLExecute model, but the SQL Server ODBC driver can use stored procedures to emulate this behavior. On a SQLPrepare . the driver asks the server to create a stored procedure that contains the SQL statement from the application. On SQLExecute . the driver executes the created stored procedure. The ODBC driver uses stored procedures to support SQLPrepare / SQLExecute when the option is enabled either in the data source or the SQLDriverConnect keywords. For example, if an application calls: The driver sends a remote stored procedure call to have the server run the ODBCnnnnnnnn procedure. Because a CREATE PROCEDURE statement essentially compiles an SQL statement into an execution plan, and an EXECUTE statement simply executes the precompiled plan, this meets the criteria for the SQLPrepare / SQLExecute mode. Excess or inappropriate use of SQLPrepare / SQLExecute degrades an applications performance. SQL Server applications should only use SQLPrepare / SQLExecute if they plan to execute a statement more than 3 to 5 times. If an application needs to execute a statement only once, using SQLPrepare / SQLExecute generates two roundtrips to the server: one to create the stored procedure and another to execute it. SQLExecDirect would only use one roundtrip and would also save the overhead of creating and storing a stored procedure. Excess use of SQLPrepare can also cause locking contention in the system tables in tempdb as concurrent users continually try to create the stored procedures to support SQLPrepare . You may think that applications must use SQLPrepare / SQLExecute to use parameter markers, even if the application will only execute the statement once or twice. This is not true, applications can use parameter markers with SQLExecDirect by calling SQLBindParameter before SQLExecDirect . If an application will be run by many concurrent users and the users will all be using the same SQL statement, the best approach is to create the SQL statement as a permanent, parameterized, stored procedure and executed it with SQLExecDirect . Having many users concurrently issue SQLPrepare commands can create a concurrency problem on the system tables in tempdb . Even if each user is executing exactly the same statement, the SQL Server ODBC driver on each client is creating its own copy of a temporary stored procedure in tempdb . If the SQL statement is created as a parameterized stored procedure, however, the procedure is created only once. Each ODBC application does not have to create a new procedure for its exclusive use, it simply uses a copy of the permanent procedures execution plan from the procedure cache. When used in the appropriate circumstances (to execute a single statement several times), SQLPrepare / SQLExecute can provide significant performance savings. Impact on Tempdb SQL Server 6.0 introduced temporary stored procedures, which are identified by having a number sign () as the first character in the name. These procedures operate like temporary tables and are automatically dropped by the server if the connection is broken. The SQL Server ODBC driver now creates the procedures that support SQLPrepare as temporary procedures. This makes it impossible for the ODBC-related stored procedures to build up as a result of broken network connections or client computer failures. However, the temporary stored procedures are always created in tempdb . This means that sites running SQL Server 6.0 or 6.5 with ODBC applications that use SQLPrepare must ensure that tempdb is large enough to hold the temporary procedures generated to support SQLPrepare . There is another factor to consider in relation to how many stored procedures exist in tempdb . ODBC applications call SQLSetConnectoption with fOption set to the driver-specific value SQLUSEPROCEDUREFORPREPARE and vParam set to either SQLUPOFF, SQLUPON, or SQLUPONDROP to control the generation of temporary procedures. SQLUPOFF means that the driver does not generate stored procedures. SQLUPONDROP means that the driver generates stored procedures, and that they are dropped when the application does a SQLDisconnect . a SQLFreeStmt with fOption set to SQLDROP, or the next time the application issues SQLPrepare on the same statement handle. SQLUPON means that temporary procedures are created, but they are only dropped on a SQLDisconnect. SQLUPON is the default setting. The driver can reuse procedures if an application re-prepares the same SQL statement, and most applications realize a performance boost because the driver is not having to continually drop stored procedures. This may result in a build up of ODBC procedures in tempdb . however, from applications that never disconnect or applications that make heavy use of SQLPrepare . These applications should set SQLUPONDROP by calling SQLSetConnectOption . Starting with the driver that shipped in SQL Server 6.5 SP2, SQLUPONDROP is now an option that can be specified on data sources for the SQL Server ODBC driver. Other Considerations of SQLPrepare To keep from having to hold locks on the tempdb system tables for the length of a user transaction, the SQL Server ODBC driver does not generate a stored procedure for SQLPrepare if it is called within a transaction. The exception to this is when the SQLPrepare is the first statement in the transaction. In this case, the driver generates a stored procedure but then immediately commits the CREATE PROCEDURE statement. The driver does not generate a stored procedure for a SQLPrepare that uses the ODBC CALL escape clause to call a stored procedure. On SQLExecute, the driver executes the called stored procedure (there is no need to create a temporary stored procedure). Calling either SQLDescribeCol or SQLDescribeParam before calling SQLExecute generates an extra roundtrip to the server. On SQLDescribeCol . the driver removes the WHERE clause from the query and sends it to the server with SET FMTONLY ON to get the description of the columns in the first result set returned by the query. On SQLDescribeParam . the driver calls the server to get a description of the columns in the tables referenced by the query. This method also has some restrictions, such as not being able to resolve parameters in subqueries. Stored Procedures This section discusses issues related to executing stored procedures using the SQL Server ODBC driver. ODBC Call vs. Transact-SQL EXECUTE Applications can call SQL Server procedures using either the Transact-SQL EXECUTE statement or the ODBC SQL CALL escape clause (the Transact-SQL statement appears first, followed by the ODBC SQL CALL): SQL Server does not send back the values for the return code or output parameters until the end of all result sets for the procedure. The program variables ProcRet and OParm do not hold the output values of 99 and 88 until SQLMoreResults returns SQLNODATAFOUND. Text and Image Data The SQL Server ODBC driver has a couple of optimizations for text and image column processing that applications can use to improve performance. Bound vs. Unbound Text and Image Columns When using server cursors (see Cursors), the driver is optimized to not transmit the data for unbound text or image columns at the time the row is fetched. The text or image data is not actually retrieved from the server until the application issues SQLGetData for the column. This optimization can be applied to applications so that no text or image data is displayed while a user is scrolling up and down a cursor. After the user selects a row, the application can call SQLGetData to retrieve the text or image data. This saves transmitting the text or image data for any of the rows the user does not select and can save the transmission of very large amounts of data. Logged vs. Nonlogged An application can request that the driver not log text and image modifications: This option should only be used for situations where the text or image data is not critical, and the data owners are willing to trade data recovery for higher performance. Data-At-Execution and Text and Image Columns ODBC Data-At-Execution allows applications to work with extremely large amounts of data on bound columns or parameters. When retrieving very large text or image columns, an application cannot simply allocate a huge buffer, bind the column into the buffer, and fetch the row. When updating very large tex t or image columns, the application cannot simply allocate a huge buffer, bind it to a parameter marker in an SQL statement, and then execute the statement. Whenever the size of the text or image data exceeds 400K (64K with SQL Server 4.21a), the application must use SQLGetData or SQLPutData with their Data-At-Execution options. Applications should always use Data-At-Execution if there is any possibility that the size of the data will exceed these limits. Data-At-Execution is described in the ODBC 2.0 Programmers Reference however, it remains one of the hardest parts of the ODBC API for an application programmer to learn. The Appendix of this paper contains the source code of two Win32 console applications, Getimage. c and Putimage. c, that illustrate using Data-At-Execution to read and write large amounts of image data. Text columns would use similar calls, the only difference would be binding between SQLCCHAR and SQLLONGVARCHAR instead of SQLCBINARY and SQLLONGVARBINARY. Programmers interested in working with text or image columns should look up the Data-At-Execution index entries of the ODBC 2.0 Programmers Reference . then search for text and image in Microsoft SQL Server Programming ODBC for SQL Server. Querying Metadata This section discusses some common issues when getting metadata and catalog information from the driver. Instcat. sql Both the SQL Server system catalog stored procedures and the ODBC API catalog functions address the need of applications to retrieve catalog information from a database. Because there is a high correlation between the ODBC catalog functions and the SQL Server catalog stored procedures, the SQL Server ODBC driver implements many of the ODBC API catalog functions as calls to a corresponding SQL Server catalog procedure. The driver is therefore dependent on the catalog stored procedures in any SQL Server to which it connects. Each version of the SQL Server ODBC driver is developed in conjunction with a specific version of SQL Server. The proper operation of each driver version requires the versions of the catalog stored procedures associated with the specific version of SQL Server with which the driver was developed, or a later version of the procedures. For example, the 2.50.0121 driver was developed in conjunction with Microsoft SQL Server version 6.0, and requires either the versions of the system catalog stored procedures that were released with SQL Server 6.0, or with later versions, such as 6.5. The driver does not work properly with older versions of the catalog stored procedures, such as those in SQL Server version 4.21a. If a driver attempts to connect to a SQL Server running an older version of the catalog stored procedures than those required by the driver, the connection completes with SQLSUCCESSWITHINFO and a call to SQLError returns the following message: Although the connection is successful, the application may later encounter errors on calls to the ODBC API catalog functions. Sites running multiple versions of the driver against a server need to ensure that the server is running with at least the version of Instcat. sql associated with the newest ODBC driver that will connect to it. For example, a site running multiple version 6.0 servers could buy SQL Server version 6.5 and upgrade some clients to use the new 2.65.0201 driver that comes with version 6.5. The site would also need to run the 6.5 version of Instcat. sql against the 6.0 servers before the new driver can connect to them. Installing a newer version of Instcat. sql into an older server does not break any existing applications connecting to that server, even ones still using the old drivers. It simply allows the applications using the new driver to operate correctly. Sites should run the Instcat. sql script at the server command prompt by using the isql utility. For more information about determining the version of Instcat. sql currently applied to a server, see Microsoft Knowledge Base article Q137636. For more information about the isql utility, see the Microsoft SQL Server Transact-SQL Reference . Multiple Active Statements per Connection Starting with SQL Server 6.5 and its associated driver, users can have multiple outstanding calls for metadata. In SQL Server 6.5, the catalog procedures underlying the ODBC catalog API implementations can be called by the ODBC driver while it is using static server cursors. This allows applications to concurrently process multiple calls to the ODBC catalog functions. Caching Metadata If an application uses a particular set of metadata more than once, it will probably benefit by caching the information in private variables when it is first obtained. This eliminates the overhead of later calls to the ODBC catalog functions for the same information (which forces the driver to make roundtrips to the server). Updates and Transactions This section discusses how an ODBC application can optimize its data modifications and transaction management. SQLRowCount If an ODBC application needs to know how many rows were affected by a data modification (UPDATE, INSERT, DELETE), it can call the SQLRowCount function after the modification completes. SQLRowCount is generally not filled after a SELECT statement, although it may be if the application is using server cursors. For more information, see Microsoft SQL Server Programming ODBC for Microsoft SQL Server . Batching Procedure Calls SQLParamOptions can be used to efficiently call a stored procedure multiple times with different parameters. SQLBindParameter normally binds a single variable to a parameter, and SQLParamOptions is used to extend this binding so that it binds an array of variables to a parameter. For example, to have five calls of a procedure that takes a single parameter, do the following: Allocate an array of five variables. Use SQLBindParameter to bind the parameter to the lead element of the array. Use SQLParamOptions to tell the driver that the parameter is bound to an array with five elements. When you issue SQLExecDirect . the driver builds a single batch calling the procedure five times, with a different element from the array associated with each procedure call. This is more efficient than sending five separate batches to the server. This process also works with procedures that take multiple parameters. Allocate an array for each parameter with the same number of elements in each array, then call SQLParamOptions specifying the number of elements. Autocommit vs. ANSI Transaction Management ODBC has two ways in which applications manage transactions. The application controls the autocommit mode by calling: When autocommit is turned off, the next statement sent to the database starts a transaction. The transaction remains in effect until the application calls SQLTransact with either the SQLCOMMIT or SQLROLLBACK options. The statement sent to the database after SQLTransact starts the next transaction. ODBC applications should not mix managing transactions through the ODBC autocommit options with calling the Transact-SQL transaction statements. If an application does this, it could generate undetermined results. The application should manage transactions in one of the following ways: Use SQLSetConnectOption to set the ODBC autocommit modes. Use Transact-SQL statements, such as BEGIN TRANSACTION. (The SQLSetConnectOption should be left at its default setting of autocommit on.) Applications should keep transactions as short as possible by not requiring user input while in a transaction. User input can take a long time, and all that time, the application is holding locks that may adversely impact other tasks needing the same data. An application should do all required queries and user interaction needed to determine the scope of the updates before starting the transaction. The application should then begin the transaction, do the updates, and immediately commit or rollback the transaction without user interaction. Using Transactions to Optimize Logging Applications doing several data modifications (INSERT, UPDATE, or DELETE) at one time should do these within one transaction (autocommit off). When autocommit is on, each individual statement is committed by the server. Commits cause the server to flush out the modified log records. To improve performance, do all updates within one transaction and issue a single commit when all the changes have been made. Care must be taken to not include too many updates within one transaction, however. Performing many updates causes the transaction to be open longer and more pages to be locked with exclusive locks, which increases the probability that other users will be blocked by the transaction. Grouping modifications into a single transaction must be done in a way that balances multiuser concurrency with single-user performance. For applications that do not require a high degree of data accuracy, consider using the SQLTXNREADUNCOMMITED transaction isolation level to minimize the locking overhead on the server. SQL Server-specific Features This section discusses features unique to Microsoft SQL Server and the Microsoft SQL Server ODBC driver. Processing COMPUTE BY and COMPUTE Statements The COMPUTE BY clause generates subtotals within a result set, and the COMPUTE clause generates a total at the end of the result set. The SQL Server ODBC driver presents these totals and subtotals back to the calling application by generating multiple result sets for each SELECT. The following example uses COMPUTE BY to generate subtotals and COMPUTE to generate a total: Using DBCC Statements DBCC statements return data to an ODBC application in two ways: Trace flags output An application can turn on various trace flags using the DBCC statement. No data is returned by the DBCC statement that turns on the trace flag, but the trace data is returned on subsequent SQL statements. For example, if the application sets on a 3604 trace flag along with another flag or flags that return output, subsequent calls to SQLExecDirect or SQLExecute return SQLSUCCESSWITHINFO, and the application can retrieve the trace flag output by calling SQLError until it returns SQLNODATAFOUND: For example, after the above SQLExecDirect completes, the following subsequent call to SQLExecDirect returns SQLSUCCESSWITHINFO: Calling SQLError returns: DBCC execution outputAll other DBCC statements return data when they are executed. SQLExecDirect or SQLExecute returns SQLSUCCESSWITHINFO, and the application retrieves the output by calling SQLError until it returns SQLNODATAFOUND. For example, the following statement returns SQLSUCCESSWITHINFO: The timing of calling SQLError is critical when output from PRINT or RAISERROR statements are included in a result set. The call to SQLError to retrieve the PRINT or RAISERROR output must be made immediately after the statement that receives SQLERROR or SQLSUCCESSWITHINFO. This is straightforward when only a single SQL statement is executed, as in the examples above. In these cases, the call to SQLExecDirect or SQLExecute returns SQLERROR or SQLSUCCESSWITHINFO and SQLError can then be called. It is less straightforward when coding loops to handle the output of a batch of SQL statements or when executing SQL Server stored procedures. In this case, SQL Server returns a result set for every SELECT statement executed in a batch or stored procedure. If the batch or procedure contains PRINT or RAISERROR statements, the output for these is interleaved with the SELECT statement result sets. If the first statement in the batch or procedure is a PRINT or RAISERROR, the SQLExecute or SQLExecDirect returns SQLSUCCESSWITHINFO or SQLERROR and the application needs to call SQLError until it returns SQLNODATAFOUND to retrieve the PRINT or RAISERROR information. If the PRINT or RAISERROR statement comes after other SQL statements (such as a SELECT), then the PRINT or RAISERROR information is returned when SQLFetch or SQLExtendedFetch is called for the result set, before the PRINT or RAISERROR returns SQLNODATAFOUND or SQLERROR. For example, in the following procedure, the SQLExecute or SQLExecDirect call returns SQLSUCCESSWITHINFO and a call to SQLError at that point returns the first print message. If the ODBC application then processes through the result set using SQLFetch . the application can get the second print statement by calling SQLError when SQLFetch returns SQLNODATAFOUND: Other Application Considerations This section discusses some additional issues to consider when programming ODBC SQL Server applications. Asynchronous Mode and SQLCancel Some ODBC functions can operate either synchronously or asynchronously (see the ODBC 2.0 Programmers Reference for the list of functions). The application can enable asynchronous operations for either a statement handle or a connection handle. If the option is set for a connection handle, it affects all statement handles on the connection handle. The application uses the following statements to enable or disable asynchronous operations: When an application calls an ODBC function in synchronous mode, the driver does not return control to the application until it is notified that the server has completed the command. When operating asynchronously, the driver immediately returns control to the application, even before sending the command to the server. The driver sets the return code to SQLSTILLEXECUTING. The application is then free to perform other work. To test for completion of the command, make the same function call with the same parameters to the driver. If the driver is still waiting for an answer from the server, it will again return SQLSTILLEXECUTING. The application must keep testing the command periodically until it returns something other than SQLSTILLEXECUTING. When the application gets some other return code, even SQLERROR, the command has completed. Sometimes a command is outstanding for a long time. If the application needs to cancel the command without waiting for a reply, it can do so by calling SQLCancel with the same statement handle as the outstanding command. This is the only time SQLCancel should be used. Some programmers use SQLCancel when the application has processed part way through a result set and they want to cancel the rest of the result set. SQLMoreResults or SQLFreeStmt with fOption set to SQLCLOSE should be used to cancel the remainder of an outstanding result set, not SQLCancel . Multithread Applications The SQL Server ODBC driver is a fully multithreaded driver. Writing a multithread application is an alternative to using asynchronous calls to have multiple ODBC calls outstanding. A thread can make a synchronous ODBC call, and other threads can process while the first thread is blocked waiting for the response to its call. This model is more efficient than making asynchronous calls because it eliminates the overhead of the repeated ODBC function calls testing for SQLSTILLEXECUTING to see if the function has completed. Asynchronous mode is still an effective method of processing. The performance improvements of a multithread model are not enough to justify rewriting asynchronous applications. If users are converting DB-Library applications that use the DB-Library asynchronous model, it is easier to convert them to the ODBC asynchronous model. Multithread applications need to have coordinated calls to SQLError . After a message has been read from SQLError . it is no longer available to the next caller of SQLError . If a connection or statement handle is being shared between threads, one thread may read a message needed by the other thread. SET Options Used by the Driver The ODBC standard is closely matched to the ANSI SQL standard, and ODBC applications expect standard behavior from an ODBC driver. To make its behavior conform more closely with that defined in the ODBC standard, the SQL Server ODBC driver always uses any ANSI options available in the version of SQL Server to which it connects. The server exposes these ANSI options through the Transact-SQL SET statement. The driver also sets some other options to help it support the ODBC environment. The SQL Server ODBC driver that ships with SQL Server 6.5 issues the following Transact-SQL SET statements: Connect to SQL Server version 6.5: The driver issues these statements itself the ODBC application does nothing to request them. Setting these options allows ODBC applications using the driver to be more portable because the drivers behavior then matches the ANSI standard. DB-Library based applications, including the SQL Server utilities, generally do not turn these options on. Sites observing different behavior between ODBC or DB-Library clients when running the same SQL statement should not assume this points to a problem with the ODBC driver. They should first rerun the statement in the DB-Library environment (such as ISQL/w) with the same SET options as would be used by the SQL Server ODBC driver. Since the SET options can be turned on and off at any time by users and applications, developers of stored procedures and triggers should also take care to test their procedures and triggers with the SET options listed above turned both on and off. This ensures that the procedures and triggers work correctly regardless of what options a particular connection may have SET on when they invoke the procedure or trigger. The SET options used by the version 2.65 driver when connected to SQL Server 6.5 has the net effect of setting on three more ANSI options than in the 6.0 environment: ANSINULLS, ANSIPADDING, and ANSIWARNINGS. These options can cause problems in existing stored procedures and triggers. The version 2.65.0240 driver that shipped with SQL Server 6.5 SP2 allows data sources and connection statements to turn these options off. For more information, see Microsoft Knowledge Base article Q149921. The version 2.50 driver that shipped with SQL Server 6.0 also sets on the QUOTEDIDENTIFIER option. With this option set on, SQL statements should comply with the ANSI rule that character data strings be enclosed in single quotes and that only identifiers, such as table or column names, be enclosed in double quotes: For more information about working with QUOTEDIDENTIFIER, see Microsoft Knowledge Base article Q156501. Like the ANSI options noted above, the version 2.65.0240 driver that shipped with SQL Server 6.5 SP2 allows SQLDriverConnect . SQLBrowseConnect . and data sources to specify that QUOTEDIDENTIFIERS not be turned on. ODBC applications should not use the Transact-SQL SET statement to turn these options on or off. They should only set these options in either the data source or the connection options. The logic in the driver depends on it correctly knowing the current state of the SET options. If the application issues the SET statements itself, the driver may generate incorrect SQL statements due to not knowing that the option has been changed. Diagnostic Messages This section discusses how to interpret the error messages that are returned by the SQL Server ODBC driver. All ODBC functions have return codes. The ODBC header files have define statements that equate the return codes to literals, such as SQLSUCCESS, SQLSUCCESSWITHINFO, and SQLERROR. If a function returns SQLSUCCESSWITHINFO, it means the function was successful but there is information available. If a function returns SQLERROR, it means the function failed and there is information available indicating the nature of the problem. To get these messages, the application can call SQLError . SQLError returns three parameters that have important information: SQLState a 5-byte character string with an ODBC error code. pfNative a signed doubleword holding whatever error code is returned by the native database. szErrorMsg a character string holding a header identifying the source of the error and the text of the error message. Identifying the Source of an Error The heading of szErrorMsg can be used to determine the source of the error: This indicates that the driver called the dbnmpntw ConnectionOpen function and that dbnmpntw in turn called the named-pipe API function CreateFile . pfNative Error Codes The value of the pfNative code in an error message is based on the source of the error: If an error is raised by an ODBC component (the Driver Manager, Cursor Library, or the SQL Server ODBC driver), then the pfNative code is 0. If an error is raised by the server, the pfNative code is the SQL Server error code. For more information about SQL Server errors, see chapters 25 and 26 in the Microsoft SQL Server Administrators Companion . If an error is raised by the Net-Library, the pfNative code is the error code returned to the Net-Library from the underlying network protocol stack. For more information about the codes returned by the different underlying network protocol stacks, see the following sources: These codes are generally the same as those listed in Operating System Error Codes in Microsoft Knowledge Base article Q116401. These codes, returned by the Winsock API, are listed in Appendix A, Error Codes, of the Windows Sockets Specification 1.1 . The Windows Sockets Specification can be found on the MSDN Library compact disc. These codes, returned from Novell, are in Novell NetWare Client Protocol Transport API for C under the section for the API function listed in the szErrorMsg . For example, if the pfNative is 253, and szErrorMsg lists SPXListenForSequencedPacket as the function, the reference manual states a 0xFD (253) return from SPX Listen For Sequenced Packet is a Packet Overflow. These codes, returned from Banyan Vines, are listed in the Vines Client Developers Guide . These codes, returned by the RPC API, are listed in the RPC section of Winerror. h. Mapping SQLState Codes The values for the SQLState code are listed in the Microsoft ODBC 2.0 Programmers Reference and SDK Guide . Diagnosing and Profiling Applications Programmers can use several tools to trace the SQL statements received and generated by the SQL Server ODBC driver. They can also use the Windows NT Performance Monitor and SQL Server ODBC driver profiling features to analyze the performance of the driver. Tracing SQL Statements Microsoft SQL Server and ODBC offer several points at which users can trace the SQL statements on their journey from the application to SQL Server, as shown in the following illustration: ODBC Driver Manager Trace The ODBC Driver Manager trace facility is available on all ODBC clients and is started from ODBC Administrator. To start trace from ODBC Administrator In the ODBC Administrator window, click Options . Click the trace options you want. The ODBC trace facility traces all calls made to any ODBC data source on the client. It records ODBC calls immediately after they come into the Driver Manager from the application. This is helpful in debugging problems that the Driver Manager may have when connecting to a driver. This is a fairly minimal trace, however, and is used only when the second tool, ODBCSpy, is not available. Heres an example of an ODBC Driver Manager trace output: A lot of information is missing from this output. There is no indication of the return code for each function call. There is no way to tell if the SQLDriverConnect call was successful however, the fact that the next call was to SQLError could indicate some problem. Since the trace does not show what szErrorMsg string or SQLStat e value was returned by SQLError . there is no way to tell what the problem might have been. The fact that the application went on to allocate a statement handle and execute a statement seems to show that no major problem was encountered. When Driver Manager tracing is on, all calls to ODBC drivers on that client are traced. There is no way to trace only a specific data source. ODBCSpy Trace The ODBCSpy utility ships with the ODBC SDK and can be used to get an informative trace of all the ODBC calls made to a specific ODBC data source. ODBCSpy traces calls as they are passed from the Driver Manager to the ODBC driver. It shows all of the parameters passed for each call to the driver and the information returned from the driver. If an error is encountered, ODBCSpy calls SQLError for all error messages returned and logs all information about the errors in the trace. Heres an ODBCSpy trace of the same SQLError call traced in the example above: This trace output includes more useful information. It shows that the SQLError function itself returned SQLSUCCESS. (The entry for SQLDriverConnect would have shown that it returned SQLSUCCESSWITHINFO, not SQLERROR.) The trace also shows that SQLError returned a SQLState of 01000, a pfNative of 5701, and a szErrorMsg string that indicates SQL Server has changed the connection context to the master database. There are also third-party ODBC tracing tools available. SQL Trace SQL Trace, a trace utility introduced in SQL Server 6.5, uses Open Data Services to intercept and trace all SQL statements coming in to SQL Server. SQL Trace is extremely valuable for determining if a problem is due to the Transact-SQL statements the driver generates to support the ODBC commands coming from the application. A programmer can use ODBCSpy to see exactly what comes from the application to the SQL Server ODBC driver, and then use SQL Trace to see what the driver actually sends to the server. If an application does: SQL Trace shows: SQL Trace can be used to dynamically trace statements coming in from different clients to a server. Sites that have servers earlier than SQL Server 6.5 can use an older, unsupported version of the utility called SQLEye. SQLEye is available on the Microsoft TechNet compact disc. SQL Server Trace Flags SQL Server has a DBCC trace flag (4032) that causes the server to trace incoming SQL statements. SQL Trace is much easier to use, so sites that have SQL Trace or SQLEye generally use those tools instead of the trace flags. When a user sets the 4032 trace flag, the user also generally sets a couple of other trace flags to control the trace: For the 3605 flag, SQL Server traces SQL statements to the SQL Server error log (C:MssqlLogErrorlog). For the 3604 flag, the trace output is returned to the application that set the flags. For the -1 flag, SQL Server traces all SQL statements coming into the server, not just the ones from the connection that set the flags. To have SQL Server trace all SQL statements from all clients to the error log: For more information about trace flags, see the SQL Server documentation. Windows NT Performance Monitor Windows NT Performance Monitor is a powerful tool for profiling the performance of SQL Server applications. SQL Server installs several counters in Performance Monitor (for more information, see the Microsoft SQL Server Administrators Companion ). In SQL Server 6.5, users can also add up to 10 user-defined counters (for more information, see Whats New in SQL Server 6.5 ). To get a better idea of how your query impacts the operation of the server, use the SQL Server counters in Performance Monitor to track the resources used by your application. ODBC Driver Profiling Features The SQL Server ODBC driver version 2.65.0201 and later offers a couple of features that aid in analyzing performance of ODBC applications: The driver can trace all queries where the servers response exceeds a specified time interval, allowing programmers to easily target long-running queries for analysis. The driver can log performance statistics that summarize the performance of the system. Logging Long-Running Queries Applications can request that the driver write all queries whose response exceeds a specified time limit to a file for later analysis by the programmer and database administrator. The log can be turned on in two ways. When an application connects using a data source that specifies long query profiling, the SQL Server ODBC driver will log long-running queries from the time the application connects until it disconnects. For more information, see Setup and Connecting. Use SQLSetConnectOption to set logging on and off dynamically. An application dynamically setting the profiling options first specifies the file to use for the log by executing: Note that this option is global to the application therefore, after the option has been started for any of the SQL Server ODBC connections, long-running queries from all SQL Server ODBC connections open from the application are logged. Logging Performance Data Applications can request that the driver log performance data for the driver. As with long-running query logging, the performance log can be turned on either by the application or by specifying performance logging in the data source using ODBC Administrator. For more information, see Setup and Connecting. When dynamically turning on performance logging by calling SQLSetConnectOption . applications can either write the performance data to a log file or read the data into the application using a sqlperf structure defined in the Odbcss. h header file. The following commands start and stop performance-data gathering: Performance statistics are recorded in a data structure named sqlperf (for an explanation of the sqlperf variables, see the appendix). The statistics are global for all connections made through the driver by the application. For example, if the application starts the performance statistics and opens three connections, the statistics are global for all three connections. If an application wants to log performance data to a file, the following command creates the log file: The log file is a tab-delimited text file that can be opened in Microsoft Excel (specify tab delimited in the wizard that appears). Most other spreadsheet products also support opening a tab-delimited text file. The following command writes a record to the performance log, with the current contents of the data structure recording the performance data: The application does not need to set up a performance log it could instead pull the performance data by using SQLGetConnectOption to get a pointer to the sqlperf structure. This structure is declared in a typedef in the Odbcss. h header file. The following statements are an example of pulling the statistics into the application: If the application uses a data source that has the performance-statistics profiling option activated, the driver writes the statistics header information to the log file and starts accumulating the statistics in its internal data structure when the application makes its first connection using the driver. When the last connection to the SQL Server ODBC driver from the application is closed, the driver writes out the global, accumulated, performance statistics. Profiling Considerations The fact that profiling is global to the driver governs the behavior of the log files. When an application connects to a data source that specifies profiling, the driver starts a log file and begins logging information from all connections active from the application to the SQL Server ODBC driver from that point forward. Even connections to SQL Server data sources that do not specify profiling are recorded because the profiling is done globally for the driver. If the application does a SQLFreeEnv . the ODBC Driver Manager unloads the driver. At this point, both the long-running query log and the performance statistics logs hold the information from the old connections. If the application then makes another connection to the data source that specifies profiling, the driver is reloaded, and it overwrites the old copy of the log file. If an application connects to a data source that specifies profiling, and then a second application connects to the same data source, the second application does not get control of the log file and therefore is not able to log any performance statistics or long-running queries. If the second application makes the connection after the first application disconnects, the driver overwrites the first applications log file with the one for the second application. Note that if an application connects to a data source that has either the long-running query or performance statistics enabled, the driver returns SQLERROR if the application calls SQLSetConnectOption to enable logging. A call to SQLError then returns the following message: Conclusion This paper explains the interaction of Microsoft SQL Server and its associated ODBC driver. This knowledge helps you produce efficient ODBC applications that optimize the interaction between the driver and the server. It helps you avoid code that results in poor performance and describes how to take advantage of the unique features of Microsoft SQL Server and the ODBC driver. This paper also helps programmers and administrators to diagnose problems encountered by ODBC applications running on Microsoft SQL Server. References This section lists additional sources of information on Microsoft SQL Server and ODBC. SQL Server Documentation The primary reference for using ODBC with SQL Server 6.5 is Programming ODBC for Microsoft SQL Server . Much of this material is also in the Help file for the driver, Drvssrvr. hlp however, the latest version of Drvssrvr. hlp, shipped with both SQL Server 6.0 and 6.5, does not cover 6.5 features. Programming ODBC for Microsoft SQL Server and Drvssrvr. hlp are included with SQL Server 6.5. Other products that ship the SQL Server ODBC driver also ship the corresponding driver Help file, Drvssrvr. hlp. ODBC Programmers Reference The primary reference for ODBC is: Microsoft ODBC 2.0 Programmers Reference and SDK Guide Microsoft Press ISBN 1-55615-658-8 Microsoft ODBC 3.0 Software Development Kit and Programmers Reference Microsoft Press ISBN 1-57231-516-4 Other ODBC Books There are many books on programming ODBC available in bookstores, including: Inside ODBC Kyle Geiger Microsoft Press ISBN 1-55615-815-7 Using ODBC 2 Robert Gryphon with Luc Charpentier, Jon Oelschlager, Andrew Shoemaker, Jim Cross, and Albert W. Lilley Que Corporation ISBN 0-7897-0015-8 The ODBC Solution Robert Signore, John Creamer, Michael Stegman McGraw-Hill ISBN 0-07-911880-1 Database Developer s Guide With Visual C Roger Jennings and Peter Hipson Sams Publishing ISBN 0-672-30613-1 Teach Yourself ODBC Programming in 21 Days Bill Whiting, Bryan Morgan, and Jeff Perkings Sams Publishing ISBN 0-672-30609-3 Appendix The appendix first defines all of the driver-specific options defined in Odbcss. h and then has two sample applications that illustrate processing text and image data. Odbcss. h Odbcss. h is a header file containing the definitions used for all of the driver-specific options in the SQL Server ODBC driver. Odbcss. h is distributed with SQL Server Workstation and with SQL Server 6.5 SP2. The version distributed with SP2 has a few extra connection options related to controlling the ANSI options used by the driver. The list below relates to the 6.5 SP2 version of Odbcss. h. SQLSetConnectOption The following options can be set on using SQLSetConnectOption . The bulleted literals are specified as the fOption parameter the literals grouped under each bulleted fOption are specified as vParam . SQLGetStmtOption If SQLGetStmtOption is called with fOption SQLSOPTSSCURRENTCOMMAND, the driver returns an integer to pvParam indicating which command in the batch is the one whose results are being processed. The first command in the batch is 1. SQLColAttributes The following options can be set on using SQLColAttributes . The bulleted literals are specified as the fDescType parameter the literals grouped under each bulleted fDescType are the values returned as pfDesc . SQLGetInfo If SQLGetInfo is called with fInfoType set to SQLINFOSSNETLIBNAME, rgbInfoValue returns the name of the Net-Library used to connect to SQL Server. SQLPerf Structure The meaning of the variables defined in the sqlperf structure are given in this section. These descriptions also apply to the statistics recorded in the performance log file. For a description of how to gather these statistics, see Diagnosing and Profiling Applications. Application Profile Statistics The following variables profile the processing that occurs in the Microsoft SQL Server ODBC driver. Application profile statistics The minimum resolution of the servers clock time in milliseconds. This is usually reported as 0 (zero). The only time this statistic should be considered is if the number reported is large. If the minimum resolution of the server clock is larger than the likely interval for some of the timer-based statistics, those statistics may be inflated. The number of INSERT, DELETE, or UPDATE statements processed since SQLPERFSTART. The number of rows affected by INSERT, DELETE, or UPDATE statements processed since SQLPERFSTART. The number of SELECT statements processed since SQLPERFSTART. The number of rows selected since SQLPERFSTART. The number of user transactions since SQLPERFSTART. For example, suppose an application had run the following statements: SQLSetConnectOption(hdbc, SQLAUTOCOMMIT, SQLAUTOCOMMITON) SQLTransact(henv, hdbc, SQLROLLBACK) This constitutes two user transactions. Even though the second transaction was rolled back, it still counted as a transaction. Also, when an ODBC application is running with SQLAUTOCOMMITON, each individual command is considered a transaction. The number of SQLPrepare functions executed since SQLPERFSTART. The number of SQLExecDirect functions executed since SQLPERFSTART. The number of SQLExecute functions executed since SQLPERFSTART. The number of times the driver has opened a server cursor since SQLPERFSTART. The number of rows in the result sets opened by cursors since SQLPERFSTART. Application profile statistics The number of rows actually retrieved through the driver from cursors since SQLPERFSTART. Here is the equation used to figure the percentage of cursor used: For example, if an application causes the driver to open a server cursor to do select count() from authors, 23 rows are in the result set for the select. If the application then only fetches three of these rows, CursorUsed / CursorSize is 3/23, so PercentCursorUsed is 13.043478. Here is the equation used to figure the average fetch time: Here is the equation used to figure average cursor size: Here is the equation used to figure average number of cursors used: The cumulative amount of time it took fetches against server cursors to complete. The number of fetches done against server cursors since SQLPERFSTART. The number of statement handles currently open on all connections open in the driver. The maximum number of concurrently opened statement handles since SQLPERFSTART. The number of statement handles that have been opened since SQLPERFSTART. Connection Statistics These variables profile the connections to SQL Server opened by the application. The number of TDS packets sent to SQL Server by the driver since SQLPERFSTART. Large commands may take multiple buffers, so if a large command is sent to the server that filled six packets, ServerRndTrips would be incremented by one, BuffersSent by six. The number of TDS packets received by the driver from SQL Server since the application started using the driver. The number of bytes of data sent to SQL Server in TDS packets since the application started using the driver. The number of bytes of data in TDS packets received by the driver from SQL Server since the application started using the driver.

No comments:

Post a Comment