# SQLAlchemy 0.5.4p2 Documentation

Search:
Version: 0.5.4p2 Last Updated: 05/26/2009 16:24:44

# SQL Server

Support for the Microsoft SQL Server database.

## Driver

The MSSQL dialect will work with three different available drivers:

- pyodbc - http://pyodbc.sourceforge.net/. This is the recommeded driver.
- pymssql - http://pymssql.sourceforge.net/
- adodbapi - http://adodbapi.sourceforge.net/

Drivers are loaded in the order listed above based on availability.

If you need to load a specific driver pass `module_name` when creating the engine:

    engine = create_engine('mssql://dsn', module_name='pymssql')

`module_name` currently accepts: `pyodbc`, `pymssql`, and `adodbapi`.

Currently the pyodbc driver offers the greatest level of compatibility.

## Connecting

Connecting with create_engine() uses the standard URL approach of `mssql://user:pass@host/dbname[?key=value&key=value...]`.

If the database name is present, the tokens are converted to a connection string with the specified values. If the database is not present, then the host token is taken directly as the DSN name.

Examples of pyodbc connection string URLs:

- mssql://mydsn - connects using the specified DSN named `mydsn`. The connection string that is created will appear like:

      dsn=mydsn;TrustedConnection=Yes

- mssql://user:pass@mydsn - connects using the DSN named `mydsn` passing in the `UID` and `PWD` information. The connection string that is created will appear like:

      dsn=mydsn;UID=user;PWD=pass

- mssql://user:pass@mydsn/?LANGUAGE=us_english - connects using the DSN named `mydsn` passing in the `UID` and `PWD` information, plus the additional connection configuration option `LANGUAGE`. The connection string that is created will appear like:

      dsn=mydsn;UID=user;PWD=pass;LANGUAGE=us_english

- mssql://user:pass@host/db - connects using a connection string dynamically created that would appear like:

      DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass

- mssql://user:pass@host:123/db - connects using a connection string that is dynamically created, which also includes the port information using the comma syntax. If your connection string requires the port information to be passed as a `port` keyword see the next example. This will create the following connection string:

      DRIVER={SQL Server};Server=host,123;Database=db;UID=user;PWD=pass

- mssql://user:pass@host/db?port=123 - connects using a connection string that is dynamically created that includes the port information as a separate `port` keyword. This will create the following connection string:

      DRIVER={SQL Server};Server=host;Database=db;UID=user;PWD=pass;port=123

If you require a connection string that is outside the options presented above, use the `odbc_connect` keyword to pass in a urlencoded connection string. What gets passed in will be urldecoded and passed directly.

For example:

    mssql:///?odbc_connect=dsn%3Dmydsn%3BDatabase%3Ddb

would create the following connection string:

    dsn=mydsn;Database=db

Encoding your connection string can be easily accomplished through the python shell. For example:

    >>> import urllib
    >>> urllib.quote_plus('dsn=mydsn;Database=db')
    'dsn%3Dmydsn%3BDatabase%3Ddb'

Additional arguments which may be specified either as query string arguments on the URL, or as keyword argument to `create_engine()` are:

- auto_identity_insert - enables support for IDENTITY inserts by automatically turning IDENTITY INSERT ON and OFF as required. Defaults to `True`.
- query_timeout - allows you to override the default query timeout. Defaults to `None`. This is only supported on pymssql.
- text_as_varchar - if enabled this will treat all TEXT column types as their equivalent VARCHAR(max) type. This is often used if you need to compare a VARCHAR to a TEXT field, which is not supported directly on MSSQL. Defaults to `False`.
- use_scope_identity - allows you to specify that SCOPE_IDENTITY should be used in place of the non-scoped version @@IDENTITY. Defaults to `False`. On pymssql this defaults to `True`, and on pyodbc this defaults to `True` if the version of pyodbc being used supports it.
- has_window_funcs - indicates whether or not window functions (LIMIT and OFFSET) are supported on the version of MSSQL being used. If you’re running MSSQL 2005 or later turn this on to get OFFSET support. Defaults to `False`.
- max_identifier_length - allows you to se the maximum length of identfiers supported by the database. Defaults to 128. For pymssql the default is 30.
- schema_name - use to set the schema name. Defaults to `dbo`.

## Auto Increment Behavior

`IDENTITY` columns are supported by using SQLAlchemy `schema.Sequence()` objects. In other words:

    Table('test', mss_engine,
           Column('id', Integer,
                  Sequence('blah',100,10), primary_key=True),
           Column('name', String(20))
         ).create()

would yield:

    CREATE TABLE test (
      id INTEGER NOT NULL IDENTITY(100,10) PRIMARY KEY,
      name VARCHAR(20) NULL,
      )

Note that the `start` and `increment` values for sequences are optional and will default to 1,1.

- Support for `SET IDENTITY_INSERT ON` mode (automagic on / off for `INSERT` s)
- Support for auto-fetching of `@@IDENTITY/@@SCOPE_IDENTITY()` on `INSERT`

## Collation Support

MSSQL specific string types support a collation parameter that creates a column-level specific collation for the column. The collation parameter accepts a Windows Collation Name or a SQL Collation Name. Supported types are MSChar, MSNChar, MSString, MSNVarchar, MSText, and MSNText. For example:

    Column('login', String(32, collation='Latin1_General_CI_AS'))

will yield:

    login VARCHAR(32) COLLATE Latin1_General_CI_AS NULL

## LIMIT/OFFSET Support

MSSQL has no support for the LIMIT or OFFSET keysowrds. LIMIT is supported directly through the `TOP` Transact SQL keyword:

    select.limit

will yield:

    SELECT TOP n

If the `has_window_funcs` flag is set then LIMIT with OFFSET support is available through the `ROW_NUMBER OVER` construct. This construct requires an `ORDER BY` to be specified as well and is only available on MSSQL 2005 and later.

## Nullability

MSSQL has support for three levels of column nullability. The default nullability allows nulls and is explicit in the CREATE TABLE construct:

    name VARCHAR(20) NULL

If `nullable=None` is specified then no specification is made. In other words the database’s configured default is used. This will render:

    name VARCHAR(20)

If `nullable` is `True` or `False` then the column will be `NULL` or ``NOT NULL` respectively.

## Date / Time Handling

For MSSQL versions that support the `DATE` and `TIME` types (MSSQL 2008+) the data type is used. For versions that do not support the `DATE` and `TIME` types a `DATETIME` type is used instead and the MSSQL dialect handles converting the results properly. This means `Date()` and `Time()` are fully supported on all versions of MSSQL. If you do not desire this behavior then do not use the `Date()` or `Time()` types.

## Compatibility Levels

MSSQL supports the notion of setting compatibility levels at the database level. This allows, for instance, to run a database that is compatibile with SQL2000 while running on a SQL2005 database server. `server_version_info` will always retrun the database server version information (in this case SQL2005) and not the compatibiility level information. Because of this, if running under a backwards compatibility mode SQAlchemy may attempt to use T-SQL statements that are unable to be parsed by the database server.

## Known Issues

- No support for more than one `IDENTITY` column per table
- pymssql has problems with binary and unicode data that this module does not work around