Microsoft SQL Server 2000 Windows CE Edition

 SQL Server CE Books Online

Technical Support

  • Microsoft Product Support Services (PSS)
  • Microsoft SQL Server Support
  • Knowledge Base (KB) Search
  • Microsoft Windows Hardware Compatibility List
  • Troubleshooting

Microsoft Accessibility Web Site

MSDN Online

Microsoft TechNet

Microsoft SQL Server Product Web Site

Samples


About SQL Server CE Books Online

This section provides general information about using SQL Server CE Books Online, accessibility information, and additional resources for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).


Documentation Conventions

The following conventions are used in SQL Server CE Books Online to distinguish elements of text.

Convention | Used for
UPPERCASE | Transact-SQL keywords and SQL elements.
Initial Capitals | Paths and file names.
Bold | Database names, table names, column names, stored procedures, command-prompt utilities, menus, commands, dialog box options, programming elements, and text that must be typed exactly as shown.
Italic | User-supplied variables, relationships, and phrasing.
Monospace
 Code samples, examples, display text, and error messages.


Using Books Online

SQL Server CE Books Online is the online documentation provided with Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). The topics in SQL Server CE Books Online are organized on the Contents tab in a hierarchical structure by subject or task.

Information in SQL Server CE Books Online appears in a window that contains three panes:

  • The Navigation pane is located on the left side of the window. This pane contains the Contents tab, the Index tab, Search tab, and the Favorites tab.

  • The Topic pane is located on the right side of the window. This pane displays the selected topic or the default topic.

  • The Toolbar pane is located below the SQL Server Books Online title bar.

You can find information in SQL Server CE Books Online by:

  • Navigating through the contents.

  • Typing a keyword in the index, a word or phrase and performing a search.

Here are some tips on navigating through SQL Server CE Books Online:

  • To return to the SQL Server CE Home page, click Home on the toolbar.

  • Colored, underlined text indicates links to other topics. To link to another topic, including Web pages, click the colored, underlined text.

  • If you use a particular topic often, you can add it to your favorites list.

  • For shortcut menu commands, right-click the Contents tab or Topic pane. For more information, see Using the Shortcut Menu Commands.

For more information about using SQL Server CE Books Online, see SQL Server Books Online.


Changing the Way Books Online Topics Are Displayed

There are several ways to easily change the size and position of the SQL Server CE Books Online window and the Navigation and Topic panes:

  • To resize the Navigation or Topic pane, point to the divider between the two panes. When the pointer changes to a double-headed arrow, drag the divider right or left.

  • To proportionately shrink or enlarge SQL Server CE Books Online, point to any corner of the window. When the pointer changes to a double-headed arrow, drag the corner.

  • To change the height or width of SQL Server CE Books Online, point to the top, bottom, left, or right edge of the window. When the pointer changes to a double-headed arrow, drag the edge.

  • To reposition SQL Server CE Books Online on your screen, click the title bar and drag the window to a new position.

When you open SQL Server CE Books Online, it appears with the size and position settings that were last specified.

To change formatting or styles for accessibility

  1. On the Options menu, click Internet Options, and then click Accessibility.

  2. In the Accessibility dialog box, select the options you want, and then click OK.

These changes do not apply to the Navigation pane or toolbar of SQL Server CE Books Online. This procedure also changes your accessibility settings for Microsoft® Internet Explorer 4.0.

To change the font size of a topic

  • On the Options menu, click Internet Options, and then click Fonts.

These changes do not apply to the Navigation pane or toolbar of SQL Server CE Books Online. This procedure also changes your font settings for Internet Explorer.

To change colors in the Topic pane of SQL Server CE Books Online

  1. In Microsoft Internet Explorer 4.0, on the View menu, click Internet Options. In Microsoft Internet Explorer 5.0, on the Tools menu, click Internet Options.

  2. On the General tab, click Colors.

  3. In the Colors dialog box, select the options you want, and then click OK.

  4. To apply the new color settings, in the Internet Options dialog box, click OK.

These changes do not apply to the Navigation pane or toolbar of SQL Server CE Books Online. This procedure also changes your color settings for Internet Explorer.


Using Accessibility Shortcut Keys in Books Online

The following table shows the keyboard shortcuts that can be used for navigation in SQL Server CE Books Online.

For more information about accessibility features and services, see http://www.microsoft.com/enable

For SQL Server CE Books Online
To | Press
Close SQL Server CE Books Online. | ALT+F4
Switch between SQL Server CE Books Online and other open windows. | ALT+TAB
Display the Options menu. | ALT+O
Change Internet Explorer settings. The Internet Options dialog box contains accessibility settings. To change these settings, click the General tab, and then click Accessibility. | ALT+O, and then press I
Hide or show the Navigation pane. | ALT+O, and then press T
Print a topic. | ALT+O, and then press P
Move back to the previous topic. | ALT+LEFT ARROW, or ALT+O, and then press B
Move forward to the next topic (provided you have just previously viewed it). | ALT+RIGHT ARROW, or ALT+O, and then press F
Turn on or off search highlighting. | ALT+O, and then press O
Switch between the Navigation pane and the Topic pane. | F6
Scroll through the table of contents, displaying each topic as you scroll. | ALT+UP ARROW, or ALT+DOWN ARROW
Scroll through a topic. | UP ARROW and DOWN ARROW, or PAGE UP and PAGE DOWN
Scroll through all the links in a topic or through all the options on a Navigation pane tab. | TAB

For the Contents Tab
To | Press
Display the Contents tab. | ALT+C
Open and close a book or folder. | PLUS SIGN and MINUS SIGN, or LEFT ARROW and RIGHT ARROW
Select a topic. | DOWN ARROW and UP ARROW
Display the selected topic. | ENTER

For the Index Tab
To | Press
Display the Index tab. | ALT+N
Type a keyword to search for. | ALT+W, and then type the word
Select a keyword in the list. | UP ARROW and DOWN ARROW
Display the associated topic. | ALT+D

For the Search Tab
To | Press
Display the Search tab. | ALT+S
Type a keyword to search for. | ALT+W, and then type the word
Start a search. | ALT+L
Select a topic in the results list. | ALT+T, and then UP ARROW and DOWN ARROW
Display the selected topic. | ALT+D
Search for a word or phrase in a topic. | CTRL+F
Search for a keyword in the result list of a prior search. | ALT+U
Search for words similar to the keyword. For example, to find words such as "running" and "runs" for the keyword "run". | ALT+M
Search only through topic titles. | ALT+R

For the Favorites Tab
To | Press
Display the Favorites tab. | ALT+I
Add the currently displayed topic to the Favorites list. | ALT+A
Select a topic in the Favorites list. | ALT+P, and then UP ARROW and DOWN ARROW
Display the selected topic. | ALT+D
Remove the selected topic from the list. | ALT+R


Using the Shortcut Menu Commands

The following table shows the commands on the shortcut menu that you can use to display and customize information.

Command | Description
Right-click in the table of contents, and then click Close All. | Closes all books or folders. This command only works if the Contents tab is displayed.
Right-click, and then click Print. | Prints the topic.

These commands can be accessed through the keyboard. You can press SHIFT+F10 to display the shortcut menu, and then click the appropriate shortcut keys. Or, you can enable mousekeys. Use a mousekey combination to display the shortcut menu, and then click the appropriate shortcut keys.


Additional Resources

This topic provides Internet resources for information about Microsoft® SQL Server™ and related products and technologies.

Resource | Address
Microsoft Technical Support Web site | http://support.microsoft.com/directory
MSDN® | http://msdn.microsoft.com
Professional Association for SQL Server | http://www.sqlpass.org/
SQL Server Magazine | http://www.sqlmag.com
Microsoft SQL Server Support | http://support.microsoft.com/support/sql
SQL Server TechNet Site | http://www.microsoft.com/technet/sql/
The Microsoft SQL Server Web site | http://www.microsoft.com/sql
The Microsoft Accessibility Web site | http://www.microsoft.com/enable


Accessibility for People with Disabilities

Microsoft is committed to making its products and services easier for everyone to use. This topic provides information about the following features, products, and services that make Microsoft® Windows®, Microsoft Windows NT®, and Microsoft SQL Server™ CE more accessible for people with disabilities:

  • SQL Server CE Accessibility Features

  • Features and hints for customizing Windows or Windows NT

  • Microsoft services for people who are deaf or hard-of-hearing

  • Microsoft software documentation online, or on audiocassette, floppy disk, or CD

  • Third-party utilities that enhance accessibility

  • Other products and services for people with disabilities

    Note The information in this section applies only to users who license Microsoft products in the United States. If you obtained this product outside the United States, your package contains a subsidiary information card listing Microsoft support services telephone numbers and addresses. You can contact your subsidiary to find out whether the type of products and services described in this section are available in your area.

SQL Server CE Accessibility Features

In addition to Windows and Windows NT accessibility products and services, the following features make SQL Server CE more accessible for people with disabilities.

The Help Viewer

The Help Viewer for Microsoft HTML Help is the tool through which you read the product documentation. It is equipped with accessibility features, including shortcut keys for navigation and commands. The Help Viewer also uses some of the accessibility features of Microsoft Internet Explorer. For example, it allows you to change the colors of the display on your computer screen. For more information, see Using Books Online.

Customizing Windows or Windows NT

There are many ways you can customize Windows or Windows NT to make your computer more accessible.

Accessibility features have been built into Windows and Windows NT since the introduction of Windows 95. These features are useful for individuals who have difficulty typing or using a mouse, have moderately impaired vision, or who are deaf or hard-of-hearing. The features can be installed during setup, or you can add them later from your Windows installation disks.

For information about installing and using these features, look up "accessibility" in the Windows Help Index.

Some of the accessibility features built into Windows and Windows NT can be added to earlier versions of those products, and to MS-DOS, through Access Pack files. You can download these files or you can order them on disks from Microsoft. (See details in "Accessibility Notes and Utilities to Download" later in this section.)

You also can use Control Panel and other built-in features to adjust the appearance and behavior of Windows or Windows NT to suit varying vision and motor abilities. These include adjusting colors and sizes, sound volume, and the behavior of the mouse and keyboard.

In Windows 98, the majority of accessibility settings can be set through the Accessibility Wizard or Control Panel. The Accessibility Wizard presents features sorted by disability, making it easy to customize Windows to each individual's needs. The Accessibility Wizard also enables you to save your settings to a file that can be used on another computer.

Dvorak keyboard layouts make the most frequently typed characters on a keyboard more accessible if you have difficulty using the standard QWERTY layout. There are three Dvorak layouts: one if you are a two-handed user, one if you type with your left hand only, and one if you type with your right hand only. You do not need to purchase any special equipment to use these features.

The specific features available, and whether they are built-in or must be obtained separately, depend on which operating system you are using.

For full documentation on the accessibility features available in the operating system you are using, obtain the documents listed below. Accessibility features are also documented in the Microsoft Windows 95 Resource Kit, the Microsoft Windows 98 Resource Kit and the Microsoft Windows NT Resource Kit.

Accessibility Notes and Utilities to Download

The following documents explain how to customize Microsoft Windows and Windows NT for users with disabilities. Specific instructions for downloading the files follow this list.

For | You Need
Customizing Windows for Individuals with Disabilities (describes all of the other documents in this list and includes links to download them; this article will be updated when new versions of Microsoft operating systems are released) | Microsoft Knowledge Base article Q165486.
Customizing Microsoft® Windows® 95 for individuals with disabilities | Cst_W95.exe
Customizing Microsoft® Windows NT® 4.0 for individuals with disabilities | Cst_NT4.exe
Customizing Microsoft Windows NT 3.1 and 3.5 for individuals with disabilities (includes Access Pack for Microsoft Windows NT, which provides features for people who have difficulty using a keyboard or mouse, or who are deaf or hard-of-hearing) | Cst_NT3x.exe
Customizing Microsoft Windows 3.1 for individuals with disabilities | Cst_W3x.exe
Customizing Microsoft Windows for Workgroups 3.1 for individuals with disabilities | Cst_WG3x.exe
Customizing Microsoft Windows 3.0 for individuals with disabilities | Cst_W30.exe
Access Pack for Microsoft Windows 3.0 and 3.1, which provides features for people who have difficulty using a keyboard or mouse, or who are deaf or hard-of-hearing | ACCP.EXE
Dvorak keyboard layouts for people who type with one hand (already included in Windows NT 3.5 and later) | GA0650.EXE

Downloading the Files

If you have a modem or another type of network connection, you can download the accessibility files from the following network services:

  • Microsoft Accessibility Microsoft Web Site.

  • Support online from Microsoft Technical Support at Microsoft Web Site. Choose the appropriate application from the list labeled "My search is about" (or choose "All Products) and enter "Q165486" in the text box labeled "My question is." The search results will display a link to the Knowledge Base article, "Customizing Windows for Individuals with Disabilities," which includes links to all of the documents listed above.

  • For other accessibility articles, choose the appropriate application from the list labeled "My search is about" and enter "kbenable" in the text box labeled "My question is."

  • Microsoft Download Service (MSDL), which you can reach by calling (425) 936-6735 any time except between 1:00 A.M. and 2:30 A.M. Pacific time.

  • MSDL supports 1200, 2400, 9600, or 14400 baud rates (V.22bis, V.32, V.32bis and V.42), with 8 data bits, no parity, and 1 stop bit. MSDL does not support 28800, 56K or ISDN connections.
Microsoft Services for People Who Are Deaf or Hard-of-Hearing

If you are deaf or hard-of-hearing, complete access to Microsoft product and customer services is available through a text telephone (TTY/TDD) service.

Customer Service

You can contact the Microsoft Sales Information Center on a text telephone by dialing (800) 892-5234 between 6:30 A.M. and 5:30 P.M. Pacific time.

Technical Assistance

For technical assistance in the United States, you can contact Microsoft Technical Support on a text telephone at (425) 635-4948 between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday, excluding holidays. In Canada, dial (905) 568-9641 between 8:00 A.M. and 8:00 P.M. Eastern time, Monday through Friday, excluding holidays. Microsoft support services are subject to the prices, terms, and conditions in place at the time the service is used.

Microsoft Documentation in Alternative Formats

In addition to the standard forms of documentation, many Microsoft products are available in other formats to make them more accessible.

The documentation for SQL Server CE is available in an online format. For more information, see Using Books Online.

If you have difficulty reading or handling printed documentation, you can obtain many Microsoft publications from Recording for the Blind & Dyslexic, Inc. RFB&D distributes these documents to registered, eligible members of their distribution service, either on audio cassettes or on floppy disks. The RFB&D collection contains more than 80,000 titles, including Microsoft product documentation and books from Microsoft Press. You can download many of these books from the Microsoft Accessibility Web site at Microsoft Web Site

For more information, contact Recording for the Blind & Dyslexic at the following address or phone numbers:

Recording for the Blind & Dyslexic, Inc.
20 Roszel Road
Princeton, NJ 08540 		Phone:
Fax:
Web: 		(609) 452-0606
(609) 987-8116
http://www.rfbd.org/

Utilities to Enhance Accessibility

A wide variety of hardware and software products are available to make personal computers easier to use for people with disabilities. Among the different types of products available for the MS-DOS®, Windows, and Windows NT operating systems are:

  • Programs that enlarge or alter the color of information on the screen for people with visual impairments

  • Programs that describe information on the screen in Braille or synthesized speech for people who are blind or have difficulty reading

  • Hardware and software utilities that modify the behavior of the mouse and keyboard

  • Programs that enable people to "type" by using a mouse or their voice

  • Word or phrase prediction software that allow users to type more quickly and with fewer keystrokes

  • Alternative input devices, such as single switch or puff-and-sip devices, for people who cannot use a mouse or a keyboard
Getting More Accessibility Information

In addition to the features and resources already described in this section, other products, services, and resources for people with disabilities are available from Microsoft and other organizations.

Microsoft

Microsoft provides a catalog of accessibility aids that can be used with the Windows and Windows NT operating systems. You can obtain this catalog from our Web site or by phone:

Microsoft Sales Information Center
One Microsoft Way
Redmond, WA 98052-6393 		Web:
Voice telephone:
Text telephone: 		Microsoft Web Site
(800) 426-9400
(800) 892-5234

Macintosh Disability Solutions

For more information on products and services for the Macintosh for people with disabilities, contact:

Disability Solutions Web: http://www.apple.com/disability/

Trace R&D Center

The Trace R&D Center at the University of Wisconsin-Madison publishes a database of more than 18,000 products and other information for people with disabilities. The database is available on their site on the World Wide Web. The Trace R&D Center also publishes a book, titled Trace ResourceBook, which provides descriptions and photographs of about 2,000 products.

To obtain these materials, contact:

Trace R&D Center
University of Wisconsin-Madison
5901 Research Park Boulevard
Madison, WI 53719-1252 		Web:
Fax: 		http://trace.wisc.edu/
(608) 262-8848


Microsoft SQL Server 2000 Windows CE Edition Copyright and Disclaimer

This document, including sample applications herein, is provided for informational purposes only and Microsoft makes no warranties, either express or implied, in this document. Information in this document, including samples, URL and other Internet Web site references, is subject to change without notice. The entire risk of the use or the results of the use of this document remains with the user.

The primary purpose of a sample is to illustrate a concept, or a reasonable use of a particular statement or clause. Most samples do not include all of the code that would normally be found in a full production system, as a lot of the usual data validation and error handling is removed to focus the sample on a particular concept or statement. Technical support is not available for these samples or for the provided source code.

Unless otherwise noted, the example companies, organizations, products, people, and events depicted herein are fictitious and no association with any real company, organization, product, person, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

©1988-2001 Microsoft Corporation. All rights reserved.

Active Directory, ActiveSync, ActiveX, Microsoft, Microsoft Press, MSDN, MS-DOS, Visual Basic, Visual C++, Windows, and Windows NT are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.


Product Overview

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) extends the SQL Server product family to new devices, such as the Microsoft® Windows® CE-powered Pocket PC, while providing developers with a consistent programming model for rapid application development. It delivers essential relational database functionality in a small footprint: a robust data store; an optimizing query processor; and reliable, scalable bi-directional merge replication capabilities.


Rapid Application Development

SQL Server CE makes application development easy while providing a consistent development model and API set. Microsoft® Visual Basic® developers can rapidly develop Windows CE applications by using eMbedded Visual Basic and ADOCE. Microsoft® Visual C++® developers can leverage their existing skills to build sophisticated Windows CE-based database applications that target mobile and embedded solutions for sales force automation, service dispatch, point-of-sale, and shop floor management by using eMbedded Visual C++ and ADOCE or OLE DB.


High-Performance Database Engine

SQL Server CE offers rich relational database functionality in the small memory footprint on today's devices. Microsoft SQL Server developers will appreciate the robust feature set which includes:

  • A compatible SQL grammar with SQL Server 2000. Statements that run on SQL Server CE will, in general, run on SQL Server.

  • A wide range of data types, including:
    • TINYINT, SMALLINT, INTEGER, BIGINT

    • REAL, NUMERIC, FLOAT

    • BIT, BINARY, VARBINARY, IMAGE

    • UNICODE character data types NATIONAL CHARACTER, NATIONAL CHARACTER VARYING, NTEXT

    • MONEY, DATETIME, UNIQUEIDENTIFIER
  • 32 indexes per table, multicolumn indexes

  • NULL support

  • Nested transactions

  • 128-bit file level encryption

  • DDL: Create databases, alter tables, referential integrity, default values

  • DML: INSERT, UPDATE, DELETE

  • SELECT: SET Functions (aggregates), INNER/OUTER JOIN, subselect, GROUP BY/HAVING

  • Scrollable and forward-only cursors


Merge Replication

Merge replication in SQL Server CE is based on Microsoft® SQL Server™ 2000 merge replication and is ideally suited to portable devices because it enables data to be updated independently on the portable device and the server. The data on the device and the server can later be synchronized when the device is connected to the server.

Usage scenarios for merge replication include: read-only replication; data capture and upload; and replicate, update and synchronize. Most applications use these replication alternatives in combination. For example, a sales support application might use read-only replication to download a price list to a device while relying on data capture and upload to capture new orders on the device and easily upload them to a server. This same application might use replicate, update, and synchronize to download customer information, enabling information to be updated on the device. The resulting data could then be uploaded to the server.

The database administrator can use both horizontal and vertical filters to define and maintain unique subsets of data for different clients or groups of clients. Horizontal filters can be used to replicate a subset of the rows in a published table. Vertical filters can be used to replicate a subset of the columns in a published table.

General Stages to Merge Replication
  1. The database administrator creates a publication containing SQL Server data that is eligible for replication. A publication is simply a collection of articles. An article is simply a table that is eligible for replication.

  2. Once the database administrator defines the publication, a Windows CE application can subscribe to the publication by invoking the Replication Object. The published data is then downloaded to the SQL Server database on the Windows CE device.

  3. The data in the database can then be updated by applications running on the Windows CE device.

  4. The Windows CE application invokes the Replication Object to trigger synchronization. For example, the application can perform synchronization at the user's request or when the device first connects to the server. When synchronization is performed, the updates made to the replica are sent to the publisher where they are merged into the publisher's database. Similarly, changes made at the publisher since the initial download or most recent merge are sent to the Windows CE device where they are merged into the database.
Message-Based Internet Replication

SQL Server CE performs synchronization by establishing an HTTP connection to SQL Server through Microsoft Internet Information Services (IIS). It uses the authentication, authorization, and encryption services of IIS and can communicate with a SQL Server system located behind a firewall or proxy server. Replication can be performed over wired and wireless LANs and WANs. SQL Server CE Relay can be configured to use a desktop's network connection to communicate with SQL Server, eliminating the requirement for the Windows CE device to have a network card or modem. The communication protocol is well suited for wireless transports: compression reduces the amount of transmitted data and encryption safeguards sensitive user data. Following a communication failure, transmissions resume from the last successful transmission.


Remote Data Access (RDA)

Remote data access (RDA) provides a simple way for a Windows CE application to access SQL Server data located in a remote SQL Server 6.5, SQL Server 7.0, or SQL Server 2000 database. RDA can be used whether the Windows CE device is continuously connected or intermittently connected to the SQL Server system. Applications use RDA when they do not need the full functionally of merge replication. You can use RDA without configuring SQL Server replication or creating publications.

Applications can use RDA in two ways. The application can submit a SQL DML statement that is simply forwarded to the SQL Server system for execution. Alternatively, the application can submit a SQL query that returns a row set. The resulting row set is transmitted to the Windows CE device where it is stored in a table. All changes made by the application will be tracked, and at the request of the application, the updated rows will be sent back to the server where they are applied to the SQL Server database. RDA uses the authentication, authorization, and encryption services of IIS. RDA can be performed over wired and wireless LANs and WANs. SQL Server CE Relay can be configured to use a desktop's network connection to communicate with SQL Server, eliminating the requirement for the Windows CE device to have a network card or modem.


Getting Started

Microsoft® Windows® CE applications written in Microsoft® eMbedded Visual Basic® or Microsoft® eMbedded Visual C++® can use Microsoft® SQL Server™ CE. Developers who are familiar with these products in the desktop environment can leverage their experience to develop data-enabled Windows CE applications.


Installing, Configuring, and Connecting

The following table quickly identifies the tasks you must perform to run SQL Server CE.

Description | Task
Before you can create a new database or access an existing database, you must perform a number of setup tasks. You must install software on your development system, Microsoft Internet Information Services (IIS) system, and Windows CE device. In addition, you must configure the IIS system to enable connectivity for implementing remote data access (RDA) or replication. | Running Setup
There are a few ways to create a database. It is recommended that you use ADOXCE if you are creating a new database. Use OLE DB/CE when you want to write directly to the OLE DB layer. You can also create a database by using the AddSubscription method in replication. | Creating a database through ADOXCE Creating a database in OLE DB/CE AddSubscription Method
Implementing RDA | Implementing RDA
Implementing replication | Implementing Replication


Installing SQL Server CE

Microsoft® SQL Server™ CE uses up to five of the following systems: a Microsoft SQL Server system, a Microsoft Internet Information Services (IIS) system, a development system, a Microsoft ActiveSync® system, and a Microsoft Windows® CE device.

Microsoft SQL Server system

This is the system on which SQL Server is running. SQL Server CE supports both remote data access (RDA) and merge replication to SQL Server.

Internet Information Services (IIS) system

This is the system on which IIS is running. SQL Server CE RDA and merge replication communicate with SQL Server through IIS. IIS and SQL Server can reside on the same system.

Development system

This is the system on which your Windows CE application is developed.

ActiveSync system

SQL Server CE now includes a tool that eliminates the requirement for the Windows CE devices to have a network card for connectivity to SQL Server.

The new tool is called SQL Server CE Relay, and it works in parallel with ActiveSync when it is being used to talk to a Windows CE device using Serial, IR, or USB connections. SQL Server CE Relay acts as a proxy to allow TCP/IP communication from the Windows CE device to be transmitted to SQL Server using the network connection of the desktop computer.

For most developers, the ActiveSync system will be the same computer as the one used for the development system. Using the same computer allows the development tools to assist with the task of pushing prototype SQL Server CE applications into the Windows CE devices ready for debugging.

Windows CE device

This is the device on which your Windows CE application will be deployed after it is completed. During development, you will need to periodically download your application to a Windows CE device so that you can test its operation.


Hardware and Software Requirements

Hardware Requirements
Platform | Requirements
SQL Server system | See the operating system requirements in SQL Server Books Online.
IIS system | 120 MB of available disk space.
Development system | 30 MB of available disk space. The computer will need an additional 30 MB of temporary storage space for the setup files.
Windows CE device | Between 1 and 3 MB of available storage space, depending on processor type and components installed. The file sizes for the SQL Server CE components vary by processor type and Windows CE operating system version. Hard disk space requirements also depend on which SQL Server CE components you install.

Operating System Requirements
Platform | Supported operating systems
SQL Server system | See the operating system requirements in the SQL Server Books Online.
Development system | Microsoft Windows 98 Second Edition, Microsoft Windows Millennium (Me), Microsoft Windows NT® 4.0 with Service Pack 5 or later, or Microsoft Windows 2000. Windows CE desktop emulation requires Windows NT 4.0 or Windows 2000. Emulation is not supported on Windows 98. Microsoft ActiveSync 3.1 or later.
IIS system | Windows NT 4.0 with Service Pack 5 or later, or Windows 2000.
Windows CE device | Windows CE version 2.11 or later.

SQL Server Requirements
SQL Server | Supported SQL Server CE features
SQL Server 2000 | All features are supported including merge replication and RDA.
SQL Server version 6.5 with Service Pack 5 or later and SQL Server 7.0 | RDA is supported; replication is not supported.

Internet Information Services and Internet Explorer Requirements
Component | Requirements
Microsoft Internet Explorer 5.0 | Internet Explorer 5.0 or later is required on your development system to access SQL Server CE HTML Help. Internet Explorer 5.0 or later is required on your IIS system.
IIS | Replication and RDA require IIS 4.0 on Windows NT 4.0 or IIS 5.0 on Windows 2000.

ActiveSync Requirements
Component | Requirements
SSCERelay.exe | Windows 98 Second Edition, Windows Millennium (Me), Windows NT 4.0 with Service Pack 5 or later, or Windows 2000.

Windows CE Requirements
Platform | Windows CE operating system version
Handheld PC Pro (H/PC Pro) | 2.11 or later
Palm-size PC (P/PC) | 2.11 or later
Pocket PC | 3.0 or later
HPC 2000 | 3.0 or later*

Support for the HPC 2000 platform is not included in the eMbedded Visual Tools 3.0 product, or in the Platform Builder 3.0 product. To support the HPC 2000 platform, you will need to download the HPC 2000 SDK and add it to your system after the tools have been installed.

The HPC 2000 SDK is available at http://www.microsoft.com/mobile/downloads/dev_all.asp.


File Locations

Microsoft SQL Server CE must be installed on your development system, Microsoft Internet Information Services (IIS) system, and Microsoft Windows CE device.

Development System

The following SQL Server CE files are installed on the development system. These files are installed in the \Program Files\Microsoft SQL Server CE folder by default.

Location | Contents
\Device | A series of subfolders. Each subfolder contains five dynamic link libraries (Ssce10, Ssceca10, Sscecw10, Ssceinet, and Sscesock) for use with each of the processors supported by SQL Server CE. These subfolders also contain DllRegister.exe, a tool that registers the other DLLs. Not all components are contained in each subfolder.
\Encryption | A series of subfolders containing a dynamic link library (Rsaenh.dll) that implements the security features of SQL Server CE. There is a separate library for each processor and Windows CE operating system version supported by SQL Server CE.
\Inc | Include files for use with Microsoft eMbedded Visual Basic® and Microsoft eMbedded Visual C++®. Ca_mergex.h is the header for the SQL CE Microsoft ActiveX® objects. Ssceconsts.bas contains the SQL CE constants for eMbedded Visual Basic. Ssceoledb.h is the SQL CE header for OLE DB. It also includes an updated version of instcat.sql for remote data access to SQL Server 6.5.and sp_MSmakegeneration.sql for updating the SQL Server 2000 system stored procedures.
\Lib | A series of subfolders contain the library Ca_mergex.lib for the SQL Server CE ActiveX objects. There is a separate folder for each processor supported by SQL Server CE. A single type library (Ca_mergex.tlb) is located in the root of this directory. It describes the SQL Server CE RDA, replication, and engine objects.
\Relay | The SQL Server CE Relay extension to ActiveSync (SSCERelay.exe).
\Redist | A series of subfolders containing the components that you may need to include together with your application when you have finished it and are ready to deploy it.

Internet Information Services System

The following SQL Server CE files are installed on the Internet Information Services (IIS) system. Microsoft Data Access Components (MDAC) 2.6 must also be installed on the IIS system.

Location | Contents
\Program Files\Microsoft SQL Server CE\Server | SQL Server CE Server Agent component (sscesa10.dll)
\Program Files\Microsoft SQL Server CE\Server | SQL Server CE replication component (sscerp10.dll)
\Program Files\Microsoft SQL Server\80\com | SQL Server CE replication components

ActiveSync System

The following SQL Server CE files should be installed on your ActiveSync system, if this is not the same computer as your development computer.

Location | Contents
\Program Files\Microsoft SQL Server CE\ | SQL Server CE Relay component (SSCERelay.exe)

Windows CE Device

The following SQL Server CE files must be installed on the Windows CE device.

Location | Contents
\Windows | Ssce10.dll, Ssceca10.dll, Sscecw10.dll, Rsaenh.dll, ADOCE, and OLE DB files.
\Windows | Ssceinet.dll and Sscesock.dll are required on Windows CE 2.11 when replication or RDA is used.

SQL Server CE is dependent upon ADOCE 3.1 and OLE DB CE 1.0. These components exist by default on the HPC 2000 platform. For earlier Windows CE releases, SQL Server CE Setup installs these components when installing SQL Server CE.


Running Setup

Use SQL Server CE Setup to install SQL Server CE on your development system only after you have installed the Microsoft eMbedded Visual Tools, and after you have installed the Windows CE Platform Builder Toolkit.

If you use either RDA or replication, you will be able to install the Server Tools option on your IIS system either during the initial setup or from your development system after setup has completed.

Setup also installs SQL Server CE Relay on your development system so that you can use ActiveSync with a Serial, IR, or USB connection from your development computer. To use ActiveSync on another computer, install ActiveSync on the computer from your development system after setup has completed.

After you have built your application, install SQL Server CE on your Windows CE device. For more information, see Building Applications and Deploying SQL Server CE Applications.

Installation on a Development System

You must install the following software on your development system before you install SQL Server CE.

  • Microsoft ActiveSync 3.1 or later.

    For more information, see the Microsoft ActiveSync Product Web site.

  • Microsoft eMbedded Visual Tools 3.0.

    Install Microsoft eMbedded Visual Tools 3.0 from the disks labeled eMbedded Visual Tools 3.0 Disk 1 and eMbedded Visual Tools 3.0 Disk 2.

  • Install one of the following:
    1. Windows CE SDK

      When you install eMbedded Visual Tools 3.0, install at least one of the following SDKs: Handheld PC Pro (for Windows CE 2.11), Palm-size PC 1.2 (for Windows CE 2.11), Pocket PC (for Windows CE 3.0), or HPC 2000 (for Windows CE 3.0). You will be prompted to install these SDKs at the conclusion of eMbedded Visual Tools 3.0 setup.

    2. Microsoft Windows CE Platform Builder Toolkit 3.0.

      If you are building your own Windows CE devices with customized versions of the operating system that will contain a Microsoft SQL Server CE application.

      After you install the Platform Builder Toolkit you should also install the Platform Builder 3.0 Add-On Pack. You need the Add-On Pack in order to have the ADO-CE components installed properly for Platform Builder.

To set up SQL Server CE on your development computer

  1. This Microsoft Web site contains instructions and links for downloading and installing SQL Server CE on your computer http://www.microsoft.com/sql/productinfo/ceoverview.htm

  2. When prompted, select Development Tools.

    To set up an IIS system at the same time, select the Server Tools.

To uninstall the SQL Server CE components from your development computer

  1. In Control Panel, double-click Add/Remove Programs, and then click the Microsoft SQL Server CE program to remove.
Installation on an IIS System

If you use either RDA or replication, you must install some SQL Server CE server components on the IIS systems. This is required both during your application development, and during your application deployment after development has been completed.

You can install the server tools at the same time that you install the development tools by selecting the Server Tools check box on the setup screen.

Alternatively, in preparation for deployment, when the SQL Server CE toolkit was installed on your development computer, the server tools that match your SQL Server CE database engine were copied to a Redist subdirectory. You can use this directory to install the server tools to your development computers, if you did not install them during the initial setup.

To install the server tools from your development computer to your IIS system

  1. Navigate to the redist\server directory.

  2. Run server.exe and follow the directions of the setup program.

To uninstall the server tools from the IIS computer

  • In Control Panel, double-click Add/Remove Programs, and then click the Microsoft SQL Server CE program to remove.

    Caution At the same time that the server components were installed, the SQL Server CE setup program also installed the Microsoft Data Access Components (MDAC). The MDAC components are not uninstalled automatically because other programs may be dependent upon them. Remove the MDAC components only if you are certain they are not needed for other programs.

Support for Multi-Lingual Environments

The server tools include localized MDAC bits that can affect how setup dialogs and error messages are displayed. The language of the SQL Server CE setup package will determine the language of the MDAC bits in the server tools. If you have IIS servers configured for more than one UI language, you should download the corresponding languages of SQL Server CE onto separate development machines.

Installation on a SQL Server 2000 System

To use replication with a SQL Server 2000 system, run the sp_MSmakegeneration.sql script as described in Updating SQL Server System Stored Procedures.

Installation on an ActiveSync System

If you use ActiveSync with a Serial, IR, or USB connection to communicate between your Windows CE device and your desktop computer, you must install the SQL Server CE Relay on the ActiveSync system. This is required both during your application development and during your application deployment after development has been completed.

SQL Server CE Relay is installed automatically on your development system at the same time that you install the development tools.

Alternatively, in preparation for deployment, when the SQL Server CE toolkit was installed on your development computer, the SQL Server CE Relay that matches your SQL Server CE database engine was copied to a Redist subdirectory. You can use this directory to install the SQL Server CE Relay to another computer.

To install the SQL Server CE Relay component from your development computer to your ActiveSync system

  1. Navigate to the redist\relay directory.

  2. Copy sscerelay.exe to the \Program Files\Microsoft SQL Server CE\Relay directory on the ActiveSync computer.

  3. For instructions on configuring the SQL Server CE Relay component see Running SQL Server CE Relay.

To uninstall SQL Server CE Relay from the ActiveSync computer

  19. SQL Server CE Relay is not installed using a setup process, so there is not an uninstall process registered with the Windows Control Panel.
    1. Open an MS-DOS command window.

    2. Navigate to the \Program files\Microsoft SQL Server CE\Relay subdirectory on your ActiveSync machine.

    3. In the command window, enter the command: sscerelay\unregister.

    4. Delete the sscerelay.exe file.


Creating and Accessing a SQL Server CE Database

This section describes the methods of creating a standard or secure SQL Server CE database. It also discusses the cursors and transactions exposed by SQL Server CE.


Creating a Database

There are three ways you can create a database in SQL Server CE:

Creating a Database Through ADOXCE

Creating a Database in OLE DB/CE

Creating a Database Through the AddSubscription Method in Replication

Once you are connected to a database, you can also create a database through CREATE DATABASE SQL syntax.


Creating a Database Through ADOXCE

To create a database through ADOXCE, you use the catalog object. The catalog object exposes the Create method that takes an OLE DB connection string. For more information on ADOXCE, see the Microsoft® CE Data Access 3.1 documentation.

Dim cat As ADOXCE.Catalog

Set cat = CreateObject("ADOXCE.Catalog.3.1")

cat.Create "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0; data source=\NorthWind.sdf"

All databases created without specifying a locale identifier (LCID) are assigned the default locale identifier, 1033 (0x00000409) for U.S. English. To create a database with a locale identifier different from the default, specify the locale identifier. For example:

cat.Create "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0; data source=\test2.sdf;Locale Identifier=1041"


Creating a Database Through OLE DB/CE

The following example shows how to create a database through OLE DB/CE:

#include "c:\Windows CE Tools\dataaccess31\include\oledb.h"
#include "c:\Windows CE Tools\dataaccess31\include\oledberr.h"
#include "c:\Program Files\Microsoft SQL Server CE\inc\ssceoledb.h"
   ULONG      cProps   = 1;
   DBPROP      rgProps[1];
   DBPROPSET   PropSet;

   // Create the SQL Server CE provider
   //
   hr = CoCreateInstance(CLSID_SQLSERVERCE_1_0,NULL,CLSCTX_INPROC_SERVER,
                        IID_IDBDataSourceAdmin,(void**)&pIDBDataSourceAdmin);
   //Set the properties

   for (ULONG i = 0; i < cProps; i++ )
   {
      VariantInit(&rgProps[i].vValue);
      rgProps[i].dwOptions = DBPROPOPTIONS_REQUIRED;
      rgProps[i].colid = DB_NULLID;
   }

   rgProps[0].dwPropertyID      = DBPROP_INIT_DATASOURCE;
   rgProps[0].vValue.vt      = VT_BSTR;
   rgProps[0].vValue.bstrVal   = SysAllocString(OLESTR("\\Northwind.sdf"));

   PropSet.rgProperties      = rgProps;
   PropSet.cProperties      = cProps;
   PropSet.guidPropertySet   = DBPROPSET_DBINIT;

   hr = pIDBDataSourceAdmin->CreateDataSource(cProps,&PropSet,NULL,IID_IUnknown,NULL);


Creating a Database Through the AddSubscription Method in Replication

The Replication Object Method of the Merge object AddSubscription Method creates a new anonymous subscription to an existing publication. CREATE_DATABASE causes the SQL Server CE database to be created on the CE device, regardless of whether or not you are doing a merge replication.


Creating Secure Databases

SQL Server CE provides two ways to secure the local database: with a password, or with a password and encryption. Using a password on the local database will prevent programmatic access to the local database but will not prevent any data from being read as cleartext from the database file. Using a password and encryption will prevent programmatic access and will store user data in an encrypted form.

Note To enable encryption, you must specify a non-zero length database password and have the optional encryption components installed on your Windows CE device.

Database encryption is not available in the CE emulation.

SQL Server CE passwords can be up to 40 characters in length and can contain any letters, symbols, or digits. Note that the password for a SQL Server CE database is not a per-user password; there is only one password for a password-protected database.

Note SQL Server CE does not support password recovery.

There are three programmatic ways to create a secure database with SQL Server CE: with SQL Syntax, OLE DB, or a Connection String.


SQL Syntax

To create a password-protected database through SQL syntax, you specify databasepassword in your CREATE DATABASE statement. The password must follow the databasepassword keyword and be in single quotes.

To create an encrypted database through SQL syntax, you specify both databasepassword and 'encryption on'.

Encrypted database example:

Create Database "secure.sdf" databasepassword 'pass' encryption on


OLE DB

To create a password-protected database through OLE DB, you must pass the provider-specific property DBPROP_SSCEOLEDB_DBPASSWORD with the desired password.

To create an encrypted database through OLE DB, you must pass the provider-specific property DBPROP_SSCEOLEDB_ENCRYPTDATABASE as TRUE and specify a password by using the provider specific property DBPROP_SSCEOLEDB_DBPASSWORD.

To open a password-protected or encrypted database, you need only specify the database password. In OLE DB, this is done with the provider-specific property DBPROP_SSCEOLEDB_DBPASSWORD.


Connection String

To create a password-protected database with the ADOXCE Catalog object or with the SQL Server CE Replication ActiveX object, you need to specify the provider-specific connection property SSCE:Database Password in the connection string.

To create an encrypted database, you need to specify the provider-specific connection property SSCE:Database Password, and the provider-specific connection property SSCE:Encrypt Database. SSCE:Encrypt Database is a Boolean value that must be set to TRUE for an encrypted database.

Encrypted database example:

"provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;data source=\secure.sdf;SSCE:Database Password='pass';SSCE:Encrypt Database=TRUE"

Note The connection string must match the syntax specified in the Microsoft OLE DB Programmer's Reference.

To open a password-protected or encrypted database, you need only specify the database password. In a connection string, this is done with the provider-specific connection property SSCE:Database Password.


Changing Passwords or Encrypting/Decrypting a Database

SQL Server CE does not support changing the database password, or encrypting/decrypting a database in place. However, it is possible to change one or more of these settings by compacting the existing database into a new database. Database compaction is normally used to compress unused space in a database and search for database consistency errors. However, the process of compaction also allows options, such as database encryption or the database password, to be enabled or disabled. The ability to compact is exposed through two mechanisms in SQL Server CE: through the Compact method of the Engine ActiveX object or through the OLE DB provider directly using the ISSCECompact interface.


Cursor Types

SQL Server CE supports three types of cursors: base table, scrollable query, and forward-only. Each cursor type has unique capabilities, so it is important to choose the proper cursor for your application to work most effectively.

Base Table Cursors

Base table cursors are the lowest-level cursor available and are the only updateable cursors. These cursors work directly against the storage engine and are the fastest of all supported cursor types. This cursor supports the ability to use bookmarks to position on rows. Indices are supported to order the rows in a table as well as enable seeking to particular values and to restrict the rows based to a range of values within an index. Base table cursors can scroll forward or backward with minimal cost.

Base table cursors have dynamic membership, meaning that two cursors opened over the same table will immediately see insertions, deletions, and changes to the data (assuming both are in the same transaction scope). Base table cursors are also updateable. A client can use this cursor type to make changes to the underlying data.

Base table cursors cannot represent the results of a query. Instead, they reflect all the functionality available to a single table in the database engine. Results of queries, such as "SELECT * FROM tablename", are returned through one of the supported query result cursors.

To open a base table cursor in ADOCE, the adCmdTableDirect flag must be passed when the Recordset is opened. If this flag is not passed, the cursor will not be a base table cursor because ADOCE will implicitly prepend "SELECT * FROM " to the table name. Base table cursors used in ADOCE and SQL Server CE should use adOpenDynamic and adLockOptimistic.

Example

rs.Open "tablename", cn, adOpenDynamic, adLockOptimistic, adCmdTableDirect
Scrollable Query Cursors

Scrollable query cursors are the most functional query result cursors. They support scrolling backward and forward and using bookmarks to position on rows. They do not support updating or indices, however. Scrollable cursors do not see exogenous changes to the data; the results of the query are cached for the lifetime of the cursor. Though scrollable cursors are more functional than forward-only cursors, they are somewhat slower and use more memory. Clients should use scrollable cursors only if scrolling or bookmarking is necessary. SQL Server CE does not support updateable cursors from the query processor.

Scrollable cursors can use either adOpenStatic or adOpenKeyset. These cursors should use adLockReadOnly and not specify the adCmdTableDirect flag.

Example

rs.Open "SELECT * FROM tablename WHERE col1 > 2;", cn, adOpenStatic, adLockReadOnly
Forward-Only Cursors

Forward-only cursors are only returned by the query processor and are the fastest query-based cursor. These cursors do not support bookmarks, scrolling backward, indices, or updating. These cursors should be used in scenarios where speed and memory footprint are most important and query results are required. Restarting these cursors is relatively expensive because the query must be run again.

Forward-only cursors should use adOpenForwardOnly and adLockOptimistic. The adCmdTableDirect flag should not be used.

Example

rs.Open "SELECT * FROM tablename WHERE col1 > 2;", cn, adOpenForwardOnly, adLockOptimistic


Transactions

Transactions provide a mechanism to group a series of changes to a database in one atomic operation. After changes have been made to the database, these changes can be committed or aborted. SQL Server CE supports transactions and exposes the ability to use them through both ADOCE and the OLE DB layer directly. Transactions can also be nested. It is possible to have atomic units of work within a larger transaction that are individually committed or aborted. In SQL Server CE, transactions can be nested up to five levels deep. Transactions are usually described by four properties referred to as ACID:

  • Atomic: The unit of work is committed or rolled back as a single unit.

  • Consistent: Transactions enable the database to move from one consistent state to another. It is potentially possible to be in an inconsistent state during the transaction.

  • Isolated: Work within the scope of a transaction is not visible outside the scope of the transaction while the transaction is active. ANSI-defined isolation levels describe isolation quality for transactions. SQL Server CE supports an isolation level of "read committed" only.

  • Durable: After a transaction commits, the committed work survives even a system crash.

    Note SQL Server CE does not guarantee durability in all cases. It is possible to lose data in the event of a system crash.

SQL Server CE places some locking restrictions while a transaction is active on some DDL operations. Specifically, schema modifications during transactions place locks on the modified objects. This may prevent other operations from proceeding until the transaction is committed. For example, if a column is added to a table during a transaction, the table will remain locked until the transaction is completed.

Transactions also influence how cursors function. If a cursor is opened within a transaction with SQL Server CE, it exists within the scope of that transaction. If the transaction is aborted, the cursor ceases to exist. Within the context of ADOCE, this means that the Recordset would become a zombie and must be closed. If the transaction commits, the cursor still exists and is fully functional.

Sub TransactionExample()
  Dim cn As ADOCE.Connection
  Dim rs As ADOCE.Recordset
  Set cn = CreateObject("ADOCE.Connection.3.1")
  Set rs = CreateObject("ADOCE.Recordset.3.1")

  'Open a connection to an SQL Server 2000 CE Edition database
  cn.Open "provider=Microsoft.SQLServer.OLEDB.CE.1.0;data source=\ssce.sdf;"

  ' Begin a transaction
  cn.BeginTrans
  ' Commit that transaction
  cn.CommitTrans

  ' Demonstrate that opening a table outside of the transaction
  ' avoids potential problems with DBPROP_ABORTPRESERVE
  rs.Open "helloworld", cn, adOpenDynamic, adLockOptimistic
  cn.BeginTrans
  cn.RollbackTrans
  rs.MoveFirst  ' recordset is still functional
  rs.Close

  ' opening a rowset within a transaction that is aborted
  ' will zombie the rowset This is published in DBPROP_ABORTPRESERVE and
  ' can be accessed in ADOCE through the "Preserve on Abort" property
  cn.BeginTrans
  rs.Open "helloworld", cn, adOpenDynamic, adLockOptimistic
  Debug.Print rs.Properties("Preserve on Abort")
  Debug.Print rs.State
  cn.RollbackTrans
  rs.MoveFirst
End Sub


SQL Reference for SQL Server CE

SQL Server CE includes SQL grammar that allows you to query a database and insert, update, and delete data to tables in the database.

SQL Server CE also includes SQL Server CE Query Analyzer, a tool for querying tables in a database. For more information, see SQL Server CE Query Analyzer Overview.

This SQL Reference discusses the elements of SQL grammar available with SQL Server CE, as well as the following information.

For this information | See
SQL syntax conventions and query elements | SQL Overview
How to use SQL Server CE Query Analyzer | Using SQL Server CE Query Analyzer
How to use the isqlw_wce utility | Using the isqlw_wce Utility
Data types | Data Types
Functions | Functions
Information schema views | Information Schema
Operators | Operators
Reserved words | Reserved Words

All examples in the SQL Reference were tested using isqlw_wce and are not case sensitive.


SQL Overview

SQL grammar allows you to query a database and insert, update, or delete rows in tables in the database.

Syntax Conventions

The syntax diagrams in this reference use these conventions.

Convention | Used for
UPPERCASE | SQL Server CE keywords.
Italic | User-supplied parameters of SQL Server CE syntax.
| (vertical bar) | Separating syntax items within brackets or braces. You can choose only one of the items.
[ ] (brackets) | Optional syntax items. Do not type the brackets.
{} (braces) | Required syntax items. Do not type the braces.
[,...n] | Indicating that the preceding item can be repeated n number of times. The occurrences are separated by commas.
[ ...n] | Indicating that the preceding item can be repeated n number of times. The occurrences are separated by blanks.
bold | Database names, table names, column names, index names, stored procedures, utilities, data type names, and text that must be typed exactly as shown.
<label> ::= | The name for a block of syntax. This convention is used to group and label portions of lengthy syntax or a unit of syntax that can be used in more than one place within a statement. Each location in which the block of syntax can be used is indicated with the label enclosed in chevrons: <label>.

Query Elements

Identifiers, delimiters, and comments can be used to query a SQL Server CE database.

  1. Identifiers

    The database object names are known as identifiers. The object names are created when the object is defined; the identifier is used to reference the object.

    With SQL Server CE, you first must connect to a database that already exists in the device before you can execute queries. Consequently, you do not need object identifiers qualified with owner, database, or server names. Reference objects in one of these ways:

    object_name

    table_name.object_name

  2. Delimiters

    You must delimit identifiers when they do not comply with the rules for the format of regular identifiers or when reserved keywords are used.

    This table summarizes the use of delimiters in SQL Server CE.

    Delimiter | Use in SQL Server CE
    Brackets [ ] | Not supported
    Double quotation marks " " Noncompliant identifiers:
    • Multiple-word identifiers

    • Reserved words used as identifiers
    Single quotation marks ' ' | Data values

  3. Comments

    You can include text strings that should not be executed in the code as comments. Comments can be used to document code or to disable temporarily certain parts of a SQL statement.

    The SQL grammar provides these ways to delineate text as comments:

/* text_of_comment */
Indicates that the text between the /* and */ commenting characters is not evaluated by the server. text_of_comment is the character string containing the text of the comment.
-- text_of_comment
Indicates that the text after the two hypens is not evaluated by the server. text_of_comment is the character string containing the text of the comment.
Default Behavior

Queries executed through SQL Server CE Query Analyzer run with the following default behavior, which cannot be changed:

  • QUOTED_IDENTIFIER_ON

  • ANSI_NULLS_ON

  • ANSI_PADDING_ON

  • ANSI_NULL_DFLT_ON_ON

  • CONCAT_NULL_YIELDS_NULL_ON


SQL Server CE Query Analyzer Overview

The Query Analyzer for SQL Server CE is a graphical tool that allows you to perform the following tasks after you connect to a database:

  • Query objects by using the SELECT statement.

  • Create tables in a database.

  • Insert and delete rows in a table.

  • Modify existing data in a table.

  • Connect to another database on the device.

You can run SQL Server CE Query Analyzer directly by opening the isqlw_wce.exe application from the Windows directory or by executing the isqlw_wce utility from the command prompt.


Using SQL Server CE Query Analyzer

When you start SQL Server CE Query Analyzer, the Query Window opens two panes:

  • Editor pane

    The Editor pane is a text editor where you type SQL statements.

  • Results pane

    The Results pane returns information about the query, and has two tabs in which query information is returned. The Rowset tab displays any returned result set. The Messages tab displays messages as a result of the query.

    If the query was executed successfully, the Messages tab displays elapsed time and rows affected, if any. If the query resulted in an error or the query itself contained an error or unsupported SQL elements, the Messages tab displays a set of error information including the failed query and a short description.

    For information about errors, see SQL Server CE Errors.

Connecting to a Database

Before executing a query using SQL Server CE Query Analyzer, you first must connect to a database.

To connect to a database

  1. On the File menu, click Connect.

    A Connect to SQL Server CE window opens.

  2. In the Path box, type the database name or the complete path and database file name. Optionally, in the Password box, type a password.

  3. Click Connect (or if the database is new, click Create).

    The Connect to SQL Server CE window closes, and you can query the database to which you have just connected.

Executing SQL Statements

When using SQL Server CE Query Analyzer to execute SQL statements, the following conditions apply:

  • Only one window can be open and one database can be connected to at any time.

  • All queries must be typed in a single line in the Editor pane. SQL Server CE returns an error if multiple-line queries are executed.


Using the isqlw_wce Utility

Use the isqlw_wce utility to run SQL Server CE Query Analyzer from the command prompt.

To start SQL Server CE Query Analyzer, navigate to the directory in which the utility resides, and then run one of these commands:

isqlw_wce script_name.sql
--Opens a script in Query Analyzer

or

isqlw_wce database_name.sdf
--Opens a database in Query Analyzer

The .sql extension denotes a script file, and the .sdf extension denotes the database file name. These extensions are associated with the isqlw_wce utility.


+ (Add)

Adds two numbers. This addition arithmetic operator also can add a number, in days, to a date.

Syntax

expression + expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types in the numeric category, except the bit data type.

Result Types

Returns the data type of the argument with the higher precedence.

Examples

This example computes the total number of customers if the goal of adding 50 new customers is achieved. This query assumes that there are 90 customers listed in the Customers table in the Northwind database.

SELECT COUNT(CustomerID) + 50 AS "Target Total" FROM Customers

Here is the result set.

Target Total
------------
140


+ (Positive)

Is a unary operator that returns the positive value of a numeric expression.

Syntax

+ numeric_expression

Arguments

numeric_expression

Is any valid Microsoft® SQL Server™ expression of any of the data types in the numeric data type category, except the datetime data type.

Result Types

Returns the data type of numeric_expression, except that an unsigned tinyint expression is promoted to a smallint result.

Examples

This example shows how the positive and negative unary operators work. When a positive unary operator is set against a negative value, the returned value is negative (positive_value * negative_value = negative_value). When a negative unary operator is set against a negative value, the returned value is positive (negative_value * negative_value = positive_value).

SELECT (DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--Without any unary operator, the value returned is '-12'

SELECT +(DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--With the positive unary operator, the value returned is still '-12'

SELECT -(DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--With the negative unary operator, the value returned is '12'


+ (String Concatenation)

Is an operator in a string expression that concatenates two or more character or binary strings, columns, or a combination of strings and column names into one expression.

Syntax

expression + expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types in the character and binary data type category, except the image or ntext data type. Both expressions must be of the same data type, or one expression must be able to be implicitly converted to the data type of the other expression.

Result Types

Returns the data type of the argument with the highest precedence.

Examples

This example uses the + operator to get an alphabetic listing of all employees in the Northwind database.

SELECT FirstName + ' ' + LastName AS "Employee Listing" FROM Employees ORDER BY FirstName


- (Subtract)

Subtracts two numbers. This subtraction arithmetic operator can also subtract a number, in days, from a date.

Syntax

expression - expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category, except the bit data type.

Result Types

Returns the data type of the argument with the higher precedence.

Examples

This example uses the subtract arithmetic operator to get the number of days between the time a customer made an order and when the order was shipped.

SELECT (DATEPART(day, ShippedDate) - DATEPART(day, OrderDate)) FROM Orders WHERE OrderID = '10248'
--The value returned is '12'


- (Negative)

Is a unary operator that returns the negative value of a numeric expression.

Syntax

- numeric_expression

Arguments

numeric_expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category, except the datetime data type.

Result Types

Returns the data type of numeric_expression, except that an unsigned tinyint expression is promoted to a signed smallint result.

Examples

This example shows how the positive and negative unary operators work. When a positive unary operator is set against a negative value, the returned value is negative (positive_value * negative_value = negative_value). When a negative unary operator is set against a negative value, the returned value is positive (negative_value * negative_value = positive_value).

SELECT (DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--Without any unary operator, the value returned is '-12'

SELECT +(DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--With the positive unary operator, the value returned is still '-12'

SELECT -(DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--With the negative unary operator, the value returned is '12'


* (Multiply)

Multiplies two expressions (an arithmetic multiplication operator).

Syntax

expression * expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category, except the datetime data type.

Result Types

Returns the data type of the argument with the higher precedence.

Examples

This example determines the cost of a customer order by multiplying the quantity ordered by the unit price from the Order Details table in the Northwind database.

SELECT UnitPrice * Quantity AS "Total Cost" FROM "Order Details" WHERE ProductID = '11' AND OrderID = '10248'

Here is the result set.

Total Cost
----------
168


/ (Divide)

Divides one number by another (an arithmetic division operator).

Syntax

dividend / divisor

Arguments

dividend

Is the numeric expression to divide. dividend can be any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category, except the datetime data type.

divisor

Is the numeric expression to divide the dividend by. divisor can be any valid SQL Server expression of any of the data types of the numeric data type category, except the datetime data type.

Result Types

Returns the data type of the argument with the higher precedence.

Examples

This example uses the divide arithmetic operator to determine the average total cost for each order of product 51, which has 39 orders.

SELECT (SUM(UnitPrice * Quantity))/39 AS "Avg. Cost per Order" FROM "Order Details" WHERE ProductID = '51'

This is the result set.

Avg. Cost per Order
-------------------
1147.2461


% (Modulo)

Provides the remainder of one number divided by another.

Syntax

dividend % divisor

Arguments

dividend

Is the numeric expression to divide. dividend must be any valid Microsoft® SQL Server™ expression of the integer data type category. (A modulo is the integer that remains after two integers are divided.)

divisor

Is the numeric expression to divide the dividend by. divisor must be any valid SQL Server expression of any of the data types of the integer data type category.

Result Types

int

Examples

This example uses modulo to identify employees with even-numbered EmployeeID values.

SELECT EmployeeID, LastName, EmployeeID % 2 FROM Employees WHERE EmployeeID % 2 = '0'

Here is the result set.

EmployeeID   LastName   #2
----------   --------   ---
2            Fuller     0
4            Peacock    0
6            Suyama     0
8            Callahan   0


& (Bitwise AND)

Performs a bitwise logical AND operation between two integer values.

Syntax

expression & expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category. expression is an integer parameter that is treated and transformed into a binary number for the bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Examples

This example performs the bitwise AND operation between two integer columns.

CREATE TABLE bitwise (a_int_value int NOT NULL, b_int_value int NOT NULL)
INSERT bitwise VALUES (170, 75)
SELECT a_int_value & b_int_value FROM bitwise
--Returns 10

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise AND operation on these two values produces the binary result 0000 0000 0000 1010, which is decimal 10.

(A & B)
         0000 0000 1010 1010
         0000 0000 0100 1011
         -------------------
         0000 0000 0000 1010


| (Bitwise OR)

Performs a bitwise logical OR operation between two given integer values as translated to binary expressions within SQL statements.

Syntax

expression | expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category. expression is an integer that is treated and transformed into a binary number for the bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Examples

This example performs the bitwise OR operation between two integer columns.

CREATE TABLE bitwise (a_int_value int NOT NULL, b_int_value int NOT NULL)
INSERT bitwise VALUES (170, 75)
SELECT a_int_value | b_int_value FROM bitwise
--Returns 235

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise OR operation on these two values produces the binary result 0000 0000 1110 1011, which is decimal 235.

(A | B)
         0000 0000 1010 1010
         0000 0000 0100 1011
         -------------------
         0000 0000 1110 1011


^ (Bitwise Exclusive OR)

Performs a bitwise exclusive OR operation between two given integer values as translated to binary expressions within SQL statements.

Syntax

expression ^ expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer that is treated and transformed into a binary number for the bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Examples

This example performs the bitwise exclusive OR operation between two integer columns.

CREATE TABLE bitwise (a_int_value int NOT NULL, b_int_value int NOT NULL)
INSERT bitwise VALUES (170, 75)
SELECT a_int_value ^ b_int_value FROM bitwise
--Returns 225

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise exclusive OR operation on these two values produces the binary result 0000 0000 1110 0001, which is decimal 225.

(A ^ B)
         0000 0000 1010 1010
         0000 0000 0100 1011
         -------------------
         0000 0000 1110 0001


~ (Bitwise NOT)

Performs a bitwise logical NOT operation for one given integer value as translated to binary expressions within SQL statements.

Syntax

~ expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer that is treated and transformed into a binary number for the bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, a tinyint if the input values are tinyint, or a bit if the input values are bit.

Examples

This example performs the bitwise NOT operation between two integer columns.

CREATE TABLE bitwise (a_int_value int NOT NULL, b_int_value int NOT NULL)
INSERT bitwise VALUES (170, 75)
SELECT ~ a_int_value, ~ b_int_value FROM bitwise
--Returns -171 and -76


= (Equals)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if both operands are equal; otherwise, the result is FALSE.

Syntax

expression = expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the equals comparison operator to focus a search to a specific customer.

SELECT * FROM Orders WHERE CustomerID = 'VINET'


> (Greater Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a higher value than the right operand; otherwise, the result is FALSE.

Syntax

expression > expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the greater than comparison operator to find all orders in the Order Details table of the Northwind database with quantities of more than 100 units.

SELECT * FROM "Order Details" WHERE Quantity > '100'


< (Less Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a lower value than the right operand; otherwise, the result is FALSE.

Syntax

expression < expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the less than comparison operator to find all orders in the Order Details table of the Northwind database with quantities fewer than 10 units.

SELECT * FROM "Order Details" WHERE Quantity < '10'


>= (Greater Than or Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a higher or equal value than the right operand; otherwise, the result is FALSE.

Syntax

expression > = expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the greater than or equal to comparison operator to find all orders in the Order Details table of the Northwind database with quantities equal to or more than 100 units.

SELECT * FROM "Order Details" WHERE Quantity >= '100'


<= (Less Than or Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a lower or equal value than the right operand; otherwise, the result is FALSE.

Syntax

expression < = expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the less than or equal to comparison operator to find all orders in the Order Details table of the Northwind database with quantities equal to or less than 10 units.

SELECT * FROM "Order Details" WHERE Quantity <= '10'


<> (Not Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand is not equal to the right operand; otherwise, the result is FALSE.

Syntax

expression < > expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the not equal to comparison operator to find all orders in the Order Details table of the Northwind database with quantities not equal to 100 units.

SELECT * FROM "Order Details" WHERE Quantity <> '100'


!= (Not Equal To)

Tests whether one expression is not equal to another expression (a comparison operator). Functions the same as the Not Equal To (<>) comparison operator.


!< (Not Less Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand does not have a lower value than the right operand; otherwise, the result is FALSE.

Syntax

expression ! < expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the not less than comparison operator to find all orders in the Order Details table of the Northwind database with quantities equal to or more than 100 units.

SELECT * FROM "Order Details" WHERE Quantity !< '100'


!> (Not Greater Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand does not have a higher value than the right operand; otherwise, the result is FALSE.

Syntax

expression ! > expression

Arguments

expression

Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.

Result Types

Boolean

Examples

This example uses the not greater than comparison operator to find all orders in the Order Details table of the Northwind database with quantities equal to or less than 10 units.

SELECT * FROM "Order Details" WHERE Quantity !> '10'


ALL

Compares a scalar value with a single-column set of values.

Syntax

scalar_expression { = | <> | != | > | >= | !> | < | <= | !< } ALL ( subquery )

Arguments

scalar_expression

Is any valid Microsoft® SQL Server™ expression.

{ = | <> | != | > | >= | !> | < | <= | !< }

Is a comparison operator.

subquery

Is a subquery that returns a result set of one column. The data type of the returned column must be the same data type as the data type of scalar_expression.

Is a restricted SELECT statement (the ORDER BY clause, the COMPUTE clause, and the INTO keyword are not allowed).

Return Types

Boolean

Result Value

Returns TRUE when the comparison specified is TRUE for all pairs (scalar_expression, x) where x is a value in the single-column set; otherwise, returns FALSE.


ALTER TABLE

Modifies a table definition by altering, adding, or dropping columns and constraints.

Syntax

ALTER TABLE table_name
{ [ ALTER COLUMN column_name
{DROP DEFAULT
| SET DEFAULT constant_expression
| IDENTITY [ ( seed , increment ) ]
}
| ADD
{ < column_definition > | < table_constraint > } [ ,...n ]
| DROP
{ [ CONSTRAINT ] constraint_name
| COLUMN column }
] }

< column_definition > ::=
{ column_name data_type }
[ [ DEFAULT constant_expression ]
| IDENTITY [ ( seed , increment ) ]
]
[ROWGUIDCOL]
[ < column_constraint > ] [ ...n ] ]

< column_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| { PRIMARY KEY | UNIQUE }
| REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}

< table_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
{ ( column [ ,...n ] ) }
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}

Arguments

table_name

Is the name of the new table. Table names must conform to the rules for identifiers. table_name must be unique within the database. table_name can contain a maximum of 128 characters.

ALTER COLUMN

Specifies that the given column is to be changed or altered.

column_name

Is the name of a column in the table. Column names must conform to the rules for identifiers and must be unique in the table.

data_type

Specifies the column data type. For information on data types, see Data Types.

DEFAULT

Specifies the value provided for the column when a value is not explicitly supplied during an insert action. DEFAULT definitions can be applied to any column except those defined with the IDENTITY property. DEFAULT definitions are removed when the table is dropped. Only a constant value, such as a character string, or a date function can be used as a default.

IDENTITY

Indicates that the new column is an identity column. When a new row is added to the table, SQL Server CE provides a unique, incremental value for the column. Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned only to integer columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment, or neither. If neither is specified, the default is (1,1).

seed

Is the value used for the first row loaded into the table.

increment

Is the incremental value added to the identity value of the previous row loaded.

ADD

Specifies that one or more column definitions, computed column definitions, or table constraints are added.

DROP { [CONSTRAINT] constraint_name | COLUMN column_name }

Specifies that constraint_name or column_name is removed from the table.ROWGUIDCOL

Indicates that the new column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column.

The ROWGUIDCOL property does not enforce uniqueness of the values stored in the column. It also does automatically generate values for new rows inserted into the table.

CONSTRAINT

Is an optional keyword indicating the beginning of a PRIMARY KEY, UNIQUE, or FOREIGN KEY constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns.

constraint_name

Is the name of a constraint. constraint_name is optional and must be unique within a database. If constraint name is not specified, SQL Server CE generates a constraint name.

NULL | NOT NULL

Are keywords that specify whether null values are allowed in the column. NULL is not strictly a constraint but can be specified in the same manner as NOT NULL.

PRIMARY KEY

Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table.

UNIQUE

Is a constraint that provides entity integrity for a given column or columns through a unique index. Columns in a UNIQUE constraint must also be NOT NULL. A table can have multiple UNIQUE constraints.

Note SQL Server CE can use indexes to enforce PRIMARY KEY and UNIQUE constraints. Users, however, should not rely on this behavior, nor should they try to manipulate any indexes that are created as part of a constraint.

FOREIGN KEY...REFERENCES

Is a constraint that provides referential integrity for the data in the column. FOREIGN KEY constraints require that each value in the column exists in the specified column in the referenced table.ref_table

Is the name of the table referenced by the FOREIGN KEY constraint.

( ref_column [ ,...n ] )

Is a column or list of columns from the table referenced by the FOREIGN KEY constraint.

ON DELETE {CASCADE | NO ACTION}

Specifies what action takes place to a row in the table created, if that row has a referential relationship and the referenced row is deleted from the parent table. The default is NO ACTION.

If CASCADE is specified, a row is deleted from the referencing table if the corresponding referenced row is deleted from the parent table. If NO ACTION is specified, SQL Server raises an error, and the delete action on the referenced row in the parent table is rolled back.

For example, in the Northwind database, the Orders table has a referential relationship with the Customers table. The Orders.CustomerID foreign key references the Customers.CustomerID primary key.

If a DELETE statement is executed on a row in the Customers table and an ON DELETE CASCADE action is specified for Orders.CustomerID, SQL Server checks for one or more dependent rows in the Orders table. If any exist, the dependent rows in the Orders table are deleted, as well as the row referenced in the Customers table.

On the other hand, if NO ACTION is specified, SQL Server raises an error and rolls back the delete action on the row in the Customers table if there is at least one row in the Orders table that references it.

ON UPDATE {CASCADE | NO ACTION}

Specifies what action takes place to a row in the table created, if that row has a referential relationship and the referenced row is updated in the parent table. The default is NO ACTION.

If CASCADE is specified, the row is updated in the referencing table if the corresponding referenced row is updated in the parent table. If NO ACTION is specified, SQL Server raises an error, and the update action on the referenced row in the parent table is rolled back.

For example, in the Northwind database, the Orders table has a referential relationship with the Customers table: Orders.CustomerID foreign key references the Customers.CustomerID primary key.

If an UPDATE statement is executed on a row in the Customers table and an ON UPDATE CASCADE action is specified for Orders.CustomerID, SQL Server checks for one or more dependent rows in the Orders table. If any exist, the dependent rows in the Orders table are updated, as well as the row referenced in the Customers table.

Alternately, if NO ACTION is specified, SQL Server raises an error and rolls back the update action on the referenced row in the Customers table if there is at least one row in the Orders table that references it.

column

Is a column or list of columns, in parentheses, used in table constraints to indicate the columns used in the constraint definition.

n

Is a placeholder indicating that the preceding item can be repeated n number of times.

Examples

A. This example changes the seed and increment values on the IDENTITY column.

CREATE TABLE MyCustomers (CustID INTEGER IDENTITY (100,1) PRIMARY KEY, CompanyName NvarChar (50))
INSERT INTO MyCustomers (CompanyName) VALUES ('Microsoft')
ALTER TABLE MyCustomers ALTER COLUMN CustId IDENTITY (200, 2)

B. This example modifies the CompanyName column so that it has a default value.

ALTER TABLE MyCustomers ALTER COLUMN CompanyName SET DEFAULT 'Microsoft'

C. This example modifies the CompanyName column so that it does not have a default value.

ALTER TABLE MyCustomers ALTER COLUMN CompanyName DROP DEFAULT


AND

Combines two Boolean expressions and returns TRUE when both expressions are TRUE. When more than one logical operator is used in a statement, AND operators are evaluated first. You can change the order of evaluation by using parentheses.

Syntax

boolean_expression AND boolean_expression

Arguments

boolean_expression

Is any valid Microsoft® SQL Server™ expression that returns a Boolean value: TRUE, FALSE, or UNKNOWN.

Result Types

Boolean

Result Value

Returns TRUE when both expressions are TRUE.

Examples

This example uses AND to get the total cost of a specific order for a particular product.

SELECT UnitPrice * Quantity AS "Total Cost" FROM "Order Details" WHERE ProductID = '11' AND OrderID = '10248'


AVG

Returns the average of the values in a group. Null values are ignored.

Syntax

AVG ( [ ALL ] expression )

Arguments

ALL

Applies the aggregate function to all values. ALL is the default.

expression

Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.

Return Types

The return type is determined by the type of the evaluated result of expression.

Expression result | Return type
integer category | int
numeric category (p, s) | numeric(28, s) divided by numeric(10, 0)
money category | money
float and real category | float

Examples

This example determines the average freight shipped to the company with CustomerID 'VINET' in 1996.

--Get all OrderIDs for the VINET CustomerID
SELECT OrderID, ShippedDate FROM Customers WHERE CustomerID = 'VINET'

This is the result set.

OrderID     ShippedDate
----------------------------------
10248      1996-07-16 00:00:00.000
10274      1996-08-16 00:00:00.000
10295      1996-09-10 00:00:00.000
10737      1997-11-18 00:00:00.000
10739      1997-11-17 00:00:00.000

--Get the average freight for all orders shipped in 1996
SELECT AVG(Freight) AS "Average 1996 Freight" FROM Orders WHERE CustomerID = 'VINET' AND OrderID IN (10248, 10274, 10295)

Here is the result set.

Average 1996 Freight
--------------------
13.18


BETWEEN

Specifies a range to test.

Syntax

test_expression [ NOT ] BETWEEN begin_expression AND end_expression

Arguments

test_expression

Is the expression to test for in the range defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression.

NOT

Specifies that the result of the predicate be negated.

begin_expression

Is any valid Microsoft® SQL Server™ expression. begin_expression must be the same data type as both test_expression and end_expression.

end_expression

Is any valid SQL Server expression. end_expression must be the same data type as both test_expression and begin_expression.

AND

Acts as a placeholder indicating that test_expression should be within the range indicated by begin_expression and end_expression.

Result Types

Boolean

Result Value

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.

Remarks

To specify an exclusive range, use the greater than (>) and less than (<) operators . If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN.

Examples

This example identifies the products with 35 or fewer units in stock.

SELECT ProductID, ProductName FROM Products WHERE UnitsInStock BETWEEN '0' AND '35'


COLLATE

A clause that can be applied to a database definition to define the collation.

Syntax

COLLATE < collation_name >

< collation_name > :: =
< Windows_collation_name >

< Windows_collation_name >:: =
CollationDesignator_< ComparisonStyle >

< ComparisonStyle > :: =
CaseSensitivity_AccentSensitivity

Arguments

collation_name

Is the name of the collation to be applied to the database definition. collation_name can be only a specified Windows_collation_name.

Windows_collation_name

Is the collation name for Windows collation. For a list of Windows collation names supported in SQL Server CE, see the Remarks section.

CollationDesignator

Specifies the base collation rules used by the Windows collation. The base collation rules cover the following:

  • Alphabet or language whose sorting rules are applied when dictionary sorting is specified.

  • Code page used to store non-Unicode character data.

    For example, Latin1_General and French are collation designators that use code page 1252; Turkish is a collation designator that uses code page 1254.

CaseSensitivity

Specifies case-insensitive (CI). SQL Server CE supports only this option.

AccentSensitivity

Specifies accent-sensitive (AS). SQL Server CE supports only this option.

Remarks

All databases created without specifying the Windows collation name are assigned the default collation, Latin1_General. Use the optional COLLATE clause to specify a collation different from the default. For example, to specify a Spanish collation, use a query like this:

CREATE DATABASE "SpanishDB.sdf" DATABASEPASSWORD 'MyPwd' COLLATE Traditional_Spanish_CI_AS

This table lists supported Windows collation names. Ensure that the locale is supported on the device where the database is created.

Note Some collation values may not be supported on some devices.

Cp/Collation | Unique LCID | Windows collation name | Identical LCID group | Supported Windows Locales
1250 | 0x0000041C | Albanian |  | Albanian
1250 | 0x0000041a | Croatian |  | Croatian
1250 | 0x00000405 | Czech |  | Czech
1250 | 0x0000040e | Hungarian |  | Hungarian
1250 | 0x0001040e | Hungarian_Technical |  |
1250 | 0x00000415 | Polish |  | Polish
1250 | 0x00000418 | Romanian |  | Romanian
1250 | 0x0000041b | Slovak |  | Slovak
1250 | 0x00000424 | Slovenian |  | Slovenian
1251 | 0x00000419 | Cyrillic_General | 0x00000402, 0x00000423, 0x00000C1A, 0x0000081A | Bulgarian, Byelorussian, Russian, Serbian
1251 | 0x00000422 | Ukrainian |  | Ukrainian
1251 | 0x0000042f | FYRO Macedonian |  | FYRO Macedonian
1252 | 0x00010407 | German_PhoneBook |  | PhoneBook Sort with German
1252 | 0x0000040f | Icelandic |  | Icelandic
1252 | 0x00000406 | Danish_Norwegian | 0x00000414, 0x00000814 | Danish, Norwegian (Bokmål), Norwegian (Nyorsk)
1252 | 0x0000040b | Finnish_Swedish | 0x0000041d, 0x0000081d | Finnish, Swedish
1252 | 0x0000040c | French | 0x0000080c, 0x00000c0c, 0x0000140c, 0x0000180c, 0x0000100c | French (Belgium), French (Canada), French (Luxemburg), French (Standard), French (Switzerland)
1252 | 0x00000409 | Latin1_General | 0x00000436, 0x0000042D, 0x00000813, 0x00000C09, 0x00002809, 0x00001009, 0x00002409, 0x00001809, 0x00002009, 0x00001409, 0x00003409, 0x00001C09, 0x00002C09, 0x00000438, 0x00000437, 0x00000421, 0x00000416, 0x0000083e, 0x0000043e, 0x00000441, 0x00003009, 0x00000809. 0x00000403, 0x00000413, 0x00000407, 0x00000410, 0x00000816, 0x00000C07, 0x00001407, 0x00001007, 0x00000807, 0x00000810 | Afrikaans, Basque, Catalan, Dutch (Belgium), Dutch (Standard), English (Australia), English (Britain), English (Canada), English (Caribbean), English (Ireland), English (Jamaican), English (New Zealand), English (South Africa), English (United States), Faeroese, German (Austria), German (Liechtenstein), German (Luxemburg), German (Standard), German (Switzerland), Indonesian, Italian, Italian (Switzerland), Portuguese (Brazil), Portuguese (Standard)
1252 | 0x00000c0a | Modern_Spanish | 0x00002C0A, 0x0000400A, 0x0000340A, 0x0000240A, 0x0000140A, 0x00001C0A, 0x0000300A, 0x0000440A, 0x0000100A, 0x0000480A, 0x00004C0A, 0x0000180A, 0x00003C0A, 0x0000280A, 0x0000500A, 0x0000380A, 0x0000200A | Spanish (Argentina), Spanish (Bolivia), Spanish (Chile), Spanish (Colombia), Spanish (Costa Rica), Spanish (Dominican Republic), Spanish (Ecuador), Spanish (Guatemala), Spanish (Modern Sort), Spanish (Panama), Spanish (Paraguay), Spanish (Peru), Spanish (Uruguay), Spanish (Venezuela)
1252 | 0x0000040a | Traditional_Spanish | 0x0000080a |
1253 | 0x00000408 | Greek |  | Greek
1254 | 0x0000041f | Turkish |  | Turkish
1255 | 0x0000040d | Hebrew |  | Hebrew
1256 | 0x00000401 | Arabic | 0x00001401, 0x00003C01, 0x00000C01, 0x00000801, 0x00002C01, 0x00003401, 0x00003001, 0x00001001, 0x00001801, 0x00002001, 0x00004001, 0x00002801, 0x00001C01, 0x00003801, 0x00002401, 0x00000429, 0x00000420 | Arabic (Algeria), Arabic (Bahrain), Arabic (Egypt), Arabic (Iraq), Arabic (Jordan), Arabic (Kuwait), Arabic (Lebanon), Arabic (Libya), Arabic (Morocco), Arabic (Oman), Arabic (Qatar), Arabic (Saudi Arabia), Arabic (Syria), Arabic (Tunisia), Arabic (United Arab Emirates), Arabic (Yemen), Farsi, Urdu
1257 | 0x00000425 | Estonian |  | Estonian
1257 | 0x00000426 | Latvian |  | Latvian
1257 | 0x00000427 | Lithuanian |  | Lithuanian
1258 | 0x0000042a | Vietnamese |  | Vietnamese
874 | 0x0000041e | Thai |  | Thai
932 | 0x00000411 | Japanese |  | Japanese
932 | 0x00010411 | Japanese_Unicode |  |
936 | 0x00000804 | Chinese_PRC | 0x00000c04, 0x00001404, 0x00001004 | Chinese (Hong Kong S.A.R.), Chinese (China), Chinese (Singapore)
936 | 0x00020804 | Chinese_PRC_Stroke | 0x00020c04, 0x00021404, 0x00021004 | Stroke Sort with Chinese (China)
949 | 0x00000412 | Korean_Wansung |  | Korean
949 | 0x00010412 | Korean_Wansung_Unicode |  |
950 | 0x00030404 | Chinese_Taiwan_Bopomofo |  | Bopomofo with Chinese (Taiwan)
950 | 0x00000404 | Chinese_Taiwan_Stroke |  | Chinese (Taiwan)

Examples

This is an example of a Windows collation name.

Latin1_General_CI_AS

Collation uses the Latin1 General dictionary sorting rules, code page 1252. It is case-insensitive and accent-sensitive.


COUNT

Returns the number of items in a group.

Syntax

COUNT ( { [ ALL ] expression | * } )

Arguments

ALL

Applies the aggregate function to all values. ALL is the default.

expression

Is an expression of any type except uniqueidentifier, image, or ntext. Aggregate functions and subqueries are not permitted.

*

Specifies that all rows should be counted to return the total number of rows in a table. COUNT(*) takes no parameters. COUNT(*) does not require an expression parameter because, by definition, it does not use information about any particular column. COUNT(*) returns the number of rows in a specified table without eliminating duplicates. It counts each row separately, including rows that contain null values.

Return Types

integer

Examples

This example counts the discontinued items in the Products table in the Northwind database.

SELECT COUNT(ProductID) AS "Total Discontinued" FROM Products WHERE Discontinued = 'True'

Here is the result set.

Total Discontinued
--------------------
8


CREATE DATABASE

Creates a new database and the file used to store the database.

Note To execute the CREATE DATABASE statement, the user first must be connected to a database. For information on connecting to a database, see Using SQL Server CE Query Analyzer.

Syntax

CREATE DATABASE "database_name"
[DATABASEPASSWORD 'database_password'
[ENCRYPTION {ON|OFF}]
]
[COLLATE collation_name comparison_style]

database password ::= identifier

Arguments

"database_name"

Is the name of the new database. database_name is a file name and falls under the naming and size limitations of the operating system. Any valid character that can be used in a file name can be used for the database name. If a path name is not specified, the database will be created in the root directory. The file extension for a database name in SQL Server CE is .sdf.

'database_password'

Is the name of the password that allows for the database to be opened; database_password is optional. SQL Server CE returns an error if a user connects to a password-protected database without a password. database_password must be enclosed in single quotes.

If the optional ENCRYPTION ON keyword is passed, the database will be encrypted with 128-bit encryption.

collation_name

Specifies the default collation for the database. collation_name can only be a Windows collation. If not specified, the database is assigned the default collation of the device. For a list of collation names, see COLLATE.

comparison_style

Specifies the comparison style of characters. SQL Server CE only supports CI_AI (case insensitive and accent insensitive).

collation_name and comparison_style are not enclosed in single or double quotes.

Examples
A. Create a password-protected database

This example creates a database with a password.

CREATE DATABASE "\test1.SDF" DATABASEPASSWORD 'tst1_pwd'

When a user tries to connect to a password-protected database without supplying the correct password, SQL Server CE returns this error.

Error: 0x80040e4d DB_SEC_E_AUTH_FAILED
Minor Error: (25028)
Description: Authentication failed.
Interface defining error: IID_IDBInitialize
Param. 0:0
Param. 1:0
Param. 2:0
Param. 3:
Param. 4:
Param. 5:

For information about errors, see SQL Server CE Errors.

B. Create a database with collation specified

This example specifies a specific collation for the database being created.

CREATE DATABASE "SpanishDB.sdf" DATABASEPASSWORD 'MyPwd' COLLATE Traditional_Spanish_CI_AS


CREATE INDEX

Creates an index on a given table.

Syntax

CREATE [ UNIQUE ] INDEX index_name
ON table ( column [ ASC | DESC ] [ ,...n ] )

Arguments

UNIQUE

Creates a unique index (one in which no two rows are permitted to have the same index value) on a table.

SQL Server CE checks for duplicate values when the index is created (if data already exists) and checks each time data is added with an INSERT or UPDATE statement. If duplicate key values exist, the CREATE INDEX statement is canceled and an error is returned. A unique index can be created only on columns that are defined NOT NULL.

When a unique index exists, UPDATE or INSERT statements that would generate duplicate key values are rolled back, and SQL Server returns an error. This is true even if the UPDATE or INSERT statement changes many rows but causes only one duplicate.

SQL Server does not allow the creation of a unique index on columns that already include duplicate values. If attempted, SQL Server displays an error message; duplicates must be eliminated before a unique index can be created on the column(s).

index_name

Is the name of the index. Index names must be unique within a table but do not need to be unique within a database. Index names must follow the rules of identifiers.

table

Is the table that contains the column or columns to be indexed.

column

Is the column or columns to which the index applies. Specify two or more column names to create a composite index on the combined values in the specified columns. List the columns to be included in the composite index (in sort-priority order) inside the parentheses after table.

Note Columns consisting of the ntext or image data types cannot be specified as columns for an index.

Important All columns in a UNIQUE INDEX must have NOT NULL specified.

[ASC | DESC]

Determines the sort direction for the particular index column: ASC, the default, is ascending; DESC is descending.

n

Is a placeholder indicating that multiple columns can be specified for any particular index.

Remarks

Only the table owner can create indexes on that table. The owner of a table can create an index at any time, whether or not there is data in the table.

Examples

This example creates a unique index on the MyCustomers table.

CREATE TABLE MyCustomers (CustID INTEGER IDENTITY (100,1) PRIMARY KEY, CompanyName NvarChar (50))
CREATE UNIQUE INDEX idxCustId ON MyCustomers (CustId)


CREATE TABLE

Creates a new table.

Syntax

CREATE TABLE table_name
( { < column_definition > | < table_constraint > } [ ,...n ]
)

< column_definition > ::=
{ column_name data_type }
[ { DEFAULT constant_expression
| [ IDENTITY [ ( seed , increment ) ]
]
} ]
[ ROWGUIDCOL ]
[ < column_constraint > [ ...n ] ]

< column_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ PRIMARY KEY | UNIQUE ]
| REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}

< table_constraint > ::=
[ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
{ ( column [ ,...n ] ) }
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
}

Arguments

table_name

Is the name of the new table. Table names must conform to the rules for identifiers. table_name must be unique within the database. table_name can contain a maximum of 128 characters.

column_name

Is the name of a column in the table. Column names must conform to the rules for identifiers and must be unique in the table.

data_type

Specifies the column data type. For information on data types, see Data Types.

DEFAULT

Specifies the value provided for the column when a value is not explicitly supplied during an insert action. DEFAULT definitions can be applied to any column, except those defined as the IDENTITY property. DEFAULT definitions are removed when the table is dropped. A constant value, such as a character string, or a date function can be used as a default.

IDENTITY

Indicates that the new column is an identity column. When a new row is added to the table, SQL Server CE provides a unique, incremental value for the column. Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned only to integer columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

seed

Is the value used for the first row loaded into the table.

increment

Is the incremental value added to the identity value of the previous row loaded.

ROWGUIDCOL

Indicates that the new column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column.

The ROWGUIDCOL property does not enforce uniqueness of the values stored in the column. It also does automatically generate values for new rows inserted into the table.

CONSTRAINT

Is an optional keyword indicating the beginning of a PRIMARY KEY, UNIQUE, or FOREIGN KEY constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns.

constraint_name

Is the name of a constraint. constraint_name is optional and must be unique within a database. If constraint name is not specified, SQL Server CE generates a constraint name.

NULL | NOT NULL

Are keywords that specify whether null values are allowed in the column. NULL is not strictly a constraint but can be specified in the same manner as NOT NULL.

PRIMARY KEY

Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table.

UNIQUE

Is a constraint that provides entity integrity for a given column or columns through a unique index. Columns in a UNIQUE constraint must also be NOT NULL. A table can have multiple UNIQUE constraints.

Note SQL Server CE can use indexes to enforce PRIMARY KEY and UNIQUE constraints. Users, however, should not rely on this behavior nor should they try to manipulate any indexes that are created as part of a constraint.

FOREIGN KEY...REFERENCES

Is a constraint that provides referential integrity for the data in the column. FOREIGN KEY constraints require that each value in the column exists in the specified column in the referenced table.

ref_table

Is the name of the table referenced by the FOREIGN KEY constraint.

( ref_column [ ,...n ] )

Is a column, or list of columns, from the table referenced by the FOREIGN KEY constraint.

ON DELETE {CASCADE | NO ACTION}

Specifies what action takes place to a row in the table created, if that row has a referential relationship and the referenced row is deleted from the parent table. The default is NO ACTION.

If CASCADE is specified, a row is deleted from the referencing table if the corresponding referenced row is deleted from the parent table. If NO ACTION is specified, SQL Server raises an error and the delete action on the referenced row in the parent table is rolled back.

For example, in the Northwind database, the Orders table has a referential relationship with the Customers table. The Orders.CustomerID foreign key references the Customers.CustomerID primary key.

If a DELETE statement is executed on a row in the Customers table and an ON DELETE CASCADE action is specified for Orders.CustomerID, SQL Server checks for one or more dependent rows in the Orders table. If any exists, the dependent rows in the Orders table are deleted, as well as the row referenced in the Customers table.

On the other hand, if NO ACTION is specified, SQL Server raises an error and rolls back the delete action on the row in the Customers table if there is at least one row in the Orders table that references it.

ON UPDATE {CASCADE | NO ACTION}

Specifies what action takes place to a row in the table created, if that row has a referential relationship and the referenced row is updated in the parent table. The default is NO ACTION.

If CASCADE is specified, the row is updated in the referencing table if the corresponding referenced row is updated in the parent table. If NO ACTION is specified, SQL Server raises an error and the update action on the referenced row in the parent table is rolled back.

For example, in the Northwind database, the Orders table has a referential relationship with the Customers table: Orders.CustomerID foreign key references the Customers.CustomerID primary key.

If an UPDATE statement is executed on a row in the Customers table and an ON UPDATE CASCADE action is specified for Orders.CustomerID, SQL Server checks for one or more dependent rows in the Orders table. If any exists, the dependent rows in the Orders table are updated, as well as the row referenced in the Customers table.

Alternately, if NO ACTION is specified, SQL Server raises an error and rolls back the update action on the referenced row in the Customers table if there is at least one row in the Orders table that references it.

column

Is a column or list of columns, in parentheses, used in table constraints to indicate the columns used in the constraint definition.

Remarks
Constraints
  1. PRIMARY KEY Constraints
    • A table can contain only one PRIMARY KEY constraint.

    • Each PRIMARY KEY generates an index.

    • All columns defined within a PRIMARY KEY constraint must be defined as NOT NULL. If nullability is not specified, all columns participating in a PRIMARY KEY constraint have their nullability set to NOT NULL.
  2. UNIQUE Constraints
    • Each UNIQUE constraint generates an index.

    • All columns defined as a UNIQUE constraint must be defined as NOT NULL. If nullability is not specified, all columns defined as UNIQUE constraints have their nullability set to NOT NULL.
  3. FOREIGN KEY Constraints
    • When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; otherwise, a foreign key violation error message is returned.

    • FOREIGN KEY constraints can reference only tables within the same database.

    • FOREIGN KEY constraints can reference another column in the same table (a self-reference). However, FOREIGN KEY constraints cannot be used to create a self-referencing or circular FOREIGN KEY constraint with the CASCADE option.

    • The REFERENCES clause of a column-level FOREIGN KEY constraint can list only one reference column, which must have the same data type as the column on which the constraint is defined.

    • The REFERENCES clause of a table-level FOREIGN KEY constraint must have the same number of reference columns as the number of columns in the constraint column list. The data type of each reference column also must be the same as the corresponding column in the column list.

    • FOREIGN KEY constraints can reference only columns in PRIMARY KEY or UNIQUE constraints in the referenced table.
  4. Additional Constraint Information
    • An index created for a constraint cannot be dropped with the DROP INDEX statement; the constraint must be dropped with the ALTER TABLE DROP CONSTRAINT statement.

    • Constraint names must follow the rules for identifiers, except that the name cannot begin with a number sign (#). If the CONSTRAINT keyword and constraint_name is not supplied, a system-generated name is assigned to the constraint.

    • When a constraint is violated in an INSERT, UPDATE, or DELETE statement, the statement is terminated.
DEFAULT Definitions

A column can have only one DEFAULT definition, which can contain constant values or constant functions.

Nullability Rules Within a Table Definition

The nullability of a column determines whether or not that column can allow a null value (NULL) as the data in that column. NULL is not zero or blank: it means no entry was made or an explicit NULL was supplied, and it usually implies that the value is either unknown or not applicable.

Examples

This example creates a two-column table with an IDENTITY column as the PRIMARY KEY.

CREATE TABLE MyCustomers (CustID int IDENTITY (100,1) PRIMARY KEY, CompanyName nvarchar (50))

This example creates a one-column table with a PRIMARY KEY constraint.

CREATE TABLE MyCustomers2 (CustID int CONSTRAINT pkCustId PRIMARY KEY)

This example creates a table with one of its columns referencing a column in another table.

CREATE TABLE MyOrders (OrderID int, CustID int REFERENCES MyCustomers(CustID))


Data Types

Each column in a SQL Server CE table has a data type that specifies the type of data (such as integer, character, or money) that the column can hold.

Note Between SQL Server 2000 and SQL Server CE, minor differences may exist in how data types are promoted when the execution of a function results in an overflow or underflow. It may be necessary to perform explicit CAST in SQL Server 2000 to get the same behavior in SQL Server CE.

SQL Server CE supports the following data types.

Data Type | Description
bigint (INT 8) | Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807). Storage size is 8 bytes.
integer (INT 4) | Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
smallint (INT 2) | Integer data from –32,768 to 32,767. Storage size is 2 bytes.
tinyint (INT 1) | Integer data from 0 to 255. Storage size is 1 byte.
bit | Integer data with either a 1 or 0 value.
numeric (p, s) | Fixed-precision and scale-numeric data from -10^38 -1 through 10^38 –1. p specifies precision and can vary between 1 and 38. s specifies scale and can vary between 0 and p.
money | Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. Storage size is 8 bytes.
float(n) | Floating point number data from - 1.79E + 308 through 1.79E + 308. n is the number of bits used to store the mantissa of the float number in scientific notation and thus dictates the precision and storage size. n must be a value from 1 through 53. Storage size is 4 bytes if n is 1 to 24. Storage size is 8 bytes if n is 25 to 53.
real | Floating precision number data from -3.40E + 38 through 3.40E + 38. Storage size is 4 bytes.
datetime | Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0 - 59.
NATIONAL CHARACTER (n) Synonym nchar(n) | Fixed-length Unicode data with a maximum length of 255 characters. Default length = 1
NATIONAL CHARACTER VARYING (n) Synonym nvarchar(n) | Variable-length Unicode data with a length of 1 to 255 characters. Default length = 1
ntext | Variable-length Unicode data with a maximum length of (2^30 - 2) / 2 (536,870,911) characters. Storage size, in bytes, is two times the number of characters entered.
binary(n) | Fixed-length binary data with a maximum length of 510 bytes. Default length = 1
varbinary(n) | Variable-length binary data with a maximum length of 510 bytes. Default length = 1
image | Variable-length binary data with a maximum length of 2^30 – 1 (1,073,741,823) bytes.
uniqueidentifier | A globally unique identifier (GUID). Storage size is 16 bytes.
IDENTITY [(s, i)] | This is a property of a data column, not a distinct data type. Only data columns with data types of INTEGER can be used for IDENTITY columns. A table can have only one IDENTITY column. A seed and increment can be specified and the column cannot be updated. s (seed). Starting value i (increment). Increment value
ROWGUIDCOL | This is a property of a data column, not a distinct data type. It is a column in a table that is defined using the uniqueidentifier data type. A table can only have one ROWGUIDCOL column.


DATEADD

Returns a new datetime value based on adding an interval to the specified date.

Syntax

DATEADD ( datepart , number, date )

Arguments

datepart

Is the parameter that specifies on which part of the date to return a new value. The table lists the dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

number

Is the value used to increment datepart. If you specify a value that is not an integer, the fractional part of the value is discarded. For example, if you specify day for datepart and 1.75 for number, date is incremented by 1.

date

Is an expression that returns a datetime value or a Unicode character string in a date format. For more information about specifying dates, see datetime in Data Types.

If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

Return Types

datetime

Examples

This example adds two months to the OrderDate for 'Fictitious Company'.

CREATE TABLE MyOrders (OrderID int IDENTITY(100, 1) PRIMARY KEY, CompanyName nvarchar(50), OrderDate datetime)
INSERT INTO MyOrders (CompanyName, OrderDate) VALUES ('Fictitious Company', GETDATE())
SELECT DATEADD(month, 2, OrderDate) FROM MyOrders


DATEDIFF

Returns the number of date and time boundaries crossed between two specified dates.

Syntax

DATEDIFF ( datepart , startdate , enddate )

Arguments

datepart

Is the parameter that specifies on which part of the date to calculate the difference. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

startdate

Is the beginning date for the calculation. startdate is an expression that returns a datetime value or a Unicode character string in a date format.

If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if the two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

For more information about specifying dates, see datetime in Data Types.

enddate

Is the ending date for the calculation. enddate is an expression that returns a datetime value or a Unicode character string in a date format.

Return Types

integer

Examples

This example determines the number of days it took to ship the orders made by the company 'Vins et alcohols Chevalier', which has a CustomerID of 'VINET'.

SELECT OrderID, DATEDIFF (d, OrderDate, ShippedDate) AS "Shipping Time in Days" FROM Orders WHERE CustomerID = 'VINET'

This is the result set.
OrderID         Shipping Time in Days
-------------------------------------
10248           12
10274           10
10295           8
10737           7
10739           5


DATENAME

Returns a character string representing the specified datepart of the specified date.

Syntax

DATENAME ( datepart , date )

Arguments

datepart

Is the parameter that specifies the part of the date to return. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
weekday | dw
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

The weekday (dw) datepart returns the day of the week (such as Sunday or Monday).

date

Is an expression that returns a datetime value or a Unicode character string in a date format. Use the datetime data type for dates after January 1, 1753. Store them as character data for earlier dates. When entering datetime values, always enclose them in quotation marks. For more information about specifying dates, see datetime in Data Types.

If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

Return Types

nvarchar

Remarks

SQL Server automatically converts between character and datetime values as necessary, for example, when you compare a character value with a datetime value.

Examples

This example extracts the month name from the date returned by GETDATE.

CREATE TABLE MyOrders (OrderID int IDENTITY(100, 1) PRIMARY KEY, CompanyName nvarchar(50), OrderDate datetime)
INSERT INTO MyOrders (CompanyName, OrderDate) VALUES ('Fictitious Company', GETDATE())
SELECT DATENAME(month, OrderDate) AS 'Month Name' FROM MyOrders

Here is the result set:

Month Name
------------------------------
August


DATEPART

Returns an integer representing the specified datepart of the specified date.

Syntax

DATEPART ( datepart , date )

Arguments

datepart

Is the parameter that specifies the part of the date to return. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
weekday | dw
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

The week (wk, ww) datepart reflects changes made to SET DATEFIRST. January 1 of any year defines the starting number for the week datepart, for example: DATEPART(wk, 'Jan 1, xxxx') = 1, where xxxx is any year.

The weekday (dw) datepart returns a number that corresponds to the day of the week, for example: Sunday = 1, Saturday = 7. The number produced by the weekday datepart depends on the value set by SET DATEFIRST, which sets the first day of the week.

date

Is an expression that returns a datetime value or a character string in a date format. Use the datetime data type only for dates after January 1, 1753. Store dates as character data for earlier dates. When entering datetime values, always enclose them in quotation marks.

If you specify only the last two digits of the year, values less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

For more information about specifying dates, see datetime in Data Types.

Return Types

integer

Examples

This example assumes the month is August.

CREATE TABLE MyOrders (OrderID int IDENTITY(100, 1) PRIMARY KEY, CompanyName nvarchar(50), OrderDate datetime)
INSERT INTO MyOrders (CompanyName, OrderDate) VALUES ('Fictitious Company', GETDATE())
SELECT DATEPART(month, OrderDate) FROM MyOrders

Here is the result set:

-----------
8


DDL Statements

SQL Server CE supports the following Data Definition Language (DDL) statements.

Statement | Function
CREATE DATABASE | Creates a new database and the file used to store the database.
CREATE TABLE | Creates a new table.
ALTER TABLE | Modifies a table definition by altering, adding, or dropping columns and constraints.
CREATE INDEX | Creates an index on a given table.
DROP INDEX | Removes one or more indexes from the current database.
DROP TABLE | Removes a table definition and all data, indexes, and constraints for that table.

To delimit identifiers in SQL Server CE, you must use double quotes. Brackets are not supported. For more information, see SQL Overview.


DELETE

Removes rows from a table.

Syntax

DELETE
[ FROM ] table_name
[ WHERE < search_condition > ]

Arguments

FROM

Is an optional keyword that can be used between the DELETE keyword and the target table_name.

table_name

Is the name of the table from which the rows are to be removed.

WHERE

Specifies the conditions used to limit the number of rows that are deleted.

<search_condition>

Specifies the restricting conditions for the rows to be deleted. There is no limit to the number of predicates that can be included in a search condition.

Remarks

If a WHERE clause is not supplied, DELETE removes all the rows from the table.

If a search_condition is specified, then it is applied to each row of the table, and all rows for which the result of the search_condition is true are marked for deletion.

The search_condition is evaluated for each row of the table before any deletions occur.

All rows that are marked for deletion are deleted at the end of the DELETE statement prior to the checking of any integrity constraint.

The DELETE statement may fail if it violates a FOREIGN KEY constraint. If the DELETE removes multiple rows and any one of the removed rows violates a constraint, the statement is canceled, an error is returned, and no rows are removed.

Examples

A. Use DELETE with no parameters

This example deletes all rows from the customers table.

DELETE customers

B. Use DELETE on a set of rows

Because CompanyName may not be unique, this example deletes all rows in which CompanyName is "Eastern Connection".

DELETE FROM customers WHERE CompanyName = 'Eastern Connection'


DML Statements

SQL Server CE supports the following Data Manipulation Language (DML) statements.

Statement | Function
INSERT | Changes existing data in a table.
UPDATE | Adds a new row to a table.
DELETE | Removes rows from a table.

To delimit identifiers in SQL Server CE, you must use double quotes. Brackets are not supported. For more information, see SQL Overview.


DROP INDEX

Removes an index from the current database.

The DROP INDEX statement does not apply to indexes created by defining PRIMARY KEY or UNIQUE constraints (created by using the PRIMARY KEY or UNIQUE options of either the CREATE TABLE or ALTER TABLE statements). For more information about PRIMARY or UNIQUE KEY constraints, see CREATE TABLE.

Syntax

DROP INDEX 'table_name.index_name'

Arguments

table_name

Is the name of the table in which the indexed column is located. Table names must conform to the rules for identifiers.

index_name

Is the name of the index to be dropped. Index names must conform to the rules for identifiers.

Remarks

After DROP INDEX is executed, all the space previously occupied by the index is regained. This space then can be used for any database object.

DROP INDEX cannot be specified on an index on a system table.

To drop the indexes created to implement PRIMARY KEY or UNIQUE constraints, the constraint must be dropped. For more information about dropping constraints, see ALTER TABLE.


DROP TABLE

Removes a table definition and all data, indexes, constraints, and permission specifications for that table.

Syntax

DROP TABLE table_name

Arguments

table_name

Is the name of the table to be removed.

Remarks

DROP TABLE cannot be used to drop a table referenced by a FOREIGN KEY constraint. The referencing FOREIGN KEY constraint or the referencing table must be dropped first.

A table owner can drop a table in any database. When a table is dropped, rules or defaults on it lose their binding, and any constraints associated with it are automatically dropped. If you re-create a table, you must rebind the appropriate rules and defaults, and add all necessary constraints.

You cannot use the DROP TABLE statement on system tables.


EXISTS

Specifies a subquery to test for the existence of rows.

Syntax

EXISTS subquery

Arguments

subquery

Is a restricted SELECT statement.

Result Types

Boolean

Result Values

Returns TRUE if a subquery contains any rows.

Examples

This example finds from the Orders table all the orders with Washington as the Shipping Region for Employees who are listed in the Employees table.

SELECT * FROM Orders WHERE ShipRegion = 'WA' AND EXISTS (SELECT EmployeeID FROM Employees AS Emp WHERE Emp.EmployeeID = Orders.EmployeeID)


Expressions

An expression is a combination of symbols and operators that the database system evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression.

Syntax

{ constant
| scalar_function
| [ alias. ] column
| ( expression )
| { unary_operator } expression
| expression { binary_operator } expression
}

Arguments

constant

Is a symbol that represents a single, specific data value. constant is one or more alphanumeric characters (letters a-z and A-Z) or symbols (such as !, @, #). Unicode character and datetime values are enclosed in quotation marks; binary strings and numeric constants are not.

scalar_function

Is a unit of SQL syntax that provides a specific service and returns a single value.

[alias.]

Is the alias, or correlation name, assigned to a table by the AS keyword in the FROM clause.

column

Is the name of a column.

( expression )

Is any valid SQL Server CE expression as defined in this topic. The parentheses are grouping operators that ensure that all the operators in the expression within the parentheses are evaluated before the resulting expression is combined with another.

{ unary_operator }

Is an operator that has only one numeric operand.

  • + indicates a positive number.

  • - indicates a negative number.

  • ~ indicates the complement operator.

    Unary operators can be applied only to expressions that evaluate to any of the data types of the numeric data type category.

{ binary_operator }

Is an operator that defines the way two expressions are combined to yield a single result. binary_operator can be an arithmetic operator, the assignment operator (=), a bitwise operator, a comparison operator, a logical operator, the string concatenation operator (+), or a unary operator. For more information, see Operators.

Expression Results

For a simple expression built of a single constant, variable, scalar function, or column name, the data type, precision, scale, and value of the expression is the data type, precision, scale, and value of the referenced element.

When two expressions are combined using comparison or logical operators, the resulting data type is Boolean and the value is one of three values: TRUE, FALSE, or UNKNOWN.

When two expressions are combined using arithmetic, bitwise, or string operators, the resulting data type is determined by the operator.

Complex expressions made up of many symbols and operators evaluate to a single-valued result. The data type, precision, and value of the resulting expression is determined by combining the component expressions two at a time until a final result is reached. The sequence in which the expressions are combined is defined by the precedence of the operators in the expression.

Remarks

An operator can combine two expressions if they both have data types supported by the operator and at least one of these conditions is TRUE:

  • The expressions have the same data type.

  • The data type with the lower precedence can be implicitly converted to the data type with the higher data type precedence.

If there is no supported implicit conversion, the two expressions cannot be combined.

In a programming language such as Microsoft® Visual Basic®, an expression always evaluates to a single result. Expressions in a SQL select list have a variation on this rule: The expression is evaluated individually for each row in the result set. A single expression may have a different value in each row of the result set, but each row has only one value for the expression. For example, in this SELECT statement, both the reference to ProductID and the term 1+2 in the select list are expressions:

SELECT ProductID, 1+2
FROM Products

The expression 1+2 evaluates to 3 in each row in the result set. Although the expression ProductID generates a unique value in each result set row, each row only has one value for ProductID.


FROM Clause

Specifies the table(s) from which to retrieve rows. The FROM clause is always required.

Syntax

[ FROM { < table_source > } [ ,...n ] ]

< table_source > ::=
table_name [ [ AS ] table_alias ]
| < joined_table >

< joined_table > ::=
< table_source > < join_type > < table_source > ON < search_condition >
| ( < joined_table > )

< join_type > ::=
[ INNER | { { LEFT | RIGHT } [ OUTER ] } ] JOIN

Arguments

< table_source >

Specifies tables, derived tables, and joined tables for the SELECT statement.

table_name [ [ AS ] table_alias ]

Specifies the name of a table and an optional alias.

< joined_table >

Is a result set that is the join of two or more tables.

For multiple joins, you can use parentheses to specify the order of the joins.

< join_type >

Specifies the type of join operation.

INNER

Specifies that all matching pairs of rows are returned. Discards unmatched rows from both tables. This is the default if no join type is specified.

LEFT [ OUTER ]

Specifies that all rows from the left table that are not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the left table are set to NULL.

RIGHT [ OUTER ]

Specifies that all rows from the right table that are not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the right table are set to NULL.

JOIN

Indicates that the specified tables should be joined.

ON < search_condition >

Specifies the condition on which the join is based. The condition can specify any valid predicate, although columns and comparison operators are often used.

Remarks

In SQL Server CE, the SELECT statement must include a FROM clause to execute successfully. Otherwise, SQL Server CE returns an error.


Functions

SQL Server CE supports the following functions.

Aggregate Functions

Perform calculations on a set of values and return a single value. Except for the COUNT function, aggregate functions ignore null values.

  • AVG

  • COUNT

  • MAX

  • MIN

  • SUM

Date and Time Functions

Perform an operation on a date and time input value and return a string, numeric, or date and time value.

  • DATEADD

  • DATEDIFF

  • DATENAME

  • DATEPART

  • GETDATE


GETDATE

Returns the current system date and time in the Microsoft® SQL Server™ standard internal format for datetime values.

Syntax

GETDATE ( )

Return Types

datetime

Examples

This example uses GETDATE to supply information for a date column.

CREATE TABLE MyOrders (OrderID int IDENTITY(100, 1) PRIMARY KEY, CompanyName nvarchar(50), OrderDate datetime)
INSERT INTO MyOrders (CompanyName, OrderDate) VALUES ('Fictitious Company', GETDATE())


GROUP BY Clause

Specifies the groups (equivalence classes) into which output rows are to be placed and, if aggregate functions are included in the SELECT clause <select list>, calculates a summary value for each group. When GROUP BY is specified, either each column in any non-aggregate expression in the select list should be included in the GROUP BY list or the GROUP BY expression must match exactly the select list expression.

Note If the ORDER BY clause is not specified, groups returned using the GROUP BY clause are not in any particular order. It is recommended that you always use the ORDER BY clause to specify a particular ordering of the data.

Syntax

[ GROUP BY group_by_expression [ ,...n ] ]

Arguments

group_by_expression

Is an expression on which grouping is performed. group_by_expression is also known as a grouping column. group_by_expression can be a column or a non-aggregate expression that references a column. A column alias that is defined in the select list cannot be used to specify a grouping column. Aggregate expressions cannot be specified in a group_by_expression.

Note Columns of type ntext and image cannot be used in group_by_expression.


HAVING Clause

Specifies a search condition for a group or an aggregate. HAVING is usually used with the GROUP BY clause.

Syntax

[ HAVING < search_condition > ]

Arguments

< search_condition >

Specifies the search condition for the group to meet. The search condition can use aggregate expressions and non-aggregate expressions. The only columns that can be used in the non-aggregate expressions are those specified as grouping columns in the GROUP BY clause. This is because the group by columns represent common properties for the entire group. Likewise, the aggregate expressions represent a common property for the entire group. The HAVING clause search condition is expressing a predicate over the properties of the group.

The image and ntext data types cannot be used in a HAVING clause.


IDENTITY (Property)

Creates an identity column in a table. This property is used with the CREATE TABLE and ALTER TABLE SQL statements.

Syntax

IDENTITY [ ( seed , increment ) ]

Arguments

seed

Is the value that is used for the first row loaded into the table.

increment

Is the incremental value that is added to the identity value of the previous row that was loaded.

You must specify both the seed and increment, or neither. If neither is specified, the default is (1,1).

Remarks

In SQL Server CE, the IDENTITY property can be created only on a column with an integer data type. A table can have only one IDENTITY column.

Examples

This example creates a two-column table in which the first column is an IDENTITY column.

CREATE TABLE MyCustomers (CustID int IDENTITY (100,1) PRIMARY KEY, CompanyName nvarchar (50))


IN

Determines if a given value matches any value in a subquery or a list.

Syntax

test_expression [ NOT ] IN
(
subquery
| expression [ ,...n ]
)

Arguments

test_expression

Is any valid Microsoft® SQL Server™ expression.

subquery

Is a subquery that has a result set of one column. This column must have the same data type as test_expression.

expression [,...n]

Is a list of expressions to test for a match. All expressions must be of the same type as test_expression.

Result Types

Boolean

Result Value

If the value of test_expression is equal to any value returned by subquery or is equal to any expression from the comma-separated list, the result value is TRUE. Otherwise, the result value is FALSE.

Using NOT IN negates the returned value.

Examples

This example selects all customers from Brazil, Argentina, and Venezuela.

SELECT * FROM Customers WHERE Country IN ('Brazil', 'Argentina', 'Venezuela')


Information Schema

SQL Server CE exposes meta data about the current database through the following INFORMATION_SCHEMA views.

View | Contains information on
COLUMNS | Columns accessible to the current user in the current database
INDEXES | Indexes in the current database
KEY_COLUMN_USAGE | Keys in the current database
PROVIDER_TYPES | Data types supported in SQL Server CE
TABLES | Tables accessible to the current user in the current database
TABLE_CONSTRAINTS | Table constraints in the current database

To retrieve data from these views, use the fully qualified name INFORMATION_SCHEMA.

SELECT * FROM INFORMATION_SCHEMA.TABLES


INSERT

Adds new rows to a table.

Syntax

INSERT [ INTO]
table_name [ ( column_list ) ]
{ VALUES
( { DEFAULT | NULL | expression } [ ,...n] )
| derived_table
}

Arguments

[INTO]

Is an optional keyword that can be used between INSERT and the target table.

table_name

Is the name of a table that is to receive the data.

( column_list )

Is a list of one or more columns in which to insert data. column_list must be enclosed in parentheses and delimited by commas.

VALUES

Introduces the list of data values to be inserted. There must be one data value for each column in column_list (if specified) or in the table. The values list must be enclosed in parentheses.

DEFAULT

Requires SQL Server CE to use the default value defined for a column.

NULL

Indicates that the value is unknown. A value of NULL is different from an empty or zero value.

expression

Is a constant, a variable, or an expression.

derived_table

Is any valid SELECT statement that returns rows of data to be loaded into the table.

Remarks

INSERT appends new rows to a table. To replace data in a table, the DELETE statement must be used to clear existing data before loading new data with INSERT. To modify column values in existing rows, use UPDATE.

If the insert column_list is omitted, then an insert column list that identifies all columns of the table in the ascending sequence of their ordinal positions is implicit.

A column in the table can be identified only once in the column_list.

If a column is not in column_list, SQL Server CE must be able to provide a value based on the definition of the column; otherwise, the row cannot be loaded. SQL Server CE automatically provides a value for the column if the column:

  • Has an IDENTITY property. The next incremental identity value is used.

  • Has a default. The default value for the column is used.

  • Is nullable. A null value is used.

The column_list and VALUES list must be used when inserting explicit values into an identity column. If the values in the VALUES list are not in the same order as the columns in the table or do not have a value for each column in the table, column_list must be used to explicitly specify the column that stores each incoming value.

When DEFAULT is used to specify a column value, the default value for that column is inserted. If a default does not exist for the column and the column allows NULLs, NULL is inserted. DEFAULT is not valid for an identity column.

Columns created with the uniqueidentifier data type store specially formatted 16-byte binary values. Unlike with identity columns, SQL Server CE automatically generates values for ROWGUID columns with the uniqueidentifier data type. During an insert operation, variables with a data type of uniqueidentifier and string constants in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (36 characters including hyphens, where x is a hexadecimal digit in the range 0-9 or a-f) can be used for uniqueidentifier columns. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid value for a uniqueidentifier variable or column.

When inserting rows, these rules apply:

  • If a value is being loaded into columns with a nchar, nvarchar, or varbinary data type, the padding or truncation of trailing blanks (spaces for nchar and nvarchar, zeros for varbinary) is determined as defined in the table below:
    Data type | Default operation
    nchar/binary | Pad original value (with trailing blanks for the nchar columns and with trailing zeros for the binary columns) to the length of the column.
    nvarchar | Trailing blanks in character values inserted into nvarchar columns are not trimmed. Values are not padded to the length of the column.
    varbinary | Trailing zeros in binary values inserted into varbinary columns are not trimmed. Values are not padded to the length of the column.

  • If an INSERT statement violates a constraint or rule or if it has a value incompatible with the data type of the column, the statement fails and SQL Server CE displays an error message.

  • If INSERT is loading multiple rows with SELECT, any violation of a rule or constraint that occurs from the values being loaded causes the entire statement to be terminated, and no rows are loaded.

When the derived_table accesses a table that is being inserted into, the derived_table is evaluated before inserting any rows into the table.

Examples

A. Use a simple INSERT

This example adds a new company to the Customers table in the Northwind database. Where certain information is unavailable, a null value is inserted.

INSERT INTO Customers VALUES ('TSTCU', 'Testing Site Telephony Co.', 'John Kay', 'Owner', NULL, 'Forks', NULL, NULL, 'USA', NULL, DEFAULT)

B. Insert data that is not in the same order as the columns

This example uses the column_list and VALUES list to specify explicitly the values that are inserted into each column in the Customers table.

INSERT INTO Customers (CustomerID, CompanyName, Country, Phone) VALUES ('XYZAB', 'Xylophone Alphabet Co.', 'USA', '206-321-8765')

C. Insert data with fewer values than columns

This example adds Liz Smith to the Employees table without supplying a value for EmployeeID.

INSERT Employees (LastName, FirstName) VALUES ('Smith', 'Liz')
D. Insert data to a derived table

This example pulls all customers from Brazil and inserts the data into a derived table.

CREATE TABLE BrazilCustomers (CustomerID nvarchar(40) NOT NULL UNIQUE, CompanyName nvarchar(40), Phone nvarchar(40))
INSERT INTO BrazilCustomers (CustomerID, CompanyName, Phone) SELECT CustomerID, CompanyName, Phone FROM Customers WHERE Country = 'Brazil'


IS [NOT] NULL

Determines whether or not a given expression is NULL.

Syntax

expression IS [ NOT ] NULL

Arguments

expression

Is any valid Microsoft® SQL Server™ expression.

NOT

Specifies that the Boolean result be negated. The predicate reverses its return values, returning TRUE if the value is not NULL, and FALSE if the value is NULL.

Result Types

Boolean

Return Code Values

If the value of expression is NULL, IS NULL returns TRUE; otherwise, it returns FALSE.

If the value of expression is NULL, IS NOT NULL returns FALSE; otherwise, it returns TRUE.

Remarks

To determine if an expression is NULL, use IS NULL or IS NOT NULL rather than comparison operators (such as = or !=). Comparison operators return UNKNOWN if either or both arguments are NULL.


LIKE

Determines whether or not a given character string matches a specified pattern. A pattern can include regular characters and wildcard characters. During pattern matching, regular characters must match exactly the characters specified in the character string. Wildcard characters, however, can be matched with arbitrary fragments of the character string. Using wildcard characters makes the LIKE operator more flexible than using the = and != string comparison operators. If any of the arguments are not of character string data type, Microsoft® SQL Server™ converts them to character string data type, if possible.

Syntax

match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]

Arguments

match_expression

Is any valid SQL expression of character string data type.

pattern

Is the pattern to search for in match_expression and can include these valid SQL Server CE wildcard characters.

Wildcard character | Description | Example
% | Any string of zero or more characters. | WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title.
_ (underscore) | Any single character. | WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).

escape_character

Is any valid SQL Server expression of any of the data types of the character string data type category. escape_character has no default and must consist of only one character.

Result Types

Boolean

Result Value

LIKE returns TRUE if the match_expression matches the specified pattern.


MAX

Returns the maximum value in the expression.

Syntax

MAX ( [ ALL ] expression )

Arguments

ALL

Applies the aggregate function to all values. ALL is the default.

expression

Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MAX can be used with numeric, character, and datetime columns but not with bit columns. Aggregate functions and subqueries are not permitted.

Return Types

Returns a value same as expression.

Remarks

MAX ignores any null values.

For character columns, MAX finds the highest value in the collating sequence.

Examples

This example uses MAX to determine the highest priced item in the Products table.

SELECT MAX(UnitPrice) FROM Products


MIN

Returns the minimum value in the expression.

Syntax

MIN ( [ ALL ] expression )

Arguments

ALL

Applies the aggregate function to all values. ALL is the default.

expression

Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MIN can be used with numeric, nchar, nvarchar, or datetime columns but not with bit columns. Aggregate functions and subqueries are not permitted.

Return Types

Returns a value same as expression.

Remarks

MIN ignores any null values.

With character data columns, MIN finds the value that is lowest in the sort sequence.

Examples

This example uses MIN to determine the lowest priced item in the Products table.

SELECT MIN(UnitPrice) FROM Products


NOT

Negates a Boolean input.

Syntax

[ NOT ] boolean_expression

Arguments

boolean_expression

Is any valid Microsoft® SQL Server™ Boolean expression.

Result Types

Boolean

Result Value

NOT reverses the value of any Boolean expression.


Operators

SQL Server CE supports the following operators.

Arithmetic Operators

+ (Add) | / (Divide)
- (Subtract) | % (Modulo)
* (Multiply) |

Bitwise Operators

Note Only one expression can be of either binary or varbinary data type in a bitwise operation.

& (AND) | ^ (Exclusive OR)
| (OR) | ~ (NOT)

Comparison Operators

= (Equals) | <> (Not Equal To)
> (Greater Than) | != (Not Equal To)
< (Less Than) | !< (Not Less Than)
>= (Greater Than or Equal To) | !> (Not Greater Than)
<= (Less Than or Equal To) |

Logical Operators

ALL | IN
AND | LIKE
ANY | NOT
BETWEEN | OR
EXISTS | SOME

Unary Operators


OR

Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses.

Syntax

boolean_expression OR boolean_expression

Arguments

boolean_expression

Is any valid Microsoft® SQL Server™ expression that returns TRUE, FALSE, or UNKNOWN.

Result Types

Boolean

Result Value

OR returns TRUE when either of the conditions is TRUE.


ORDER BY Clause

Specifies the sort order for the result set. The ORDER BY clause is invalid in subqueries.

Syntax

[ ORDER BY { order_by_expression [ ASC | DESC ] } [ ,...n] ]

Arguments

order_by_expression

Specifies a column on which to sort. A sort column can be specified as a name or column alias (which can be qualified by the table name) or an expression. Multiple sort columns can be specified. The sequence of the sort columns in the ORDER BY clause defines the organization of the sorted result set.

The ORDER BY clause can include items not appearing in the select list.

Note ntext and image columns cannot be used in an ORDER BY clause.

ASC

Specifies that the values in the specified column should be sorted in ascending order, from lowest value to highest value.

DESC

Specifies that the values in the specified column should be sorted in descending order, from highest value to lowest value. Null values are treated as the lowest possible values.

There is no limit to the number of items in the ORDER BY clause.

Examples

This example lists employees by FirstName.

SELECT FirstName + ' ' + LastName FROM Employees ORDER BY FirstName


Reserved Words

The SQL Server CE reserved words are as follows.

Important Avoid using reserved words as identifiers. If reserved words must be used as identifiers, they must be delimited with double quotation marks.

ADD | ENCRYPTION | OR
ALL | END | ORDER
ALTER | ERRLVL | OUTER
AND | ESCAPE | OVER
ANY | EXCEPT | PERCENT
AS | EXEC | PLAN
ASC | EXECUTE | PRECISION
AUTHORIZATION | EXISTS | PRIMARY
AVG | EXIT | PRINT
BACKUP | EXPRESSION | PROC
BEGIN | FETCH | PROCEDURE
BETWEEN | FILE | PUBLIC
BINARY | FILLFACTOR | RAISERROR
BIT | FLOAT | READ
BREAK | FOR | READTEXT
BROWSE | FOREIGN | REAL
BULK | FREETEXT | RECONFIGURE
BY | FREETEXTTABLE | REFERENCES
CASCADE | FROM | REPLICATION
CASE | FULL | RESTORE
CHAR | FUNCTION | RESTRICT
CHARACTER | GOTO | RETURN
CHECK | GRANT | REVOKE
CHECKPOINT | GROUP | RIGHT
CLOSE | HAVING | ROLLBACK
CLUSTERED | HOLDLOCK | ROWCOUNT
COALESCE | IDENTITY | ROWGUIDCOL
COLLATE | IDENTITY_INSERT | RULE
COLUMN | IDENTITYCOL | SAVE
COMMIT | IF | SCHEMA
COMPUTE | IN | SELECT
CONSTRAINT | INDEX | SESSION_USER
CONTAINS | INNER | SET
CONTAINSTABLE | INSERT | SETUSER
CONTINUE | INT | SHUTDOWN
CONVERT | INTERSECT | SMALLINT
COUNT | INTO | SOME
CREATE | IS | STATISTICS
CROSS | JOIN | SUM
CURRENT | KEY | SYSTEM_USER
CURRENT_DATE | KILL | TABLE
CURRENT_TIME | LEFT | TEXTSIZE
CURRENT_TIMESTAMP | LIKE | THEN
CURRENT_USER | LINENO | TO
CURSOR | LOAD | TOP
DATABASE | MAX | TRAN
DATABASEPASSWORD | MIN | TRANSACTION
DATEADD | NATIONAL | TRIGGER
DATEDIFF | NCHAR | TRUNCATE
DATENAME | NOCHECK | TSEQUAL
DATEPART | NONCLUSTERED | UNION
DBCC | NOT | UNIQUE
DEALLOCATE | NULL | UPDATE
DECLARE | NULLIF | UPDATETEXT
DEFAULT | NUMERIC | USE
DELETE | OF | USER
DENY | OFF | VALUES
DESC | OFFSETS | VARYING
DISK | ON | VIEW
DISTINCT | OPEN | WAITFOR
DISTRIBUTED | OPENDATASOURCE | WHEN
DOUBLE | OPENQUERY | WHERE
DROP | OPENROWSET | WHILE
DUMP | OPENXML | WITH
ELSE | OPTION | WRITETEXT


SELECT Statement

This statement retrieves rows from the database and allows the selection of one or many rows or columns from one or many tables. This is the primary SQL construct used to express queries. It does not modify, insert, or delete any data.

Syntax

The main clauses of a SQL SELECT statement can be summarized as:

SELECT select_list
FROM table_source
[ WHERE search_condition ]
[ GROUP BY group_by_expression ]
[ HAVING search_condition ]
[ ORDER BY order_expression [ ASC | DESC ] ]

Note The syntax of these clauses is defined in this section. Proper usage of a SELECT statement also requires an understanding of the logical semantics of such a statement (such as what meaning does a SELECT statement have). See Remarks for a brief explanation.

Remarks

A SELECT statement describes a query to the system. The execution of the query does not update any data. The query result is also a table with identically structured rows, each of which has the same set of columns. The SELECT statement defines exactly which columns will exist in this result table, and the rows that will populate the table. It does not tell the system how to execute the query, and the system executes the query in whatever manner is deemed optimal (using an internal cost-based optimization module). The result is guaranteed to be equivalent to the canonical execution strategy described next. The only differences may be in the order of rows in the table, although this will be consistent with any ordering specified by an ORDER BY clause.

  1. Generate the join of tables in the FROM clause. If the explicit JOIN syntax is used, the JOIN result is obvious. If the FROM clause has a list of table names separated by commas, this is implicitly a cross-product join of the tables.

  2. If a WHERE clause exists, apply the search condition to the rows resulting from Step 1, and retain only those rows that satisfy the condition.

  3. If there are no aggregates in the SELECT clause, and if there is no GROUP BY clause, go to Step 7.

  4. If there is a GROUP BY clause, divide the rows resulting from Step 2 into several groups, such that all the rows in each group have the same value on all the grouping columns. If there is no GROUP BY clause, put all the rows into a single group.

  5. For each group arising from Step 4, apply the HAVING clause, if it is specified. Only those groups that satisfy the HAVING clause will be retained.

  6. For each group arising from Step 5, generate exactly one result row by evaluating the select list from the SELECT clause against that group.

  7. If the SELECT clause has the DISTINCT keyword, eliminate any duplicate rows in the result of Step 6.

  8. If there is an ORDER BY clause, sort the result of Step 7 as specified by the order expression.


SELECT Clause

Specifies the columns to be returned by the query.

Syntax

SELECT [ ALL | DISTINCT ] < select_list >

< select_list > ::=
{ *
| { table_name | table_alias }.*
| { column_name | expression } [ [ AS ] column_alias ]
} [ ,...n ]

Arguments

ALL

Specifies that duplicate rows can appear in the result set. ALL is the default.

DISTINCT

Specifies that only unique rows can appear in the result set. Null values are considered equal for the purposes of the DISTINCT keyword.

< select_list >

The columns to be selected for the result set. The select list is a series of expressions separated by commas.

*

Specifies that all columns from all tables in the FROM clause should be returned. The columns are returned by table, as specified in the FROM clause, and in the order in which they exist in the table.

table_name | table_alias.*

Limits the scope of the * to the specified table. Requires that all columns from the specified table in the FROM clause should be returned. The columns are returned in the order in which they exist in the table. If a table has an alias specified in the FROM clause, the alias must be used, and the use of the table name is invalid.

column_name

Is the name of a column to return. Qualify column_name to prevent an ambiguous reference, such as occurs when two tables in the FROM clause have columns with duplicate names. For example, both the Customers and Orders tables in the Northwind database have a column named ColumnID. If the two tables are joined in a query, the customer ID can be specified in the select list as Customers.CustomerID. If a table alias is provided, the table alias must be used to qualify the column name. Otherwise, the table name should be used.

expression

Is a column name, constant, function, or any valid combination of column names, constants, and functions connected by one or more operators.

column_alias

Is an alternative name to replace the column name in the query result set. For example, an alias such as "Quantity", or "Quantity to Date", or "Qty" can be specified for a column named quantity. Aliases are used also to specify names for the results of expressions, for example:

SELECT AVG(UnitPrice) AS "Average Price" FROM "Order Details"

column_alias can be used in an ORDER BY clause. However, it cannot be used in a WHERE, GROUP BY, or HAVING clause.

Remarks

In SQL Server CE, the SELECT statement must include a FROM clause to execute successfully. Otherwise, SQL Server CE Query Analyzer returns an error.


SOME | ANY

Compares a scalar value with a single-column set of values.

Syntax

scalar_expression { = | < > | ! = | > | > = | ! > | < | < = | ! < }
{ SOME | ANY } ( subquery )

Arguments

scalar_expression

Is any valid Microsoft® SQL Server™ expression.

{ = | <> | != | > | >= | !> | < | <= | !< }

Is any valid comparison operator.

SOME | ANY

Specifies that a comparison should be made.

subquery

Is a subquery that has a result set of one column. The data type of the column returned must be the same data type as scalar_expression.

Result Types

Boolean

Result Value

SOME or ANY returns TRUE when the comparison specified is TRUE for ANY pair (scalar_expression, x) where x is a value in the single-column set. Otherwise, returns FALSE.


SUM

Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

Syntax

SUM ( [ ALL ] expression )

Arguments

ALL

Applies the aggregate function to all values. ALL is the default.

expression

Is a constant, column, or function, and any combination of arithmetic, bitwise, and string operators. expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.

Return Types

Returns the summation of all expression values in the most precise expression data type.

Expression result | Return type
integer category | int
decimal category (p, s) | decimal(38, s)
money and smallmoney category | money
float and real category | float

Examples

This example queries for the total number of units in stock for all discontinued products in the Northwind database.

SELECT SUM(UnitsInStock)AS "Units Remaining" FROM Products WHERE Discontinued = 'True'

Here is the result set.

Units Remaining
---------------
101


UPDATE

Modifies existing data in a SQL Server CE table.

Syntax

UPDATE table_name
SET
{ column_name = { expression | DEFAULT | NULL } } [ ,...n ]
[ WHERE < search_condition > ]

Arguments

table_name

Is the name of the table to update.

SET

Specifies the list of column or variable names to be updated.

column_name

Is a column that contains the data to be changed.

expression

Is a variable, literal value, or expression that returns a single value. The value returned by expression replaces the existing value in column_name.

DEFAULT

Specifies that the default value defined for the column is to replace the existing value in the column. This can also be used to change the column to NULL if the column has no default and is defined to allow null values.

WHERE

Specifies the conditions that limit the rows that are updated.

< search_condition >

Specifies the condition to be met for the rows to be updated. There is no limit to the number of predicates that can be included in a search condition.

Remarks

Every column_name specified in the SET clause must reside in the table specified in the UPDATE clause.

The same column_name should appear only once in the SET clause.

Identity columns cannot be updated.

If a WHERE clause is not specified, all rows of the table are updated.

The search_condition in the WHERE clause is evaluated for each row of the table before updating any row of the table.

If an update to a row violates a constraint or rule, if it violates the NULL setting for the column, or if the new value is an incompatible data type, the statement is canceled, an error is returned, and no records are updated.

All nchar columns are right-padded to the defined length.

All trailing spaces are removed from data inserted into nvarchar columns, except in strings containing only spaces. These strings are truncated to an empty string.

Examples

This example changes the shipping address for all orders made by the company with CustomerID = 'VINET' in the Orders table of the Northwind database.

UPDATE Orders SET ShipAddress = '21 rue de l''xylophie' WHERE CustomerID = 'VINET'


WHERE Clause

Specifies a search condition to restrict the rows returned.

Syntax

[ WHERE < search_condition >]

Arguments

< search_condition >

Restricts the rows returned in the result set through the use of predicates. There is no limit to the number of predicates that can be included in a search condition.

Examples

This example uses the WHERE clause to get the total number of units in stock for all discontinued products in the Northwind database.

SELECT SUM(UnitsInStock)AS "Units Remaining" FROM Products WHERE Discontinued = 'True'

Here is the result set.

Units Remaining
---------------
101


Synchronizing Data with SQL Server CE

To transfer (synchronize) data between Microsoft® SQL Server™ CE and SQL Server using Remote Data Access (RDA) or replication, you will need to configure the required systems.

  • RDA provides a simple, yet powerful way for a Windows® CE application to update a remote SQL Server database or to transfer data back and forth between the remote SQL Server database and a SQL Server CE database on a Windows CE device. RDA is appropriate when the full power of SQL Server CE merge replication is not required.

  • Microsoft SQL Server CE replication is based on SQL Server 2000 merge replication. This makes replication ideally suited to portable devices because it allows data to be updated autonomously on the portable device and at the server. Then, the data can be merged when the device is connected to SQL Server.

This section helps you understand the communication protocols that RDA and replication support. It provides an overview of Microsoft Internet Information Services (IIS) security and SQL Server security, and explains how RDA and replication interact with both security models to help you plan your security architecture. Configuring IIS, which is required for RDA and replication connectivity to SQL Server, is also covered.

Additionally, SQL Server CE Relay enables connectivity to SQL Server using a desktop computer network connection, which eliminates the need for a network card or modem in the Windows CE device.

See Also

Remote Data Access

Replication

SQL Server CE Relay


Communication and Connectivity

SQL Server CE RDA and replication components communicate using Web protocols. The SQL Server CE Client Agent on the Windows CE device uses HTTP to communicate with the SQL Server CE Server Agent ISAPI DLL on the Web server. The SQL Server CE Server Agent communicates directly with SQL Server.

RDA and Replication Communication Protocols

SQL Server CE RDA and replication support the following Windows CE TCP/IP transports:

  • Ethernet

  • Wireless LANs

  • Wireless WANs

SQL Server CE RDA and replication support the leading wireless LAN protocols, including:

  • Proxim (OpenAir)

  • IEEE 802.11

SQL Server CE RDA and replication support the leading wireless WAN protocols, including:

  • ARDIS

  • RAM

  • Modems operating over analog cellular systems, such as AMPS and N-AMPS

  • CDPD

  • TDMA, including D-AMPs and PDC (Personal Digital Cellular)

  • GSM

  • CDMA

SQL Server CE RDA and replication support the following connection types when using SQL Server CE Relay:

  • USB

  • Serial

  • Infrared

SQL Server CE RDA and replication are optimized for wireless communication. They automatically compress data to minimize the amount of data sent over the wireless network. They can be configured to use encryption to safeguard user data propagated between the SQL Server CE and SQL Server.

Data is propagated between the Windows CE device and the server by using a simple protocol patterned after file transfer protocols. SQL Server CE RDA and replication recover from communication failures by restarting from the last successfully transmitted block of data. This makes synchronization possible even if the underlying transport is not reliable.

SQL Server CE RDA and replication are primarily intended for Windows CE devices that are occasionally connected to the network. However, it is also useful for Windows CE devices that are consistently connected.


Planning for Security

SQL Server CE replication security depends on IIS and SQL Server security. You must understand IIS and SQL Server security to understand SQL Server CE replication security. This section provides an overview of IIS and SQL Server security. It also explains how RDA and replication interact with IIS and SQL Server security.


IIS Security

SQL Server CE replication and RDA rely on IIS authentication, authorization, and encryption.

IIS Authentication

SQL Server CE replication and RDA rely on three modes of IIS authentication:

  • Anonymous authentication

  • HTTP Basic authentication

  • Integrated Windows authentication (but not Kerberos authentication)
Anonymous Authentication

IIS performs no client authentication when Anonymous authentication is specified. This is the most common mode of authentication for public Internet Web sites. When a request arrives, IIS impersonates the anonymous user, typically IUSR_computername, and all of the work that IIS performs on behalf of the client is done under this identity.

HTTP Basic Authentication

In Basic authentication mode, the client must provide a user name and password. The user name and password are sent over HTTP in Base64 encoding. If this information is intercepted, it can easily be decoded. For this reason, Basic authentication is almost always used with Secure Sockets Layer (SSL) encryption to prevent the user name and password from being compromised. When the user name and password arrive on the IIS system, IIS logs on using the supplied user name and password. As the result of a successful logon attempt, IIS adopts the identity of the Windows account for which the client supplied the user name and password. All of the work that IIS performs on behalf of the client is done under this identity.

Integrated Windows Authentication

Integrated Windows authentication (formerly called NTLM or Windows NT Challenge/Response authentication) is a secure form of authentication because the user name and password are not sent across the network. When Integrated Windows authentication is used, the client uses hashing to prove its knowledge of the password through a cryptographic exchange with the IIS server. Both the client and the IIS server are authenticated during the cryptographic exchange. Integrated Windows authentication cannot operate over a proxy server or firewall. As a result, Integrated Windows authentication can be used for intranet applications but is seldom, if ever, used for Internet applications. As the result of successful authentication, IIS adopts the identity of the client. All of the work that IIS performs on behalf of the client is done under the client's identity.

Integrated Windows authentication is supported on Windows CE 3.0 or later. Integrated Windows authentication is not supported on earlier versions of Windows CE.

On Windows 2000 with Active Directory, Integrated Windows authentication has been extended to support Kerberos. With the advent of Kerberos, Integrated Windows authentication now supports delegation. Delegation allows a client on one system to access the resources of another system under the client's identity. In fact, the remote system can use delegation to access the resources of a third system under the client identity, and so forth. Windows CE does not currently support Kerberos. As a result, SQL Server CE replication and RDA cannot use delegation. This has one important consequence. You cannot use IIS Integrated Windows authentication in combination with SQL Server Integrated Windows authentication when IIS and SQL Server are on different systems. That requires Kerberos delegation between the IIS and SQL Server systems. If your IIS server and SQL Server are on different systems and you want to use Integrated Windows authentication with SQL Server, you must configure IIS to use either Anonymous authentication or Basic authentication.

IIS Authorization

IIS authorization determines whether the client is permitted to invoke your Web site. IIS provides the following mechanisms for controlling access.

IIS first checks the address of the client against any IP address restrictions you have configured. You can configure your Web site to prevent specific computers, groups of computers, or entire networks from accessing it. When a client initially tries to access your Web site, IIS checks the IP address of the client computer against the IP address restriction settings on the server. If the IP address is denied access, then the client request is rejected with a "403 Access Forbidden" message.

If IIS is configured to require authentication, it next checks whether the client has a valid Windows user account as described in the Configuring IIS Authentication section above. If not, then the request from the client is rejected with a "403 Access Forbidden" message.

IIS then checks the Web permissions associated with the Web site. This controls which type of HTTP requests the client can perform on your Web site.

IIS then checks NTFS permissions for the file system directory associated with your Web site. You can use Windows Explorer to control execute, read, and write permissions to the file system directory. By doing this, you control what operations the client can perform on your Web site.

IIS Encryption

IIS encryption is based on the SSL protocol that provides secure communications on the Internet. SSL implements a security protocol on top of a reliable connection-oriented transport protocol. The Windows CE client connects to IIS and the two perform a handshake to establish a secure session. After the security handshake is complete, the SSL protocol encrypts and authenticates data sent between the Windows CE client and IIS.

IIS can host two or more virtual Web servers on a single computer, but doing so can lead to problems when using SSL. IIS supports virtual Web sites in three ways:

  • By assigning each Web site its own network card and IP address.

  • By having Web sites share a network card and IP address but assigning each Web site its own port.

  • By having Web sites share a network card, IP address, and port but assigning each Web site its own domain name and using HTTP 1.1 host headers to differentiate Web sites.

The first two options work with SSL because the IP addresses or port numbers for the sites differ. The third option does not work with SSL because the IP address and port are the same for each Web site; the only difference is the host header in the HTTP request. This leads to a problem because the client cannot send the HTTP data to the Web server until the SSL connection is established, and the Web server cannot determine which certificate and private key to use to establish the secure connection until it sees the header. There is no way around this problem. If you want to use SSL on multiple virtual Web sites on a single IIS server, you must choose option one or two.


SQL Server Security

A user passes through two stages of security when working in SQL Server: SQL Server Authentication and SQL Server Authorization.

SQL Server Authentication

SQL Server Authentication is the process by which the system validates login information from a client. The user name and password are compared to an authorized list. If the client-supplied user name and password match the authorized list, the client is allowed to connect to an instance of SQL Server.

SQL Server supports two authentication modes: Integrated Windows authentication and SQL Server Authentication.

When Integrated Windows authentication is used, Windows is entirely responsible for authenticating the client. In this case, the client is identified by its Windows user account.

When SQL Server Authentication is used, SQL Server authenticates the client by comparing the client-supplied user name and password to the list of valid user names and passwords maintained within SQL Server. In this case, the client must supply the appropriate SQL Server login and password when it connects to SQL Server.

SQL Server Authorization

SQL Server Authorization is the process that verifies that the client has permission to access a SQL Server database. Authorization also controls the activities the client is allowed to perform within that SQL Server database.

SQL Server Authorization is based upon user accounts. When a client is authenticated, the user name of the client is mapped to a SQL Server user account.

The client must have a user account in each database they want to access. Requiring a user account in each database prevents clients from connecting to an instance of SQL Server and accessing all the databases on a server. For example, if a server contains a personnel database and a recruiting database, clients who should be able to access the recruiting database but not the personnel database would have a user account created only in the recruiting database.

The user accounts in each database are used to control access to the tables, views, stored procedures, and so on in that database. The activities a client is allowed to perform are controlled by the permissions applied to the user account from which they gained access to the database.

When Integrated Windows authentication is used, each Windows user account can be mapped to it own SQL Server user account. Alternatively, entire Windows groups can be mapped to a SQL Server user account. The second approach is often better because managing group permissions is easier than managing permissions for individual users.

You are responsible for creating SQL Server user accounts and for mapping Windows users and groups to these SQL Server user accounts. For more information see "Granting a Windows NT User or Group Access to a Database" in SQL Server Books Online.

For more information regarding SQL Server security, see "Managing Security" in SQL Server Books Online.


Replication and RDA Security

SQL Server CE replication and RDA security rely entirely upon IIS security and SQL Server security.

The Windows CE application initiates synchronization by invoking the SQL Server CE Replication or RDA Object. The Replication or RDA Object invokes the SQL Server CE Client Agent, which in turn invokes the SQL Server CE Server Agent ISAPI DLL. You configure IIS authentication and authorization to control who can invoke the SQL Server CE Server Agent. By doing this, you control who can perform database synchronization or remote database access.

You can configure IIS to use SSL encryption. This will safeguard the data sent between the Windows CE device and IIS when database synchronization or remote database access is performed.

Once the SQL Server CE Server Agent is invoked, it connects to SQL Server. You can configure SQL Server authentication and authorization to control who can access SQL Server or your SQL Server publications.

In summary, SQL Server CE replication or RDA security is a six-step process involving:

  • IIS Authentication

  • IIS Authorization

  • IIS Encryption

  • SQL Server Authentication

  • SQL Server Authorization

  • SQL Server CE Encryption
IIS Authentication

When you configure the SQL Server CE Server Agent ISAPI DLL, you specify whether clients must perform IIS authentication when connecting to the Agent. You can choose from three forms of IIS authentication: anonymous authentication, Basic Authentication, or Integrated Windows Authentication.

If you choose anonymous authentication, IIS performs no client authentication. All work that the SQL Server CE Server Agent performs on behalf of the client is done under the identity of the IIS anonymous account. By default, the IIS anonymous account is IUSR_computername but you can designate some other Windows user account as the IIS anonymous account. Anonymous authentication is most commonly used for Internet applications when the SQL Server CE clients do not have Windows user accounts.

If you choose Basic authentication, the SQL Server CE client must supply a valid Windows account user name and password. IIS attempts to log in using the client-supplied user name and password. If the login attempt succeeds, all work that the SQL Server CE Server Agent performs is done under the identity of the specified Windows user account. If the login attempt fails, the synchronization request from the client is rejected. Basic authentication can be used for both Internet and intranet applications. It requires that each client have a valid Windows account with a corresponding user name and password. By default, Basic authentication passes the user name and password across the network in base64 encoding. This can pose a security risk if anyone eavesdrops on the password exchange because the base64 encoding can easily be decoded. SSL encryption should always be used whenever Basic authentication is used to safeguard the user password.

Integrated Windows authentication works much like Basic authentication. The SQL Server CE client must supply a valid Windows account user name and password. IIS attempts to log in using the user name and password. If the login attempt succeeds, all work that the SQL Server CE Server Agent performs is done under the identity of the Windows user account. If the login attempt fails, the client synchronization request is rejected. Integrated Windows has one primary advantage over Basic authentication. Unlike Basic authentication, Integrated Windows authentication does not transmit the client's user name and password over the network in unencrypted form. This avoids the risk of someone intercepting the password. Integrated Windows is best suited to intranet applications. Integrated Windows authentication is seldom used for Internet applications because it cannot operate over a proxy server or firewall.

Windows CE does not support Digest Authentication, Kerberos Authentication, or Client Certificate Authentication. As a result, SQL Server CE replication and RDA do not support these forms of authentication either.

It is expected that most Internet applications will use Basic authentication and SSL encryption. Intranet applications can use either Integrated Windows authentication or Basic authentication.

IIS Authorization

Once the IIS client is authenticated, IIS authorization determines whether the client can invoke the SQL Server CE Server Agent ISAPI DLL. You control who can perform SQL Server CE replication or RDA by controlling who can access the SQL Server CE Server Agent. IIS provides the following mechanisms for controlling access.

IIS first checks the address of the client against any IP address restrictions you have configured. You can configure your Web server to prevent specific computers, groups of computers, or entire networks from accessing your SQL Server CE Server Agent. When a client initially tries to access your SQL Server CE Server Agent, IIS checks the IP address of the client computer against the IP address restriction settings on the server. If the IP address is denied access, then the synchronization request from the client is rejected with a "403 Access Forbidden" message.

If IIS is configured to require authentication, it next checks whether the client has a valid Windows user account as described in the preceding "IIS Authentication" section. If not, then the client's synchronization request is rejected with a "403 Access Forbidden" message.

IIS then checks the Web permissions. This IIS security check is not relevant for SQL Server CE replication or RDA.

IIS then checks NTFS permissions for the SQL Server CE Server Agent DLL (Sscesa10.dll). You can use Windows Explorer to control execute permission to the SQL Server CE Server Agent DLL. You should only grant execute permission to Windows users who are entitled to invoke SQL Server CE replication or RDA.

Note Although IIS can also be used with a File Allocation Table (FAT) file system, we strongly recommend you use NTFS. NTFS allows you to use Access Control Lists to grant or deny access to the SQL Server CE Server Agent ISAPI DLL and the input and output replication or RDA message files on the IIS system.

IIS Encryption

When you configure the SQL Server CE Server Agent ISAPI DLL, you can specify SSL encryption. When you specify SSL encryption, all communication between the SQL Server CE Client Agent and SQL Server CE Server Agent is encrypted.

You should use SSL encryption in the following situations:

  • If you configure IIS to use Basic authentication. This is essential to safeguard the Internet password of the user. By default, Basic authentication transmits the user name and password across the network in base64 encoding. This can pose a security risk if anyone eavesdrops on the password exchange because the base64 encoding can easily be decoded. SSL encryption should always be used whenever Basic authentication is used to safeguard the user's Internet password.

  • For replication only: If either the SQL Server Publisher or Distributor relies on SQL Server Authentication, you should configure IIS to use SSL encryption. Your Distributor is using SQL Server Authentication if the DistributorSecurityMode property specifies DB_AUTHENTICATION. Your Publisher is using SQL Server Authentication if the PublisherSecurityMode property specifies DB_AUTHENTICATION. When SQL Server Authentication is used, the DistributorPassword and PublisherPassword are passed across the network in clear text form. This can pose a security risk if anyone eavesdrops on the password exchange. SSL encryption should always be used whenever SQL Server Authentication is used to safeguard DistributorPassword and PublisherPassword.

  • For RDA only: You should use SSL encryption if your application specifies an OLEDBConnectionString containing a password. The RDA Pull, Push, and SubmitSQL methods require an OLEDBConnectionString parameter. This connection string is passed across the network in clear text form. This can pose a security risk if anyone eavesdrops on the password exchange.

  • You should use SSL encryption to safeguard your user data while it is being transmitted between the Windows CE device and the IIS system.
SQL Server Authentication

SQL Server supports two forms of authentication: Integrated Windows authentication and SQL Server Authentication.

SQL Server Integrated Windows Authentication

When Integrated Windows authentication is used, Windows is entirely responsible for authenticating the client. In this case, the client is identified by its Windows user account. In the case of SQL Server CE replication or RDA, the Replication Provider or SQL Server CE Server Agent acts as the database client. It runs under the identity of a Windows user account.

When IIS is configured to use anonymous authentication, the Replication Provider and SQL Server CE Server Agent run under the identity of the Internet Guest Account (IUSR_computername). If you configure another Windows user account as the IIS anonymous user account, the Replication Provider and SQL Server CE Server Agent run under the identity of that account.

When IIS is configured to use Basic Authentication, the Replication Provider and SQL Server CE Server Agent run under the identity of the Windows user account for which the client supplied the Internet user name and password.

When IIS is configured to use Windows Integrated authentication, the Replication Provider and SQL Server CE Server Agent run under the identity of the client.

SQL Server Authentication

When SQL Server Authentication is used, SQL Server authenticates the client by comparing the client-supplied user name and password to the list of valid user names and passwords maintained within SQL Server. In this case, the Windows CE application must supply the appropriate SQL Server login and password through the SQL Server CE Replication or RDA Object. The SQL Server CE Client Agent conveys the login and password to the SQL Server CE Replication Provider or the SQL Server CE Server Agent through the input message file. The SQL Server CE Replication Provider or Server Agent invokes SQL Server using the login and password specified by the client.

For replication only: If the same SQL Server is acting as both the Distributor and the Publisher, the Windows CE application specifies the security attributes for both the Publisher and the Distributor using the PublisherSecurityMode, PublisherLogin, and PublisherPassword properties of the SQL Server CE Replication Object. If one SQL Server is acting as the Distributor and another is acting as the Publisher, the Windows CE application specifies the security attributes for the Publisher by using the PublisherSecurityMode, PublisherLogin, and PublisherPassword properties. The Windows CE application specifies the security attributes for the Distributor by using the DistributorSecurityMode, DistributorLogin, and DistributorPassword properties of the SQL Server CE Replication object.

SQL Server Authorization

When a client is successfully authenticated, the user or group name of the client is mapped to a SQL Server user account.

The client must have a user account in each database they want to access. The user account is used to control access to the tables, views, stored procedures, and so on, in that database. The activities a client is allowed to perform are controlled by the permissions applied to the user account through which they gained access to the database.

For RDA only: You can precisely control what database operations RDA clients can perform through the permissions you grant them.

For replication only: When you create a publication, SQL Server creates a publication access list (PAL) for the publication. You must update the PAL to grant access to the publication. For more information, see Publication Access List.

When you create a publication, you can use the Check Permissions option to provide an enhanced level of security to your publication. The Check Permissions option ensures that the Merge Agent has the authority to upload data changes to a Publisher. When you specify this option, SQL Server verifies that the Merge Agent login has the permissions to perform INSERT, UPDATE, and DELETE statements on the publication database. For more information, see Check Permissions.

SQL Server CE Encryption

You can safeguard your SQL Server CE database by protecting the database with a password and encrypting its contents. Do this by setting the Database Password and Encrypt Database properties when creating the database.


Configuring IIS

Configuring IIS for either replication or remote data access (RDA) involves the following steps:

  1. Configuring the Server Agent ISAPI DLL

  2. Configuring IIS Authentication
    1. Configuring IIS authorization

    2. Configuring Server Agent authorization
  3. Configuring Directory Authorization

  4. Configuring IIS encryption (optional)

  5. Configuring IP address and domain name restrictions (optional)

  6. Configuring IIS security auditing (Optional)


Configuring the Server Agent ISAPI DLL

The SQL Server CE Server Agent is an ISAPI DLL. You configure SQL Server CE replication or RDA on the server by using the IIS snap-in. For a detailed description of IIS configuration and the IIS snap-in, see the online documentation for IIS.

When you configure SQL Server CE replication or RDA within IIS, you can either create a new Web site for replication or RDA, or you can place replication or RDA within an existing Web site. In the configuration instructions that follow, we assume that you configure replication or RDA within the existing IIS default Web site. See "About Web and FTP Sites" in the IIS Server administration documentation for more information about creating Web sites.

You can create an individual IIS virtual directory for each SQL Server CE publication, or two or more SQL Server CE publications can share an IIS virtual directory. It is recommended that you create an individual IIS virtual directory for each SQL Server CE publication because this allows you to control security more precisely. You can create one IIS virtual directory for all RDA clients, or you can create individual IIS virtual directories for different groups of RDA clients. You should create individual IIS virtual directories for different groups of RDA clients when you want to enforce different security policies for different clients. IIS authentication and authorization is controlled at the IIS virtual directory level. By creating an IIS virtual directory for each SQL Server CE publication or for different groups of RDA clients, you can establish exactly the authentication and authorization policy you require for each publication or each set of clients.

The SQL Server CE Server Agent allocates a separate worker thread pool for each IIS virtual directory. These worker threads are used when performing synchronization or RDA operations. By configuring an IIS virtual directory for each publication or different groups of RDA clients, you increase the number of worker threads and hence the number of replication operations or clients that can be active concurrently.

You should create one NTFS or FAT file directory for each IIS virtual directory. This file directory contains the SQL Server CE Server Agent ISAPI DLL and the input and output message files that SQL Server CE replication or RDA creates during synchronization or when accessing SQL Server. It is strongly recommended that you use NTFS, rather than FAT, because NTFS provides much stronger security. When you use NTFS, you can use NTFS file permissions to control precisely who can access SQL Server CE replication or RDA.


Configuring the Server Agent ISAPI DLL on Windows 2000

SQL Server CE replication or RDA requires that you install and configure IIS.

Installing IIS on Windows 2000 Professional

If you are using Microsoft Windows 2000 Professional, you must install IIS. If you are using any other version of Windows 2000, IIS is already installed and you can proceed directly to Configuring IIS on Windows 2000.

To install IIS on Windows 2000 Professional:

  1. Click the Start button, choose Settings, and then click Control Panel.

  2. In Control Panel, double-click Add/Remove Programs and click Add/Remove Windows Components.

  3. In the Windows Components Wizard, select the Internet Information Services (IIS) check box and click Next. The system will install IIS on your system.

  4. When IIS installation is complete, click Finish to close the Windows Components Wizard.
Configuring IIS on Windows 2000

To configure IIS on Windows 2000 Professional

  1. Use Windows Explorer to optionally create an alternate file directory on your IIS system to contain the SQL Server CE Server Agent ISAPI DLL and the input and output SQL Server CE replication or RDA message files. You can create the directory wherever you want and call it whatever you want. For example, create the NTFS file directory C:\Inetpub\SsceReplication\NorthWind.

  2. Use Windows Explorer to copy the SQL Server CE Server Agent ISAPI DLL (Sscesa10.dll) to the file directory you created in the previous step. Sscesa10.dll is installed in the \Program Files\Microsoft SQL Server CE\Server directory by default. Register the DLL by entering Regsvr32 sscesa10.dll at the command prompt. For example:
    regsvr32 C:\Inetpub\SSCEReplication\NorthWind\sscesa10.dll
  3. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking on Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager. If the Internet Services Manager option is not present in Administrative Tools, you must install IIS as described above.

  4. On Windows 2000 Server, you can start the IIS snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking on Internet Services Manager.

    In the left pane, expand the computer containing your site. Right-click the Web site where you want to install SQL Server CE replication or RDA and select New then Virtual Directory to start the Virtual Directory Creation Wizard. For example, right-click Default Web Site.

    1. In the Welcome to the Virtual Directory Creation Wizard, click Next.

    2. On the Virtual Directory Alias sheet, enter the name you want to assign to your virtual directory, for example, Northwind. Click Next.

    3. On the Web Site Content Directory sheet, enter the full path for the directory you created in Step 1. For example, C:\Inetpub\SsceReplication\NorthWind. Click Next.

    4. On the Access Permissions sheet, enter the access permissions for the virtual directory. It is recommended that you be as restrictive as possible because doing so makes your Web site more secure. You must select Execute permissions. This permits Sscesa10.dll to run. You can disable Read, Run scripts, Write, and Browse permissions. Click Next.

    5. Click Finish to complete the Virtual Directory Creation Wizard.
  5. In the left pane, expand your Web site. From the list of Virtual Directories, right-click your virtual directory and select Properties.

  6. Click the Virtual Directory tab. In the Execute Permissions list, ensure that Scripts and Executables is selected. In the Application Protection list, select the form of protection you want: High (Isolated), Medium (Pooled), or Low (IIS Process). SQL Server CE replication or RDA will work in any of the application protection modes. The default application protection mode is Medium (Pooled). Refer to the IIS documentation for more information.

  7. You can use the Directory Security sheet to configure security for your virtual directory. Configuring security is described in the following section.

  8. When you are done configuring IIS, click OK and close Internet Services Manager.


Configuring the Server Agent ISAPI DLL on Windows NT 4.0

SQL Server CE replication or RDA requires IIS. If you have not already installed IIS, you must do so by installing the Microsoft Windows NT 4.0 Option Pack.

To configure the SQL Server CE Server Agent ISAPI DLL once you have installed IIS

  1. Use Windows Explorer to create a file directory on your IIS system to contain the SQL Server CE Server Agent ISAPI DLL and the input and output SQL Server CE replication or RDA message files. You can create the directory wherever you want and call it whatever you want. For example, create the NTFS file directory C:\Inetpub\SSCEReplication\NorthWind.

  2. Use Windows Explorer to copy the SQL Server CE Server Agent ISAPI DLL (SSCESA10.DLL) to the file directory you created in the previous step. SSCESA10.DLL is installed in the \Program Files\Microsoft SQL Server CE\Server directory by default. Register the DLL by entering "regsvr32 sscesa10.dll" at the command prompt. For example:
    regsvr32 C:\Inetpub\SSCEReplication\NorthWind\sscesa10.dll
  3. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and clicking on Internet Service Manager.

  4. In the left pane, expand IIS, and expand the computer containing your site. Right-click the Web site where you want to install SQL Server CE replication or RDA and select New, Virtual Directory to start the New Virtual Directory Wizard.
    1. On the Welcome to the New Virtual Directory Wizard sheet, enter the name you want to assign to your virtual directory. For example, "Northwind". Click Next.

    2. Enter the full path for the file directory you created in step 1. For example, C:\Inetpub\SSCEReplication\NorthWind. Click Next.

    3. Enter the access permissions for the virtual directory. It is recommended that you be as restrictive as possible because doing so makes you Web site more secure. You must select Allow Execute Access. This permits SSCESA10.DLL to run. You can disable Allow Read Access, Allow Script Access, Allow Write Access, and Allow Directory Browsing. Click Finish to complete the New Virtual Directory Wizard.
  5. In the left pane, expand your Web site. From the list of Virtual Directories, right-click your virtual directory and select Properties.

  6. Select the Virtual Directory Property tab. Under Permissions, select the Execute option. SQL Server CE replication or RDA can run in either the IIS process or a separate process. Select the Run in separate memory space check box to force SQL Server CE replication or RDA to run in a separate process. Refer to the IIS documentation for more guidance.

  7. You can use the Directory Security Property sheet to configure security for your virtual directory. Configuring security is described in the following section.

  8. When you are done configuring IIS, click OK and close Internet Service Manager.


Configuring IIS Authentication

The goal of IIS authentication is to identify the client and associate the client with a valid Windows user account. You must configure IIS authentication on Windows 2000 or Windows NT 4.0 as described below.


Configuring IIS Authentication on Windows 2000

You can use one of more of the following forms of IIS authentication with Microsoft SQL Server CE replication or RDA.


Anonymous Authentication on Windows 2000

IIS relies on anonymous authentication by default.

Note If IIS and the SQL Server Distributor are located on different systems, you must configure the IIS anonymous user account as a domain user account. The default anonymous user computername\IUSR_computername cannot be used, because it is a machine local account.

To explicitly configure anonymous authentication

  1. Start the Internet Information Services snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the Internet Information Services snap-in by clicking Start, Programs, Administrative Tools, and then Internet Services Manager.

  3. In the left pane, expand the computer containing your site and then expand your Web site.

  4. From the list of virtual directories, right-click your virtual directory, select Properties, and then click the Directory Security tab.

  5. In Anonymous access and authentication control, click Edit to display the Authentication Methods sheet.

  6. Select the Anonymous access check box.

  7. By default, anonymous users will run under the identity computername\IUSR_computername. You can change the account used for anonymous access by clicking the Edit button and entering a different Windows user account in the Username box.

  8. Click OK to close the Authentication Methods sheet.

  9. Click OK to close the virtual directory sheets.

  10. Close Internet Services Manager.


Basic Authentication on Windows 2000

To configure Basic authentication

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the IIS snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your site and then expand your Web site.

  4. From the list of virtual directories, right-click your virtual directory, select Properties, and then click the Directory Security tab.

  5. In Anonymous access and authentication control, click Edit to display the Authentication Methods sheet.

  6. Select the Basic authentication check box.

  7. Clients who log in using Basic authentication must belong to a Windows domain. Clients who log in without specifying a domain are assumed to be members of the local domain of your Web server by default. You can configure a different default domain name by clicking the Edit button and entering a domain name in the Domain Name box. If your Web server does not belong to a network, then the Web server's default local domain is the name of your computer.

    Important If you specify Basic authentication, you should also specify SSL encryption to avoid transmitting the password of the user across the network in unencrypted form.

  8. Click OK to close the Authentication Methods sheet.

  9. Click OK to close the virtual directory sheets.

  10. Close Internet Services Manager.


Integrated Windows Authentication on Windows 2000

To configure Integrated Windows authentication (formerly called NTLM or Windows NT Challenge/Response Authentication)

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the IIS snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your site and then expand your Web site.

  4. From the list of virtual directories, right-click your virtual directory, select Properties, and then click the Directory Security tab.

  5. In Anonymous access and authentication control, click Edit to display the Authentication Methods sheet.

  6. Select the Integrated Windows authentication check box.

    Important Integrated Windows authentication cannot operate over a proxy server or firewall. As a result, it can be used for intranet applications but is seldom, if ever, used for Internet applications.

    Note Integrated Windows authentication is supported on Windows CE 3.0 or later. It is not supported on earlier versions of Windows CE.

  7. Click OK to close the Authentication Methods sheet.

  8. Click OK to close the virtual directory sheets.

  9. Close Internet Services Manager.


Configuring IIS Authentication on Windows NT 4.0

You configure IIS authentication on Windows NT 4.0 much the same as you do on Windows 2000.


Anonymous Authentication on Windows NT 4.0

IIS relies on anonymous authentication by default.

Note If IIS and the SQL Server Distributor are located on different systems, you must configure the IIS anonymous user account as a domain user account. The default anonymous user computername\IUSR_computername cannot be used, because it is a machine local account.

To explicitly configure anonymous authentication

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server and then expand the computer containing your site.

  3. From the list of virtual directories, right-click your Web site and click the Directory Security tab.

  4. In Anonymous access and authentication control, click Edit to display the Authentication Methods sheet.

  5. Select the Allow Anonymous Access check box.

  6. By default, anonymous users will run under the identity computername\IUSR_computername. You can change the account used for anonymous access by clicking the Edit button and entering a different Windows user account in the Username box.

  7. Click OK to close the Authentication Methods sheet.

  8. Click OK to close the virtual directory sheets.

  9. Close Internet Service Manager.


Basic Authentication on Windows NT 4.0

To configure Basic authentication

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server and expand the computer containing your site.

  3. From the list of virtual directories, right-click your Web site and then click the Directory Security tab.

  4. Within Anonymous access and authentication control, click Edit to display the Authentication Methods property sheet.

  5. Select the Basic Authentication check box.

  6. Clients who log in using Basic authentication must belong to a Windows domain. Clients who log in without specifying a domain are assumed to be members of the local domain of your Web server. You can configure a different default domain name by clicking the Edit button and entering a domain name in the Domain Name box. If your Web server does not belong to a network, then the default local domain of the Web server is the name of your computer.

    Important If you specify Basic authentication, you should also specify SSL encryption to avoid transmitting the password of the user across the network in unencrypted form.

  7. Click OK to close the Authentication Methods sheet.

  8. Click OK to close the virtual directory sheets.

  9. Close Internet Service Manager.


Integrated Windows Authentication on Windows NT 4.0

To configure Integrated Windows authentication (formerly called NTLM or Windows NT Challenge/Response Authentication)

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server and then expand the computer containing your site.

  3. From the list of virtual directories, right-click your Web site and click the Directory Security tab.

  4. Within Anonymous access and authentication control, click Edit to display the Authentication Methods sheet.

  5. Select the Windows NT Challenge/Response check box.

    Important Windows NT Challenge/Response Authentication cannot operate over a proxy server or firewall. As a result, Windows NT Challenge/Response Authentication can be used for intranet applications but is seldom, if ever, used for Internet applications.

    Note Windows NT Challenge/Response Authentication is supported on Windows CE 3.0 or later. It is not supported on earlier versions of Windows CE.

  6. Click OK to close the Authentication Methods sheet.

  7. Click OK to close the virtual directory property sheets.

  8. Close Internet Service Manager.


Configuring IIS Authorization

Configure IIS authorization as described in the following sections.


Configuring Server Agent Authorization

After authenticating the client, IIS checks whether the client is authorized to invoke SQL Server CE replication or RDA. You control who can invoke SQL Server CE replication or RDA by setting NTFS permissions on the SQL Server CE Server Agent ISAPI DLL. Proper configuration of permissions is crucial to prevent unauthorized access to SQL Server CE replication or RDA.

Configuring Server Agent Authorization on Windows 2000 or Windows NT 4.0

To secure the SQL Server CE Server Agent DLL (Sscesa10.dll)

  1. Start Windows Explorer by double-clicking My Computer. Navigate to the file system directory you specified when you configured the IIS virtual directory.

  2. Right-click Sscesa10.dll. Click Properties and click the Security tab. If you do not see the Security tab, your server has a FAT file system and you can skip this step. SQL Server CE replication or RDA works with FAT file systems, but it is not secure. It is recommended that you use NTFS. To convert the file system to NTFS, see the Windows documentation.

  3. Make sure that the permissions are set as follows (if necessary, use the Add button to add the appropriate users and then select their permissions).
    User | Required permissions
    Always grant Administrators Full Control. | Full Control
    Always grant System Full Control. | Full Control
    For anonymous authentication, grant computername\IUSR_computername or the configured IIS anonymous user account read and execute permissions. | Read and Execute
    For Basic or Integrated Windows authentication, grant the user or group of the client read and execute permissions. | Read and Execute

  4. If the Everyone group has been granted access to the SQL Server CE Server Agent DLL, it is recommended that you use the Remove button to eliminate access by the Everyone group.


Configuring Directory Authorization

Once invoked, the SQL Server CE Server Agent will attempt to create, read, write, and delete input and output SQL Server CE replication or RDA message files on the IIS system. These files are placed in the file system directory you specified when you configured the IIS virtual directory. This is the same file system directory that contains Sscesa10.dll. You control access to the file system directory by assigning NTFS permissions to that directory.

Configuring Directory Authorization on Windows 2000 or Windows NT 4.0

To secure the file system directory

  1. Start Windows Explorer by double-clicking My Computer. Navigate to the file system directory you specified when you configured the IIS virtual directory.

  2. Right-click the file system directory. Click Properties and click the Security tab. If you do not see the Security tab, your server has a FAT file system and you can skip this step. SQL Server CE replication or RDA works with FAT file systems, but it is not secure. It is recommended that you use NTFS. To convert the file system to NTFS, see the Windows documentation.

  3. Click the Add button to set the file system directory permissions as follows.
    User | Required permissions
    Always grant Administrators Full Control. | Full Control
    Always grant System Full Control. | Full Control
    For anonymous authentication, grant computername\IUSR_computername or the configured IIS anonymous user account modify permission. | Modify
    For Basic or Integrated Windows authentication, grant the user or group of the client modify permission. | Modify

  4. If the Everyone group has been granted access to the SQL Server CE Server Agent DLL, it is recommended that you use the Remove button to eliminate access by the Everyone group.


Configuring IIS Encryption

Replication or RDA does not require IIS encryption; however, there are circumstances when you should use it. See "IIS Encryption" in Replication Security or RDA Security.

SSL is the most widely used method for transmitting encrypted data over the Internet. SSL uses public key cryptography to securely generate and exchange a secret key called the session key. The Windows CE client and IIS use the session key to encrypt and decrypt the data they send to one another. Using SSL encryption is optional. If you do not want to use SSL, you can skip this step.

The SSL features in IIS cannot be used until you obtain and assign a server certificate to your IIS Web server.

Configuring SSL encryption is a multistep process involving:

  1. Requesting a server certificate for your IIS Web site.

  2. Obtaining a server certificate from a certificate authority.

  3. Installing the newly issued server certificate into IIS.

  4. Enabling SSL encryption.

  5. Updating the database of trusted Certificate Authority on each of your Windows CE devices so they recognize the server certificate as authentic.


Requesting a Server Certificate

If your IIS Web server already has a server certificate, you can skip directly to Enabling SSL Encryption. Otherwise, you must request, obtain, and install an IIS server certificate.

In the following instructions, we describe how you can obtain a server certificate from a Windows 2000 standalone certification authority. See Windows 2000 online Help for more information about obtaining server certificates.


Requesting a Server Certificate on Windows 2000

To request a server certificate for IIS 5.0 on Windows 2000 from a standalone certification authority

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the Internet Information Services snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your Web site. Right-click the Web site containing your virtual directory. Click Properties and then click the Directory Security tab.

  4. Under Secure Communications, click Server Certificate to start the Web Server Certificate Wizard. If this button is not available, you have right-clicked a virtual directory, directory, or file rather than the Web server. In this case, close the dialog box and right-click the Web site.

  5. Read the opening screen of the IIS Certificate Wizard. It introduces you to the wizard and informs you of the status of any enrollments you performed in the past. Because the wizard knows the current state of your certificate requests, it displays only the appropriate options and warns you if you try to try to do something that might invalidate a pending request. Click Next.

  6. On the Server Certificate sheet, select Create a new certificate and click Next.

  7. On the Delayed or Immediate Request sheet, select Prepare a request now but send it later and click Next.

  8. On the Name and Security Settings sheet, enter the name of your Web site in the Name box. The wizard will automatically extract the friendly name of the Web site defined when you initially configured the site. This property is not used in the certificate; it is just a friendly name to help the administrator.

  9. Enter the public key length of the certificate. Server Gated Cryptography (SGC) is an extension of SSL/TLS that allows financial institutions with export versions of Windows 2000 Server to use 128-bit encryption. However, with new cryptographic export laws that allow much stronger encryption than previously available outside North America, this capability is no longer required. You can leave the check box empty. Click Next.

  10. Enter information for Organization and Organization Unit. This information will go into the certificate, so make sure it is accurate. The names must contain only the uppercase or lowercase ASCII letters A through Z, the digits 0 through 9, the space character, and the special characters ' ( ) +, - . / : = ? Names cannot contain underscores or other special characters. This limitation exists because Windows CE 3.0 and earlier cannot accept server certificates containing Unicode character strings. For more information, see Microsoft Knowledge Base article Q216947. Click Next.

  11. In Common name, enter the name of the computer to be certified. This information will go into the certificate; in fact, it is probably the most important information in the certificate, so make sure it is correct. When the Windows CE device attempts to connect to your Web site, it will compare the name contained in the server certificate with the name of the system where your Web server is actually running. If these names are not identical, SQL Server CE replication or RDA will not be able to communicate using SSL. By default, the wizard will select either the NetBIOS or DNS name of the server. If the computer is to be used as an intranet server, you can use either name. If the server is to be used on the Internet, the name must be the name of the Web server as it appears on the Internet. For example, the computer might have a NetBIOS name of WebServer and an internal DNS name of webserver.mycompany.com. However, because it will be used as a Web server on the Internet, its Internet DNS name might be www.mycompany.com. This is the name you should enter into the Common Name box. As described in Step 9, the name must contain only uppercase or lowercase ASCII letters A through Z, the digits 0 through 9, the space character, or the special characters ' ( ) +, - . / : = ? The name cannot contain underscores or other special characters. Click Next.

  12. Enter information for Country/Region, State/Province, and City/Locality. This information will be included in the certificate. When entering the state/province, enter the entire name of the state or province, not its abbreviation. Names can only contain the characters described in Step 9. Click Next.

  13. On the Certificate Request File Name sheet, enter the fully qualified name of the certificate request file. By default, the file name is C:\Certreq.txt. The certificate request will be stored as a PKCS#10 certificate request file. Click Next.

  14. On the Request File Summary sheet, review the certificate request information you have entered and click Next.

  15. On the Completing the Web Server Certificate Wizard sheet, click Finish to generate the certificate request.

  16. Click OK to close the Web Site Properties sheets.

  17. Close Internet Services Manager.


Requesting a Server Certificate on Windows NT 4.0

To request a server certificate for IIS 4.0 on Windows NT 4.0 from a standalone certification authority

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server and then expand the computer containing your site. Right-click the Web site containing your virtual directory. Click Properties and then click the Directory Security tab.

  3. Under Secure Communications, click Edit.

  4. On the Secure Communications sheet, click Key Manager.

  5. On the Key Manager sheet, expand Local Computer. Right-click your Web server and click Create New Key.

  6. Click Put the request in a file, and enter the fully qualified name of the certificate request file. The certificate request will be stored as a PKCS#10 certificate request file. Click Next.

  7. Enter any name you want for Key Name. Enter a password and a key bit length. Remember the password. You will be required to re-enter this password when you install the server certificate.

  8. Enter information for Organization and Organization Unit. This information will go into the certificate, so make sure it is accurate. The names can contain only the uppercase or lowercase ASCII letters A through Z, the digits 0 through 9, the space character, or the special characters ' ( ) +, - . / : = ? Names cannot contain underscores or other special characters. This limitation exists because Windows CE 3.0 and earlier cannot accept server certificates containing Unicode character strings. For more information, see Microsoft Knowledge Base article Q216947. Click Next.

  9. In Common name, enter the name of the computer to be certified. This information will go into the certificate; in fact, it is probably the most important information in the certificate, so make sure it is correct. When the Windows CE device attempts to connect to your Web site, it will compare the name contained in the server certificate with the name of the system where your Web server is actually running. If these names are not identical, SQL Server CE replication or RDA will not be able to communicate using SSL. If the computer is to be used as an intranet server, you can use either name. If the server is to be used on the Internet, the name must be the name of the Web server as it appears on the Internet. For example, the computer might have a NetBIOS name of WebServer and an internal DNS name of webserver.mycompany.com. However, because it will be used as a Web server on the Internet, its Internet DNS name will be www.mycompany.com. This is the name you should enter into the Common Name box. As described in step 9, the name must contain only uppercase or lowercase ASCII letters A through Z, the digits 0 through 9, the space character, or the special characters ' ( ) +, - . / : = ? The name cannot contain underscores or other special characters. Click Next.

  10. Enter information for Country/Region, State/Province, and City/Locality. This information will be included in the certificate. When entering the state or province, enter the entire name, not its abbreviation. Names must only contain the characters described in Step 9. Click Next.

  11. Enter information for Name, E-Mail address, and Phone number. Click Next.

  12. Click Finish to generate the certificate request.

  13. IIS displays a message box stating, "The request has been generated and placed in the file filename." Click OK to close the message box.

  14. Close the Key Manager sheet.

  15. Click OK to close the Secure Communications sheets.

  16. Click OK to close the Virtual Directory sheets.

  17. Close Internet Service Manager.


Obtaining a Server Certificate

You can obtain a server certificate from a remote third-party certification authority, such as VeriSign. Alternatively, you can install Windows 2000 Certificate Services and issue your own server certificate.

When you install Windows 2000 Certificate Services, you can create either an Enterprise Certification Authority or a Standalone Certification Authority. For more information about certification authorities and Windows 2000 Certificate Services, see Windows 2000 online Help.

Windows CE devices running Windows CE 3.0 or earlier do not recognize IIS server certificates signed using either the MD4 or RSA/SHA1 signature algorithms. Windows CE devices reject such certificates with the error ERROR_INTERNET_SECURITY_CHANNEL_ERROR. To be acceptable to a Windows CE device, your IIS server certificate must be signed using either the MD2 or MD5 signature algorithm.

If you want to generate IIS server certificates by using your own standalone certification authority, you must choose the Advanced option when you install Windows 2000 Certificate Services. Then select the MD2 or MD5 signature algorithm for the certificates your certification authority issues.

By default, Windows 2000 certification authorities generate RSA/SHA1 certificates. If your standalone certification authority was installed using the default RSA/SHA1 signature algorithm, you must remove the certification authority, re-install it using the Advanced option, specify the MD2 or MD5 signature algorithm, and issue a new IIS server certificate.

If you have installed Windows 2000 Certificate Services, you can determine the signature algorithm of the certification authority as follows:

  1. Start the Certification Authority snap-in. On Windows 2000, do this by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Certification Authority.

  2. In the left pane, right-click your certification authority and click Properties.

  3. Select the General tab and view the Hash algorithm property. If the Hash algorithm property is not either MD2 or MD5 you must remove and reinstall the certification authority.
Obtaining a Server Certificate from a Windows 2000 Standalone Certification Authority

To obtain a server certificate from a Windows 2000 standalone certification authority

  1. Copy the certificate request file to the system where your standalone certification authority resides.

  2. Submit the certificate request file to your standalone certification authority by running the CertReq command prompt utility. At the command prompt, run CertReq.exe and specify the name of the certificate request file. For example:
    CertReq MyCertReqFile.txt
  3. CertReq will display the Select Certification Authority dialog box containing a list of certification authorities. Select your standalone certification authority from the list and click OK.

  4. CertReq will inform you that your certificate request is pending, and it will display the numeric RequestId for your request.

  5. Start the Certification Authority snap-in. On Windows 2000 do this by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Certification Authority.

  6. In the left pane, expand the list of items under the computer containing your certification authority. Right-click Pending Requests to display the list of pending certificate requests.

  7. In the right pane, right-click the RequestId for your certificate request; click All Tasks and Issue.

  8. Close Certification Authority.

  9. Retrieve the newly issued server certificate by running the CertReq command prompt utility. At the command prompt, run CertReq.exe specifying the retrieve option and the RequestId for your certificate request. For example:
    CertReq –retrieve 3
  10. CertReq will display the Select Certification Authority dialog box containing a list of certification authorities. Select your standalone certification authority from the list and click OK.

  11. CertReq will display the Save As Outfile Name dialog box. Enter the name you want to give your certificate file and click OK. Specify .cer as the file extension. The Certification Authority will package your certificate in a PKCS#7 certificate file.


Installing the Server Certificate

After you obtain the server certificate, you must install it in IIS.


Installing the Server Certificate on Windows 2000

To install the server certificate in IIS 5.0 on Windows 2000

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel double-click Administrative Tools. In Administrative Tools double-click Internet Services Manager.

  2. On Windows 2000 Server, start the IIS snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your Web site. Right-click the Web site containing your replication or RDA virtual directory. Click Properties, and then click the Directory Security tab.

  4. Within Secure Communications, click Server Certificate to start the Web Server Certificate Wizard. If this button is not available, you have right-clicked a virtual directory, directory, or file rather than the Web server. In this case, close the dialog box and right-click the Web site.

  5. Read the Welcome to the Web Server Certificate Wizard sheet. It should indicate that you have a pending certificate request. Click Next.

  6. On the Pending Certificate Request sheet, click Process the pending request and install the certificate. Click Next.

  7. On the Process a Pending Request sheet, enter the full name of the file containing the server certificate in the Path and file name box. The file extension for the certificate file is typically .cer. Click Next.

  8. The properties of the server certificate are displayed on the Certificate Summary sheet. Click Next.

  9. On the Completing the Web Server Certificate Wizard sheet, click Finish.

  10. Click OK to close the Web Site Properties sheets.

  11. Close Internet Services Manager.


Installing the Server Certificate on Windows NT 4.0

To install the server certificate in IIS 4.0 on Windows NT 4.0

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server and expand the computer containing your site. Right-click the Web site containing your virtual directory. Click Properties and then click the Directory Security tab.

  3. Under Secure Communications, click Edit.

  4. On the Secure Communications sheet, click Key Manager.

  5. On the Key Manager sheet, expand Local Computer and your Web server.

  6. Right-click the new key request and click Install Key Certificate.

  7. In the Open dialog box, enter the full name of the file containing the server certificate. Click Open.

  8. On the Confirm Password sheet, enter the password you specified when requesting the server certificate.

  9. On the Server Bindings sheet, select the Web server to which you want to bind the server certificate.

  10. Close the Key Manager sheet. A dialog box will appear, asking if you want to commit all changes now. Click Yes.

  11. Click OK to close the Secure Communications sheet.

  12. Click OK to close the Web Site Properties sheets.

  13. Close Internet Service Manager.


Enabling SSL Encryption

After you have obtained and installed a server certificate for your IIS Web site, you must enable SSL encryption for your IIS virtual directory.


Enabling SSL Encryption on Windows 2000

To enable SSL encryption for your IIS virtual directory on Windows 2000 with IIS 5.0

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the IIS snap-in by clicking the Start button, chooding Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your Web site, and then expand the list of virtual directories for your Web site.

  4. From the list of virtual directories, right-click the IIS virtual directory you configured for SQL Server CE replication or RDA. Click Properties and click the Directory Security tab.

  5. Under Secure Communications, click Edit to display the Secure Communications sheet.

  6. Select the Require secure channel (SSL) check box to enable SSL encryption. You can select Require 128-bit encryption if this option is provided. Export restrictions and national laws might limit the availability of this option.

  7. Click OK to close the Secure Communications property sheet.

  8. Click OK to close the Directory Security property sheet.

  9. Close Internet Services Manager.


Enabling SSL Encryption on Windows NT 4.0

To enable SSL encryption for your IIS virtual directory on Windows NT 4.0 with IIS 4.0

  1. Start Internet Service Manager by clicking the Start button, choosing Programs, Windows NT 4.0 Option Pack, Microsoft Internet Information Server, and then clicking Internet Service Manager.

  2. In the left pane, expand Internet Information Server, expand the computer containing your site, and expand the list of virtual directories for your Web site.

  3. From the list of virtual directories, right-click the IIS virtual directory you configured for SQL Server CE replication or RDA. Click Properties and click the Directory Security tab.

  4. Under Secure Communications, click Edit to display the Secure Communications sheet.

  5. Select the Require secure channel check box to enable SSL encryption. You can select 128-bit encryption by clicking Encryption Settings and selecting the Require 128-bit encryption check box. Export restrictions and national laws might limit the availability of this option.

  6. Click OK to close the Secure Communications property sheet.

  7. Click OK to close the Directory Security property sheet.

  8. Close Internet Service Manager.


Updating the Database of Trusted Certificate Authorities

SSL encryption on Windows CE depends on the IIS server being trustworthy. To prove its trustworthiness, IIS must provide an acceptable server certificate to Windows CE.

IIS establishes its trustworthiness by obtaining a server certificate from a Certification Authority (CA). The CA can, in turn, have certification from a higher authority, and so on, creating a chain of trust. To determine whether a certificate is trustworthy, Windows CE determines the identity of the root CA and then determines if it is trustworthy.

Windows CE maintains a database of trusted CAs. When a secure connection is attempted, Windows CE extracts the root certificate from the certification chain and checks it against the Certificate Authority database.

The following root certificate authorities are included in the Windows CE 2.1x Schannel Certificate Authority database:

  • VeriSign/RSA Commercial

  • VeriSign/RSA Secure Server

  • VeriSign Class 2 Public Primary CA

  • VeriSign Class 3 Public Primary CA

  • VeriSign Class 4 Public Primary CA

  • Keywitness Canada, Inc.

  • GTE Cybertrust ROOT

  • Thawte Server CA

  • Thawte Premium Server CA

  • Thawte Personal Basic CA

  • Thawte Personal Freemail CA

  • Thawte Personal Premium CA

  • Microsoft Root Authority

  • Root SGC Authority

If you issue an IIS server certificate using your own standalone CA, your root certificate will not be present in the Windows CE Certificate Authority database. As a result, Windows CE will not trust your IIS server certificate. If you install such a server certificate in IIS and attempt to use SSL encryption, SQL Server CE replication or RDA will fail with ERROR_INTERNET_INVALID_CA (12045).

If you want to use server certificates that you issue yourself, you must either certify your standalone CA through one of the trusted certificate authorities or add your standalone CA root certificate to the Windows CE Certificate Authority database.

To add the root certificate of your standalone certificate authority to the Windows CE Certificate Authority database

  1. Save the root certificate of the standalone Certificate Authority to a .cer file.

  2. Install the root certificate in the Windows CE Certificate Authority database on the Windows CE device.


Saving the Root Certificate on Windows 2000

To save the root certificate on Windows 2000

  1. Start the IIS snap-in by clicking the Start button, choosing Settings, and then clicking Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager.

  2. On Windows 2000 Server, start the IIS snap-in by clicking the Start button, choosing Programs, Administrative Tools, and then clicking Internet Services Manager.

  3. In the left pane, expand the computer containing your Web site, and expand the list of virtual directories for your Web site.

  4. From the list of virtual directories, right-click the IIS virtual directory you configured for SQL Server CE replication or RDA. Click Properties and click the Directory Security tab.

  5. On the Directory Security sheet, click the View Certificate button.

  6. From the set of Certificate property sheets, click the Certification Path tab.

  7. On the Certification Path sheet, double-click the highest-level certificate in the Certification path pane to display the root certificate.

  8. From the set of Certificate sheets, click the Details tab.

  9. On the Details sheet, click the Copy to File button to start the Certificate Export Wizard.

  10. Click Next.

  11. On the Export File Format sheet, click DER encoded binary X.509 (.CER). Click Next.

  12. On the File to Export sheet, enter Rootcert.cer. Click Next.

  13. On the Completing the Certificate Export Wizard sheet, click Finish to complete the wizard.

  14. The Certificate Export Wizard will display a message stating, "The export was successful." Click OK to close the message box.

  15. Click OK to close the root Certificate sheets.

  16. Click OK to close the server Certificate sheets.

  17. Click OK to close the Web site property sheets.

  18. Close the Internet Services Manager snap-in.


Saving the Root Certificate on Windows NT 4.0

To save the root certificate on Windows 2000

  1. Double-click the file containing the server certificate.

  2. From the set of Certificate property sheets, click the Certification Path tab.

  3. On the Certification Path sheet, double-click the highest-level certificate in the Certification path pane to display the root certificate.

  4. From the set of Certificate sheets, click the Details tab.

  5. On the Details sheet, click the Copy to File button to start the Certificate Export Wizard.

  6. Click Next.

  7. On the Export File Format sheet, click DER encoded binary X.509 (.CER). Click Next.

  8. On the File to Export sheet, enter Rootcert.cer. Click Next.

  9. On the Completing the Certificate Export Wizard sheet, click Finish to complete the wizard.

  10. The Certificate Export Wizard will display a message stating, "The export was successful." Click OK to close the message box.

  11. Click OK to close the root Certificate sheets.

  12. Click OK to close the server Certificate sheets.


Updating the Database of Trusted Certificate Authorities on Windows CE

After saving the root certificate of the standalone certificate authority to the Rootcert.cer file, you must install the root certificate in the Windows CE Certificate Authority database on the Windows CE device.

To install the root certificate on the Windows CE device

  1. Copy Rootcert.exe that matches the processor type of your device from the SQL Server CE installation directory (by default, Program Files\Microsoft SQL Server CE\Device\processor family\processor type) to the \Windows directory of the Windows CE device.

  2. Copy the Rootcert.cer file that you created in the previous step to the root directory of the Windows CE device.

  3. Run Rootcert.exe from File Explorer.

The root certificate utility program (Rootcert.exe) does the following:

  1. It opens and reads the Rootcert.cer file contained in the root directory of the Windows CE device.

  2. It creates the registry key HKLM\Comm\SecurityProviders\SCHANNEL\CAs if this key does not already exist in the registry on the Windows CE device.

  3. It creates the registry key HKLM\Comm\SecurityProviders\SCHANNEL\CAs\filename, where filename is the name of the input Rootcert.cer file.

    It creates the following registry values under the HKLM\Comm\SecurityProviders\SCHANNEL\CAs\filename key:

    DWORD:Enabled = 1

    DWORD:Type = 1

    BINARY:CACert = X509 certificate bytes obtained from the .CER file.

  4. It displays the message "Root certificate installed successfully."

After updating the Windows CE registry, start the application that is invoking SQL Server CE replication or RDA. Windows CE will use the root certificate the next time SSL is invoked.

The source code for the root certificate utility program is included in the SQL Server CE Samples directory.


Configuring IP Address and Domain Name Restrictions

You can use IIS IP address and domain name restrictions to grant or deny specific computers, groups of computers, or domains access to your IIS Web site. For example, if your intranet server is connected to the Internet, you can prevent Internet users from accessing your IIS Web server by granting access only to members of your intranet and explicitly denying access to outside users. See the IIS documentation for more information.


Configuring IIS Security Auditing

You can monitor the security of SQL Server CE replication or RDA by using the security auditing mechanisms built into Windows and IIS. Auditing consists of creating auditing polices regarding access to your IIS Web server and NTFS directories and files, and monitoring the security logs to detect any access attempts by unauthorized persons. See the section on Auditing in the IIS administration documentation for additional information on security auditing.


ANSI to Unicode Conversions

If the SQL Server you are connecting to contains ANSI data, it will be converted to Unicode before being stored in the SQL Server CE database. Depending on the code page of the SQL Server and the IIS server, conversion errors may occur. To ensure that the data is converted correctly, see the following sections.

ANSI to Unicode Conversions in the Server Agent

The SQL Server CE server agent running on the IIS computer converts ANSI data in SQL Server to or from Unicode for SQL Server CE. Before doing ANSI to Unicode conversions, the server agent determines which code page the ANSI data is stored in so it uses the correct translation. The following information is taken into consideration:

  1. If no other settings are available, the ANSI code page of the IIS computer where the server agent is running is used.

  2. If you are using SQL Server 2000, the server agent will use the code page of the SQL Server. When each SQL Server is set up to correctly identify the ANSI data that is being stored, the correct translation will be selected automatically for each connection.

In all cases, you can override the code page by setting the following registry key to the desired code page:

HKLM\Software\Microsoft\MSSQLServerCE\TRANSPORT\OVERRIDE_SERVER_CP

You can use this to force a specific code page when the first two steps do not give the correct value for the data that is being stored. This is particularly useful when there is no support for your version of ANSI in the version of SQL Server that you are using. This registry setting will affect all of the ANSI to Unicode and Unicode to ANSI translations that the server agent makes for any SQL Server connection, so do not use this registry entry unless you know that all of your SQL Servers are storing ANSI data with the same code page.

In all cases, after the correct code page translation has been selected, the server agent requires that the IIS computer include the Windows NT support for that code page. If it is missing from that computer, it can be added by installing the correct Windows NT language version on the IIS computer. For example, if you are communicating with a Japanese database via an English IIS computer, then the Japanese Windows NT language version should be installed on the IIS computer.

ANSI to Unicode Conversions Outside the Server Agent

If the server agent has been correctly configured but the ANSI data is still not being handled properly, you may need to make additional adjustments. See the documentation for your provider driver to ensure that the correct settings have been made to allow the ANSI data to reach the server agent.

For example, SQL Server defines the following property for configuring OEM/ANSI character translation in its OLE DB provider driver:

SSPROP_INIT_AUTOTRANSLATE

When this property is VARIANT_TRUE, SQL Server char, varchar, or text data sent to a client DBTYPE_STR variable is converted from character to Unicode by using the SQL Server ACP, and then converted from Unicode to character by using the client ACP.

If the data is known to be of a different code page than that of either the SQL Server or the IIS computer, this property should be set to VARIANT_FALSE to force no translation to be performed on the data before reaching the server agent.

An RDA client would pass "Auto Translate = FALSE" in the OLE DB connection string to avoid ANSI to Unicode conversions prior to the data reaching the server agent.


SQL Server CE Relay

If your Windows CE device does not have direct network connectivity, then SQL Server CE Relay allows you to synchronize data between devices running SQL Server CE and SQL Server through a desktop computer's network connection.

SQL Server CE implements replication and remote data access capabilities on devices running Microsoft Windows CE using HTTP connections to servers running Microsoft Internet Information Services (IIS). SQL Server CE Relay enables the ability to connect a Windows CE device with a desktop computer using USB, serial, or IR. This eliminates the requirement for the Windows CE device to have direct network connectivity to synchronize data with the SQL Server.

Benefits of SQL Server CE Relay

The benefits of using SQL Server CE Relay include:

  • Lower computing costs. Customers with CE devices that contain modem cards may have to pay for the time they are dialed in to connect to a server. Being able to synchronize SQL Server CE data while the CE device is cradled and connected to the server can save on the overall computing costs.

  • Use in poor wireless situations. If there is bad wireless coverage in the office due to concrete walls, etc., a user could use any configured desktop to synchronize the database data with SQL Server.


How SQL Server CE Relay Works

SQL Server CE Relay runs on the desktop computer in cooperation with ActiveSync 3.1. When the InternetProxyServer property on the CE device is set to "ppp_peer:nn" (peer point-to-point protocol), where "nn" is a specified client port number. ActiveSync recognizes the ppp_peer command and any requests sent to this destination will appear at the desktop machine on the associated client port.

Important The InternetProxyServer property must be configured properly to use SQL Server CE Relay.

If Relay is running on the desktop and has been configured to listen on the same port, it accepts the request from the device running Windows CE and sends the request to a pre-configured server and port (either an IIS server or a proxy server).

This process works identically but in reverse when the request to synchronize data comes back from the SQL Server. The device and desktop machine must have an ActiveSync connection so the ppp_peer command can be interpreted as part of the serial, IR, or USB connection.

Configuring SQL Server CE Relay

SQL Server CE Relay can be configured to run automatically whenever there is an ActiveSync connection, or it can be started manually. SQL Server CE Relay must have a connection with ActiveSync 3.1 or above.

The name for the SQL Server CE Relay executable is SSCERelay.exe. By default, it is installed in C:\Program Files\Microsoft SQL Server CE\Relay.

Relay accepts a variety of parameters that determine the mode in which it will function. Each parameter is identified by the option label immediately preceding it. The option label and the parameter must be space delimited, but they do not need to be specified in any specific order. Options for configuring SQL Server CE Relay are:

Option | Required | Parameter Required | Definition
/clientport | yes | yes | The port that the client device will read/write to and from
/servername | yes | yes | The server or proxy server that Relay will connect to via the desktop. If you use a specific server, then the CE device must use that same server in the InternetURL property. Using a proxy server allows the client more flexibility because it can go to any server that the proxy server can reach. The IP address of the server or proxy server could also be used. When specifying the server name, UNC paths are not accepted. For example, the following would fail during synchronization: /servername "//myserver" The following would succeed during synchronization: /servername myserver
/serverport | yes | yes | The port that the server reads/writes to and from. This will usually be 80.
/noui | no | N/A | Run Relay without the icons appearing in the Windows taskbar
/register | no | N/A | Registers Relay with ActiveSync connect and disconnect features.
/unregister | no | N/A | Unregisters Relay with ActiveSync connect and disconnect features
/? | no | N/A | Calls Help at the command prompt, which lists SQL Server CE Relay parameters.
/stop | no | N/A | Halts all instances of Relay running no matter whether they were started manually or automatically


Running SQL Server CE Relay

SQL Server CE Relay can be run in a variety of configurations. For all parameter definitions, see How SQL Server CE Relay Works.

When Relay is running, the program appears as an icon in the Windows taskbar. One icon will appear for each instance of Relay. For a list of the different Relay icons, see SQL Server CE Relay Icons.

If SQL Server CE Relay is not configured properly, an error will show up in the errors text file, named sscerelay.log, on the desktop machine located in the same folder from which sscerelay.exe was executed.

Running SQL Server CE Relay Manually

If Relay will be used infrequently, it is recommended that you run the program from the command prompt each time it is needed. When run from the command prompt, Relay starts immediately.

Registering Relay with ActiveSync

You can configure Relay to automatically start and stop whenever the connection between the device running SQL Server CE and ActiveSync is active. This allows for easier and automatic synchronization of data at the same time that personal information is synchronized.

To register Relay with ActiveSync, configure Relay once with the /register option. When an ActiveSync connection is made, it will also start Relay with the parameters specified.

Important When the ActiveSync connection is broken, all instances of Relay will be stopped.

This registration with ActiceSync only needs to occur once as long as the configuration parameters, such as clientport, servername, and serverport, do not change. When you specify the /register option, two registry keys are created within Windows CE Services.

One registry key is created under HKEY_LOCALMACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect, with the string value name MicrosoftSSCERELAYAutoConnect, and it is set with the string value data based on the parameters you specified.

The second registry key is created under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect, with the string value name MicrosoftSSCERELAYAutoDisconnect, and it is set with the /Stop option.

To unregister Relay with ActiveSync, run Relay with the /unregister option. This will remove the registry keys from the Windows CE Services.

Important Only one instance of SQL Server CE Relay can be registered with ActiveSync. When a second instance is registered, it replaces the first instance in the registry.

In the following example, the parameters to run Relay would be entered at the command prompt as:

sscerelay /clientport 81 /servername CorpServer /serverport 80 /register

In this example:

  • The mobile device listens on port 81.

  • The desktop machine listens on port 80.

  • The proxy server is named CorpServer.

  • The /register option registers Relay to be run every time an ActiveSync connect is made.

    Note The InternetProxyServer property must be set to "ppp_peer:81" in the SQL Server CE ActiveX Control on the Windows CE device.

Running multiple instances of SQL Server CE Relay

Different client ports must be used when running multiple instances of Relay simultaneously. Since only one instance of Relay can be registered with ActiveSync, you must manually configure Relay to run multiple instances.

Note On Windows 98 SE, Relay is limited to 20 instances.

Stopping SQL Server CE Relay

Using the /stop option in the command prompt will halt all instances of Relay that are running.


SQL Server CE Relay Considerations

Consider the following when implementing SQL Server CE Relay:

  • SQL Server CE Relay must have a connection with ActiveSync 3.1. The partnership can be a guest connection, but it is necessary because ActiveSync enables the ability to use serial, IR, or USB connections between a device running SQL Server CE and the desktop machine.

  • Relay utilizes ppp_peer in Microsoft operating systems. It serves an IP address out to the Internet. The desktop computer can serve as a proxy to connect you to any server it is connected to. However, SQL Server CE Relay is not a true proxy server because it cannot encrypt data, but you will still have firewall support if it exists at the desktop server.

  • Relay does not support SSL encryption or Integrated Windows authentication.

  • Relay works with devices running Windows CE versions 2.11, 2.12, and 3.0.

  • Relay works with desktop machines running Windows 98 SE, Windows ME, Windows NT 4.0 with Service Pack 6 or above, or Windows 2000.
SQL Server CE Relay and Server Names

It is possible to specify one server name in SQL Server CE Relay and a different server name through the SQL Server CE ActiveX control and for the synchronization to succeed. The synchronization would succeed if the virtual directory names and security access is the same on both servers.

If the different servers are valid IIS servers, Relay is going to send the data to the server specified in its parameters. The synchronization could fail if the virtual directory or a server agent does not exist or is not properly configured. The synchronization will succeed if both servers are set up identically and each has access to the SQL Server on the backend.


SQL Server CE Relay Icons

SQL Server CE Relay appears as an icon on the Windows status bar whenever it is running. Different icons show depending on the function Relay is performing.

Icon | Description
 | Information is traveling from the device running SQL Server CE to the desktop machine.
 | Information is traveling from the desktop machine to the device running SQL Server CE.
 | Information is traveling both ways between the desktop machine and the device running SQL Server CE.
 | Represents SQL Server CE Relay is running, but information is not flowing between the desktop machine and the device running SQL Server CE.


Remote Data Access

This section contains the following information about SQL Server CE remote data access (RDA).

Topic | Description
Introducing Remote Data Access | Provides an overview of RDA. It explains how RDA is used and describes components of RDA.
Planning for RDA | Describes how you can plan for RDA. It lists the hardware and software that RDA supports. It contrasts typical RDA topologies. It describes what data can be accessed.
Implementing RDA | Describes how you can configure Internet Information Services (IIS) and SQL Server to support RDA.

For information about configuring Microsoft® Internet Information Services (IIS) to connect with SQL Server and the supported communication protocols, see Synchronizing Data with SQL Server CE. For information about writing programs that use RDA, see Remote Data Access (RDA). For troubleshooting information, see Remote Data Access and Replication.


Introducing Remote Data Access

SQL Server CE remote data access (RDA) provides a simple way for a Microsoft® Windows® CE application to "pull" data from a remote Microsoft® SQL Server™ database table and store that data in a local SQL Server CE database table. The application can read and update the local SQL Server CE database table. SQL Server CE can optionally track all changes that are made to the local table. The Windows CE application can later "push" the changed records from the local table back to the SQL Server table.

Windows CE applications can also use RDA to "submit" SQL statements to be executed on a remote SQL Server database. For example, the application could submit SQL statements that insert, update, or delete records to a remote SQL Server table. The application can invoke any SQL statement that does not return a record set, including a stored procedure on the remote system.

RDA provides a simple yet powerful way for a Windows CE application to update a remote SQL Server database or to transfer data back and forth between the remote SQL Server database and a SQL Server CE database on a Windows CE device. RDA is appropriate when the full power of SQL Server CE merge replication is not required.

RDA is Internet based. SQL Server CE communicates with SQL Server through Microsoft® Internet Information Services (IIS). By connecting through IIS, RDA takes advantage of IIS authentication and authorization services. SQL Server can be located behind a firewall or be accessed with Microsoft Proxy Server. RDA can be performed over both local area networks (LANs) and wide area networks (WANs). SQL Server CE Relay can be configured to use a desktop's network connection to communicate with SQL Server, eliminating the requirement for the Windows CE device to have a network card or modem.

The RDA communication protocol is well suited to wireless transports. Compression is used to reduce the amount of transmitted data. Encryption can be used to safeguard sensitive user data during transmission. Following a communication failure, retransmission resumes from the last successfully transmitted message buffer.


Typical Uses of RDA

Your application can use RDA in the following ways:

  • Data download

  • Data capture and upload

  • Data download, update, and upload

  • Submit SQL statements

Applications can use these techniques in combination. For example, a sales support application might use a data download to "pull" a price list to a Windows CE device. The application might use a data capture and upload to capture new orders on the device. These orders would then be "pushed" to SQL Server. The application might use a data download, update, and upload to "pull" customer information to the Windows CE device. The customer information could be updated on the device and the resulting changes "pushed" back to SQL Server. Finally, the application might submit SQL statements directly to the SQL Server database.

Data Download

An application running on the Windows CE device can pull SQL Server data to a SQL Server CE database. For example, an application might download a company employee directory, product price list, or product catalog to the Windows CE device.

Data Capture and Upload

An application running on the Windows CE device can capture data that originates from user-entered forms, a GPS system, a bar code reader, or something similar. The application can store the captured data in a SQL Server CE database on the device. Periodically the application can push the captured data from the SQL Server CE database to a SQL Server database.

Data Download, Update, and Upload

An application running on the Windows CE device can pull SQL Server data to a SQL Server CE database. The application can then update the SQL Server CE database. Periodically the application can push the changed data from the SQL Server CE database to a SQL Server database.

Submitting SQL Statements

An application running on the Windows CE device can submit SQL statements to be executed on a remote SQL Server database. This is especially useful when the Windows CE device is always connected to the network.


RDA Architecture

RDA makes use of the SQL Server CE Database Engine, SQL Server CE Client Agent, and SQL Server CE Server Agent.

The following figure shows how these components work together.

SQL Server CE Database Engine

The SQL Server CE Database Engine manages the SQL Server data store on the Windows CE device. For tracked pulls, the Database Engine tracks all database records that are inserted, updated, or deleted by maintaining a small amount of change tracking information with each record.

SQL Server CE Client Agent

The SQL Server CE Client Agent is the primary RDA component on the Windows CE device. It implements the RDA Object Interface. This is the interface that application programs call to programmatically control RDA.

When an application calls an RDA Pull method, the SQL Server CE Client Agent forwards the request to the SQL Server CE Server Agent through HTTP. When the Client Agent receives the recordset back from SQL Server, it stores the recordset in the SQL Server CE database.

When an application calls an RDA Push method, the Client Agent extracts all inserted, updated, and deleted records from the SQL Server CE database and sends them to the SQL Server CE Server Agent through HTTP.

When an application calls an RDA SubmitSQL method, the SQL Server CE Client Agent forwards the specified SQL request to the SQL Server CE Server Agent through HTTP.

SQL Server CE Server Agent

The SQL Server CE Server Agent is an ISAPI DLL. It is responsible for handling the HTTP requests made by the SQL Server CE Client Agent.

When an application calls an RDA Pull method, the Client Agent sends the request to the Server Agent through HTTP. The Server Agent connects to SQL Server through OLE DB and invokes the client's SQL statement. The Server Agent returns the resulting recordset to the Client Agent through HTTP.

When an application calls an RDA Push method, the Client Agent extracts all inserted, updated, and deleted records from the SQL Server CE database and propagates them to the SQL Server CE Server Agent through HTTP. The Server Agent connects to SQL Server through OLE DB and inserts, updates, or deletes the records in the SQL Server database. If errors occur, the Server Agent reports the errors to the Client Agent through HTTP.

When an application calls an RDA SubmitSQL method, the SQL Server CE Client Agent forwards the specified SQL request to the SQL Server CE Server Agent through HTTP. The Server Agent connects to SQL Server through OLE DB and invokes the client's SQL statement. If errors occur, the Server Agent reports the errors to the Client Agent through HTTP.


Planning for RDA

Planning for RDA is simple but important. This section helps you plan to implement RDA by listing the hardware, software, databases, and communication protocols that RDA supports. It contrasts typical RDA topologies. It describes what data can be accessed through RDA. It provides an overview of RDA security to help you plan your security architecture.


Supported Platforms

Windows CE

SQL Server CE RDA is supported on Windows CE devices running:

Platform | Operating System Version
Handheld PC Pro (H/PC Pro) | 2.11 or later
Palm-size PC (P/PC) | 2.11 or later
Pocket PC | 3.0 or later
Handheld PC 2000 (H/PC 2000) | 3.0 or later

Internet Information Services (IIS)

RDA is supported with IIS running:

  • Microsoft® Windows NT® 4.0 with Service Pack 5 and Microsoft® Internet Information Services 4.0

  • Microsoft® Windows® 2000 Professional, Server, Advanced Server, or Data Center Server with Microsoft Internet Information Services 5.0
Databases

RDA is supported with Microsoft SQL Server 6.5 Service Pack 5 or later.

RDA requires that MDAC 2.6 be present on your IIS system. SQL Server CE Setup installs MDAC 2.6 when you specify the Server Tools installation option.

See Also

Installing SQL Server CE


Configuring Microsoft SQL Server 6.5

RDA can be used to connect to Microsoft SQL Server 6.5 Service Pack 5 or later through the OLE DB Provider for SQL Server provided the catalog stored procedures are upgraded. The OLE DB Provider for SQL Server uses a set of system stored procedures, known as catalog stored procedures, to obtain information from the SQL Server system catalog. The Instcat.sql file, installed with the Development Tools Setup option in \Program Files\Microsoft SQL Server CE\Inc, includes updates to the catalog stored procedures. The SQL Server system administrator must upgrade the catalog stored procedures on the SQL Server 6.5 computer to a compatible level for RDA. Upgrading the catalog stored procedures does not affect the operation of existing SQL Server clients.

To upgrade the catalog stored procedures, the system administrator can run a script, Instcat.sql, by using the osql utility. To run osql, the computer must be installed as a client workstation for SQL Server. The system administrator should back up the master database before running the script.

At the command prompt, use the osql utility to run Instcat.sql. For example:

C:> OSQL -Usa -P sa_password -S server_name -i location\Instcat.sql

sa_password is the system administrator password, server_name is the name of the server on which an instance of SQL Server 6.5 is installed, and location is the path of Instcat.sql. You can use Instcat.sql from an installed instance of SQL Server CE (the default location is C:\Program Files\Microsoft SQL Server CE\Inc). To use osql with Integrated Windows Authentication, use the -E option instead of -U and -P (SQL Server Authentication).

Instcat.sql generates many messages. Most of these indicate how Transact-SQL statements issued by the script affected rows. These messages can be ignored, although the output should be scanned for messages that indicate an execution error. The last message should indicate that Instcat.sql completed successfully.

Instcat.sql fails when there is not enough space available in the master database to store the catalog stored procedures or to log the changes to existing procedures. If Instcat.sql fails, contact your system administrator.


RDA Topologies

RDA is easy to configure. You can choose from two RDA topologies.

In the simplest topology, both IIS and SQL Server reside on a single server. A SQL Server CE client running on a Windows CE device communicates with IIS through HTTP. IIS communicates with SQL Server through OLE DB by using any of the SQL Server network transports. You can place the IIS and SQL Server system behind a firewall.

For additional security, you can place IIS on one server and SQL Server on another server. A SQL Server CE client running on a Windows CE device communicates with IIS through HTTP. IIS communicates with SQL Server through OLE DB using any of the SQL Server network transports. You can isolate the IIS server behind a firewall. You can install another firewall between the IIS and SQL Server systems.

A desktop system may be used to connect SQL Server CE to SQL Server when SQL Server CE Relay is properly configured. For a topology that includes a desktop system, see SQL Server CE Relay.


Accessing Data

The following data type mappings are performed when RDA is used to access SQL Server data.

Note Be sure to see "Limitations on Pulling Data" following this table.

SQL Server data type | SQL Server CE data type
BIGINT (INT 8) | BIGINT (INT 8)
BINARY (n) | BINARY (n) or IMAGE If the length of the data is 510 bytes or less, RDA maps the SQL Server BINARY data to SQL Server CE BINARY; otherwise, it maps it to SQL Server CE IMAGE. If the length of the IMAGE data exceeds the length of the BINARY column, pushing tracked data back to SQL Server will fail.
BIT | BIT
CHARACTER Synonym CHAR | NATIONAL CHARACTER or NTEXT If the length of the data is 255 characters or less, RDA maps the SQL Server CHARACTER data to SQL Server CE NATIONAL CHARACTER; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the CHARACTER column, pushing tracked data back to SQL Server will fail.
CHARACTER VARYING Synonyms CHAR VARYING VARCHAR | NATIONAL CHARACTER VARYING or NTEXT If the length of the data is 255 characters or less, RDA maps the SQL Server CHARACTER VARYING data to SQL Server CE NATIONAL CHARACTER VARYING; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the CHARACTER VARYING column, pushing tracked data back to SQL Server will fail.
COMPUTED COLUMNS | Not supported The Pull method will fail if the recordset contains a COMPUTED COLUMN.
DATETIME | DATETIME
DECIMAL (see NUMERIC) |
DOUBLE PRECISION | DOUBLE PRECISION
FLOAT | FLOAT
IMAGE | IMAGE
INTEGER (INT 4) Synonyms INT | INTEGER (INT 4)
MONEY | MONEY
NATIONAL CHARACTER Synonyms NATIONAL CHAR NCHAR | NATIONAL CHARACTER If the length of the data is 255 characters or less, RDA maps the SQL Server NATIONAL CHARACTER data to SQL Server CE NATIONAL CHARACTER; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the NATIONAL CHARACTER column, pushing tracked data back to SQL Server will fail.
NTEXT | NTEXT
NUMERIC Synonyms DECIMAL DEC | NUMERIC
NATIONAL CHARACTER VARYING Synonyms NATIONAL CHAR VARYING NVARCHAR | NATIONAL CHARACTER VARYING If the data length is 255 characters or less, RDA maps the SQL Server NATIONAL CHARACTER VARYING data to SQL Server CE NATIONAL CHARACTER VARYING; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the NATIONAL CHARACTER VARYING column, pushing tracked data back to SQL Server will fail.
REAL | REAL
SMALLDATETIME | DATETIME If the precision of the DATETIME data exceeds the precision of the SMALLDATETIME column, pushing tracked data back to SQL Server will fail.
SMALLINT (INT 2) | SMALLINT (INT 2)
SMALLMONEY | MONEY If the precision of the MONEY data exceeds the precision of the SMALLMONEY column, pushing tracked data back to SQL Server will fail.
SQL_VARIANT | Not supported The Pull method will fail if the recordset contains a column with the data type SQL_Variant.
TEXT | NTEXT If the length of the TEXT data exceeds 1,073,741,823 characters, pulling data from SQL Server will fail.
TIMESTAMP | Not supported The Pull method will fail if the recordset contains a TIMESTAMP column.
TINYINT (INT 1) | TINYINT (INT 1)
UNIQUEIDENTIFIER | UNIQUEIDENTIFIER
VARBINARY (n) | VARBINARY(n) or IMAGE If the length of the data is 510 bytes or less, RDA maps the SQL Server VARBINARY data to SQL Server CE VARBINARY; otherwise, it maps it to SQL Server CE IMAGE. If the length of the IMAGE data exceeds the length of the VARBINARY column, pushing tracked data back to SQL Server will fail.

When possible, you should choose data types that are supported by both SQL Server and SQL Server CE. By doing this, you make it unnecessary for RDA to perform data mapping. When this is not possible, your application should validate the values stored in SQL Server CE to ensure that RDA can map these values between SQL Server and SQL Server CE.

You cannot pull data from a table having a PRIMARY KEY of type CHAR, NCHAR, VARCHAR, or NVARCHAR with length greater than 255 characters. These column types are mapped to NTEXT, and a PRIMARY KEY cannot be created on a NTEXT column.

Limitations on Pulling Data

SQL Server CE RDA has the following limitations:

  • Case Sensitivity

    SQL Server CE databases are not case-sensitive. You cannot perform RDA between SQL Server CE and a case-sensitive SQL Server database.

  • RowGuid

    When using RDA to pull data from a table from SQL Server that also participates in replication on the server, you must exclude the system column with the ROWGUIDCOL attribute. By default, the name of this column is RowGuid.

    For example, use "SELECT CompanyName, ContactName FROM Customers" for the SQLSelectString parameter in the Pull method, instead of "SELECT * FROM Customers."

  • Table and Column

    The following limitation is imposed on all RDA tables:

    Number of Columns available = 253 (255 - 2 system columns)

    Note Service Pack 5 is needed when RDA is used to pull data from SQL Server 6.5 and tracking is turned on.


Security

RDA uses authentication and authorization to control which Windows CE users can access SQL Server. RDA uses encryption to preserve the privacy of data transmitted between Windows CE devices and SQL Server.

RDA security depends on IIS and SQL Server security. You must understand IIS and SQL Server security to understand RDA security.

For an overview of IIS and SQL Server security and an explanation of how RDA interacts with IIS and SQL Server security, see Planning for Security. For understanding the specific configuration requirements for RDA, see Implementing RDA.


Implementing RDA

Implementing RDA involves configuring IIS and SQL Server. The process to configure IIS is the same as configuring IIS for replication. For detailed information about configuring IIS, see Configuring IIS.

Configuring SQL Server only requires granting appropriate database access for the login information supplied through RDA, as described in the following procedure.

Configuring Database Access

You must grant database access based on how you configured IIS and SQL Server Authentication.

To configure the Database Access option:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  2. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Security, and then left-click Logins.

  3. In the right pane, right-click the user ID under which the Merge Agent executes and select Properties. The Merge Agent's user ID depends on how you configured IIS and SQL Server Authentication.
    IIS authentication mode | SQL Server authentication mode | Must grant database access to
    Anonymous Authentication | Integrated Windows Authentication | computername\IUSR_computername or the configured IIS anonymous user account.
    Basic Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Integrated Windows Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Anonymous, Basic, or Integrated Windows Authentication | SQL Server Authentication | The user specified in the SQL Server OLEDBConnectionString parameter of the Pull, Push, or SubmitSQL method in the RDA Object.

  4. Click the Database Access tab.

  5. Select the Permit check box for your database.

  6. Click OK to close the SQL Server Login Properties sheets, and then close Enterprise Manager.

See Also

Configuring IIS


Replication

This chapter contains the following information about replication.

Topic | Description
Introducing Replication | Provides an overview of Microsoft® SQL Server™ CE replication and explains how it is used. It describes the components of SQL Server CE replication and how those components work.
Planning for Replication | Describes how you can plan for SQL Server CE replication. It lists the hardware and software that replication supports. It contrasts typical SQL Server CE replication topologies. It describes what data can be replicated.
Implementing Replication | Describes how you can configure SQL Server to support SQL Server CE replication.
Managing Replication | Describes how you can administer and monitor SQL Server CE replication.

For information about configuring Microsoft® Internet Information Services (IIS) to connect with SQL Server and the supported communication protocols, see Synchronizing Data with SQL Server CE. For information about writing programs that use replication, see Replication. For troubleshooting information, see Remote Data Access and Replication.


Introducing Replication

Microsoft® SQL Server™ CE replication is based on Microsoft® SQL Server™ 2000 merge replication. This makes replication ideally suited to portable devices because it allows data to be updated autonomously on the portable device and the server. The data can later be merged when the device is connected to SQL Server.

Replication is Internet based. SQL Server CE synchronizes with SQL Server by establishing an HTTP connection to the SQL Server Publisher by using Microsoft® Internet Information Services (IIS). By connecting through IIS, replication takes advantage of IIS authentication and authorization services. The SQL Server Publisher can be located behind a firewall or be accessed with Microsoft Proxy Server. Replication can be performed over local area networks (LANs) and wide area networks (WANs). SQL Server CE Relay can be configured to use a desktop's network connection to communicate with SQL Server, eliminating the requirement for the Windows CE device to have a network card or modem.

The replication communication protocol is well suited to wireless transports. Compression is used to reduce the amount of transmitted data. Encryption can be used to safeguard sensitive user data during transmission. Following a communication failure, transmission resumes from the last successfully transmitted message buffer.

You can use row and column filters to define and maintain subsets of data that can be published to different sites. Row filtering can be used to publish a subset of rows in a published table. For example, in a service organization, each service representative might only need to receive the customer records for the accounts they service. Column filtering can be used to publish a subset of columns in a published table. For example, a column filter could be used to eliminate large text or image columns that may be inappropriate on a Microsoft® Windows® CE device.

Row and column filtering can be used on the same article within a publication. You can use filtering to specify the data that is published to each Windows CE device. For more information about filtering published data, see the replication documentation in SQL Server Books Online.


Typical Uses of Replication

Your application can use replication in the following ways:

  • Data download

  • Data capture and upload

  • Data download, update, and upload

Applications can use these techniques in combination. For example, a sales support application might use data download to publish a price list to a Windows CE device. The application might use data capture and upload to capture new orders on the device. These orders would then be sent to the SQL Server Publisher. The application might use data download, update, and upload to publish customer information to the Windows CE device. The customer information could be updated on the device and the resulting changes propagated back to the SQL Server Publisher.

Data Download

An application running on the Windows CE device can subscribe to a SQL Server publication. This causes the subscription to be downloaded to a SQL Server CE database on the device. For example, an application might subscribe to a company employee directory, product price list, or product catalog.

Data Capture and Upload

An application running on the Windows CE device can capture data that originates from user-entered forms, a GPS system, a bar code reader, or something similar. The application can store the captured data in a SQL Server CE database on the device. Periodically the application can initiate replication synchronization to transfer the captured data from the SQL Server CE database to the SQL Server Publisher. From the Publisher, the data can then be propagated to other Subscribers.

Data Download, Update, Upload

An application running on the Windows CE device can subscribe to a SQL Server publication. This causes the subscription to be downloaded to a SQL Server CE database on the device. The application can then update the SQL Server CE database. Periodically the application can initiate replication synchronization. During synchronization, the updates made to the subscription are sent to the Publisher where they are merged into the Publisher's database. Similarly, changes made at the Publisher since the initial download or most recent merge are sent to the Windows CE device where they are merged into the subscription. These periodic merge operations keep the data on the server and the Windows CE device synchronized.


Replication Architecture

Replication makes use of the SQL Server CE Database Engine, SQL Server CE Client Agent, SQL Server CE Server Agent, and SQL Server CE Replication Provider.

SQL Server CE Database Engine

The SQL Server CE Database Engine manages the SQL Server data store on the Windows CE device. For subscription databases, the Database Engine tracks all database records that are inserted, updated, or deleted by maintaining a small amount of change tracking information with each record.

SQL Server CE Client Agent

The SQL Server CE Client Agent is the primary SQL Server CE replication component on the Windows CE device. It implements the SQL Server CE Replication Object interface. This is the interface that applications call to programmatically control replication. When synchronization occurs, the SQL Server CE Client Agent extracts all inserted, updated, and deleted records from the SQL Server CE Subscriber and propagates them to the SQL Server CE Server Agent through HTTP. Conversely, when the SQL Server CE Server Agent propagates data changes at the Publisher back to the Windows CE device, it is the SQL Server CE Client Agent that applies these changes to the SQL Server CE subscription database.

SQL Server CE Server Agent

The SQL Server CE Server Agent is an ISAPI DLL. It is responsible for handling the HTTP requests made by the SQL Server CE Client Agent. When synchronization occurs, the SQL Server CE Server Agent creates a new input message file on the IIS server and writes the data insert, update, and delete requests sent by the SQL Server CE Client Agent into that file. When all data insert, update, and delete requests have been written to the input message file, the SQL Server CE Server Agent initiates the SQL Server Reconciler process and waits for it to complete.

When the SQL Server Reconciler process is completed, the SQL Server CE Server Agent locates the output message file created by the SQL Server CE Replication Provider. This file contains the changes that have occurred at the publisher and must be applied to the subscription database on the Windows CE device. The SQL Server CE Server Agent reads the output message file and transmits it to the SQL Server CE Client Agent on the Windows CE device.

SQL Server CE Replication Provider

The SQL Server Reconciler invokes the SQL Server CE Replication Provider when synchronization is performed. The SQL Server CE Replication Provider reads the input message file to inform the SQL Server Reconciler about changes made to the SQL Server CE subscription database that must be applied to the publication. The SQL Server Reconciler, in turn, informs the SQL Server CE Replication Provider about changes made at the Publisher that must be applied to the subscription database on the Windows CE device. The SQL Server CE Replication Provider writes these changes to an output message file it creates on the IIS system.


How Replication Works

SQL Server CE merge replication uses this process:

  1. You create a publication containing SQL Server data that will be published to other sites, including Windows CE devices running SQL Server CE. A publication is simply a collection of articles. An article is a table that is enabled for replication.

  2. A Windows CE application can subscribe to the publication by using the SQL Server CE Replication Object. When the subscription is created, the initial snapshot is downloaded from the Distributor to create the subscription database on the Windows CE device.

  3. The subscription database on the Windows CE device can then be updated by applications running on that device.

  4. Periodically, the updates made at the SQL Server CE Subscriber are sent to the Publisher and merged with data updates made at the Publisher and data updates made at other Subscribers that have been propagated to the Publisher. Similarly, changes made at the Publisher since the initial download or most recent merge are sent to the Windows CE device where they are merged into the subscription database.
Publishing Data

You can use publications to specify the data that is published. Publications are tailored to different users or groups of users. In some cases, all users may need exactly the same data. For example, every employee might need a copy of the company employee directory. In other cases, different groups of users might need different partitions of data. For example, sales representatives may need one set of data, while customer support technicians need a different set of data. Individuals might also need data specifically filtered for them. For example, a sales representative might need the data for their own customer accounts.

You can create a publication and specify which articles it contains. A publication contains one or more articles. An article is a published table. Although SQL Server publications may contain other database objects, such as stored procedures, views, and user-defined functions, SQL Server CE replication ignores these objects and does not include them in your SQL Server CE subscription. You specify which of the table rows and columns are included in the article. For more information, see the Replication section in SQL Server Books Online.

Subscribing to Publications

After you define the publication, a Windows CE application can subscribe to it by calling the methods exposed by the SQL Server CE Replication Object on the Windows CE device. When the subscription is created, the initial snapshot is applied from the Distributor to the subscription database on the SQL Server CE Subscriber.

Updating Data at the Subscriber

Windows CE applications can update the subscription database. SQL Server merge replication allows each subscription database to be updated autonomously. Updates may occur whether or not the Windows CE device is connected to the network and to the Publisher. Each SQL Server CE database uses change tracking to keep track of INSERT, UPDATE, and DELETE statements made at the SQL Server CE Subscriber.

Synchronizing Data

Typically, the user periodically connects the Windows CE device to the network. This allows the Windows CE application program to synchronize changes made at the Subscriber with changes made at the Publisher. The Windows CE application initiates synchronization by calling the synchronization methods exposed by the SQL Server CE Replication Object. The SQL Server CE Replication Object is part of the SQL Server CE Client Agent.

The SQL Server CE Client Agent performs synchronization by invoking the SQL Server CE Server Agent. The SQL Server CE Server Agent is an ISAPI DLL that is hosted by IIS. The SQL Server CE Client Agent and SQL Server CE Server Agent communicate using the HTTP protocol.

The SQL Server CE Client Agent sends the SQL Server CE Server Agent change history information concerning each record that has been inserted, updated, or deleted in the subscription database. The SQL Server CE Client Agent uses the change tracking information maintained by the SQL Server CE database to locate all of the modified database records. The SQL Server CE Server Agent writes this change history information to an input message file on the IIS system. If a communication failure interrupts the transfer of change history information, the system is able to restart transmission from the last successfully transmitted block of change history information. This makes synchronization possible even if the network is not reliable.

When all of the change history information has been transferred from the SQL Server CE Client Agent to the SQL Server CE Server Agent and written to the input message file, the SQL Server CE Server Agent invokes the SQL Server Reconciler.

The SQL Server Reconciler conducts the merge. The SQL Server Reconciler invokes both the SQL Server Replication Provider and the SQL Server CE Replication Provider.

The SQL Server CE Replication Provider runs on the SQL Server Publisher. The SQL Server CE Replication Provider reads the input message file. It conveys information about the changes made to the SQL Server CE subscription database to the SQL Server Reconciler. The SQL Server Reconciler calls the SQL Server Replication Provider to incorporate these changes into the publication database.

The SQL Server Reconciler then searches the publication database looking for inserts, updates, and deletes that must be propagated to the SQL Server CE Subscriber. These changes may have occurred at the Publisher or may have been propagated to the Publisher by other Subscribers. The SQL Server Reconciler sends all of the changes to the SQL Server CE Replication Provider. The SQL Server CE Replication Provider writes these changes to the output message file.

The SQL Server Reconciler detects and resolves conflicts. Conflicts occur when updates are made to the same record. The SQL Server Reconciler resolves these conflicts by using conflict resolvers. You can choose from the conflict resolvers provided with SQL Server to implement simple forms of conflict resolution for your SQL Server CE replication applications.

For example, the first change to propagate to the Publisher can be configured to always win any conflict that may occur. Alternatively, you can write custom conflict resolvers to implement more sophisticated solutions. The SQL Server Reconciler invokes the custom conflict resolver, passing it the conflicting data records. The custom conflict resolver resolves the conflict.

The SQL Server Reconciler notifies the SQL Server CE Server Agent when the merge is complete at the Publisher.

The SQL Server CE Server Agent communicates to the SQL Server CE Client Agent that the merge is complete and that the output message file is present and ready to be processed.

The SQL Server CE Client Agent relies upon the SQL Server CE Server Agent to read the output message file on its behalf. The SQL Server CE Client Agent processes the output message file block by block and applies each change to the subscription database on the Windows CE device. By processing the output message file in this way, the SQL Server CE Client Agent avoids writing the entire output message file on the Windows CE device. This conserves storage space on the Windows CE device. After the SQL Server CE Client Agent has incorporated all changes into the subscription database on the Windows CE device and conflicts (if any) have been resolved, the publication and subscription databases are synchronized and data is converged. Because updates can occur continuously, you would need to stop all updates at the Publisher and at all Subscribers and then run several merges before data values would be identical at the Publisher and at the Subscribers.


Planning for Replication

Planning for SQL Server CE replication is simple but important. This chapter helps you plan to implement SQL Server CE replication by listing the hardware and software that SQL Server CE supports. It contrasts typical SQL Server CE replication topologies. It describes what data can be replicated. It provides information regarding limitations on published data.


Supported Platforms

Windows CE

SQL Server CE replication is supported on Windows CE devices running:

  • Windows CE OS 2.11 or later. This includes H/PC Pro and P/PC devices.

  • Windows CE OS 3.0 or later. This includes Pocket PC and H/PC 2000 devices.
Microsoft Internet Information Services (IIS)

SQL Server CE replication is supported with IIS running:

  • Microsoft® Windows NT® 4.0 with Service Pack 5 and Microsoft Internet Information Services 4.0

  • Microsoft® Windows® 2000 Professional, Server, Advanced Server, or Data Center Server with Microsoft Internet Information Services 5.0.
Databases

SQL Server CE replication is supported with SQL Server Publishers and Distributors running any edition of Microsoft SQL Server 2000. SQL Server CE replication is not supported with earlier versions of SQL Server, with Microsoft® Data Engine 1.0, or with the Microsoft® Jet Database Engine.

See Also

Installing SQL Server CE


Replication Topologies

You can configure SQL Server CE replication in a variety of ways. You should choose your configuration based on the following factors:

  • Performance

    The performance of your system depends on the number of Windows CE devices you must support, the frequency with which the devices must synchronize with the server, the timeframe during which synchronization must occur, and the load that each device imposes on the server while synchronizing.

  • Security

    The configuration you choose is influenced by the security requirements of your application.

Basic Configuration Rules

The following basic configuration rules govern your SQL Server CE replication configuration:

  • The SQL Server CE Subscriber is always an anonymous Subscriber. Individual SQL Server CE Subscribers cannot be assigned a merge replication conflict resolution priority. The merge replication conflict resolution priority for SQL Server CE Subscribers is always 0.

  • SQL Server CE cannot be a Publisher or Distributor. Two or more Windows CE devices can only share a publication by subscribing to the same SQL Server 2000 publication.

  • An SQL Server CE Subscriber must always synchronize with the same Publisher. Synchronizing with alternate synchronization partners is not supported.
Topologies

You can choose from a variety of SQL Server CE replication topologies. Here are some of the more common ways to configure SQL Server CE replication.

In the simplest SQL Server CE replication topology, IIS, the SQL Server Publisher, and the SQL Server Distributor all reside on a single server. SQL Server CE Subscribers, running on Windows CE devices, synchronize by connecting to IIS on the Publisher. The Publisher may be located behind a firewall.

For additional security, you may want to place IIS on one server and configure the SQL Server Publisher and Distributor on another server. The IIS server may be isolated from the Internet by a firewall. SQL Server CE clients, running on Windows CE devices, synchronize by connecting to IIS. Another firewall can isolate the SQL Server Publisher and Distributor from the IIS system.

To increase capacity, you may want to place IIS, the SQL Server Publisher, and the SQL Server Distributor on three separate servers. The IIS server can be isolated from the Internet by a firewall. SQL Server CE Subscribers, running on Windows CE devices, synchronize by connecting to IIS. Other firewalls can be used to isolate the SQL Server Publisher and Distributor from the IIS system. By placing IIS, the Publisher, and the Distributor on separate servers, you spread the work of synchronization across multiple servers.

If you must support very large numbers of SQL Server CE Subscribers that synchronize at the same time, you may want to partition the work across multiple IIS systems. You can do this by assigning groups of Windows CE devices to individual IIS systems and republishing the SQL Server publication to each of these systems. Individual SQL Server CE Subscribers would always synchronize with their specified Publisher (different SQL Server CE clients could be assigned to different Publishers).

A desktop system may be used to synchronize SQL Server CE to SQL Server when SQL Server CE Relay is properly configured. For a topology that includes a desktop system, see SQL Server CE Relay.

SQL Server CE replication can be used on a Windows NT 4.0 or Windows 2000 cluster containing a farm of IIS Web servers. However, the SQL Server CE Server Agent ISAPI DLL maintains session state across client calls. You must use load-balancing hardware or software that is capable of maintaining a "sticky" connection between the SQL Server CE Client Agent and the SQL Server CE Server Agent running on the IIS Web server.

Load-balancing systems typically work as follows. Clients access the cluster using a common domain name with a single virtual IP address. The load-balancing hardware or software intercepts the incoming HTTP traffic and directs it to one of the servers in the cluster. Because SQL Server CE replication maintains session state within IIS, you must ensure that your load-balancing hardware or software that distributes incoming HTTP requests among the IIS servers always routes any individual client's request to the same IIS server.

SQL Server CE can be used with a variety of load-balancing systems, including Windows 2000 Network Load Balancing (NLB), Windows NT4.0 Load Balancing Services (WLBS), and Cisco LocalDirector network/router hardware. All of these load-balancing systems are capable of maintaining sticky connections between clients and Web servers.

Windows 2000 Network Load Balancing (NLB)

Windows 2000 Network Load Balancing (NLB) is included as part of Microsoft Windows 2000 Advanced Server and Windows 2000 Datacenter Server. NLB can be use with SQL Server CE because NLB supports "Client Affinity". When Client Affinity is specified, NLB ensures that the client is always directed to the same IIS server within the cluster. Note, however, that should a server or network failure occur during a "stateful" client session, a new logon is required to reauthenticate the client and reestablish session state. Also, adding a new IIS server to the cluster will redirect some client traffic to the new server, which can affect existing sessions.

When you use NLB, you must set NLB Affinity to either Single (the default) or Class C. Single affinity directs all client requests from the same IP address to the same IIS server. Class C affinity directs all client requests from a range of TCP/IP Class C addresses to the same IIS server. Use Class C affinity when there is more than one proxy server at the client's site. In this case, requests from a single client may go through different proxy servers and may therefore appear to originate from different clients. Class C affinity ensures that clients that use multiple client proxy servers will have their TCP connections directed to the same IIS server. Class C affinity only works when all of the client's proxy servers are located within the same 256 host Class C address range. You specify affinity as part of configuring the NLB Port Rules.

For more information, see http://www.microsoft.com/windows2000/library/howitworks/cluster/nlb.asp

Windows NT 4.0 Load Balancing Services (WLBS)

Windows NT 4.0 Load Balancing Services (WLBS) was originally released as part of Windows NT Server, Enterprise Edition. WLBS was renamed Network Load Balancing (NLB) in Windows 2000. The description of NLB above applies equally to WLBS. Only the name has changed.

For more information, see http://www.microsoft.com/ntserver/ntserverenterprise/techdetails/overview/NTSEE.asp


Publishing Data and Database Objects

Supported Data Types and Data Type Mappings

The following data type mappings are performed when replicating between SQL Server and SQL Server CE.

Note Be sure to see Limitations on Published Data.

SQL Server Data Type | SQL Server CE Data Types
BIGINT (INT 8) | BIGINT (INT 8)
BINARY (n) | BINARY (n) or IMAGE If the length of the data is 510 bytes or less, SQL Server CE replication maps the SQL Server BINARY data to SQL Server CE BINARY; otherwise, it maps it to SQL Server CE IMAGE. If the length of the IMAGE data exceeds the length of the BINARY column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
BIT | BIT
CHARACTER Synonym CHAR | NATIONAL CHARACTER or NTEXT If the length of the data is 255 characters or less, SQL Server CE replication maps the SQL Server CHARACTER data to SQL Server CE NATIONAL CHARACTER; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the CHARACTER column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
CHARACTER VARYING Synonyms CHAR VARYING VARCHAR | NATIONAL CHARACTER VARYING or NTEXT If the length of the data is 255 characters or less, SQL Server CE replication maps the SQL Server CHARACTER VARYING data to SQL Server CE NATIONAL CHARACTER VARYING; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the CHARACTER VARYING column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
COMPUTED COLUMNS | Not supported COMPUTED COLUMNS are vertically partitioned out of all SQL Server CE subscriptions.
DATETIME | DATETIME
DECIMAL (see NUMERIC) |
DOUBLE PRECISION | DOUBLE PRECISION
FLOAT | FLOAT
IMAGE | IMAGE
INTEGER (INT 4) Synonyms INT | INTEGER (INT 4)
MONEY | MONEY
NATIONAL CHARACTER Synonyms NATIONAL CHAR NCHAR | NATIONAL CHARACTER If the length of the data is 255 characters or less, SQL Server CE replication maps the SQL Server NATIONAL CHARACTER data to SQL Server CE NATIONAL CHARACTER; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the NATIONAL CHARACTER column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
NTEXT | NTEXT
NUMERIC Synonyms DECIMAL DEC | NUMERIC
NATIONAL CHARACTER VARYING Synonyms NATIONAL CHAR VARYING NVARCHAR | NATIONAL CHARACTER VARYING If the length of the data is 255 characters or less; SQL Server CE replication maps the SQL Server NATIONAL CHARACTER VARYING data to SQL Server CE NATIONAL CHARACTER VARYING; otherwise, it maps it to SQL Server CE NTEXT. If the length of the NTEXT data exceeds the length of the NATIONAL CHARACTER VARYING column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
REAL | REAL
SMALLDATETIME | DATETIME If the precision of the DATETIME data exceeds the precision of the SMALLDATETIME column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
SMALLINT (INT 2) | SMALLINT (INT 2)
SMALLMONEY | MONEY If the precision of the MONEY data exceeds the precision of the SMALLMONEY column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.
SQL_VARIANT | SQL_VARIANT is mapped to NTEXT.
TEXT | NTEXT If the length of the TEXT data exceeds 1,073,741,823 characters, synchronization will fail when the data is sent from the SQL Server publication to the SQL Server CE subscription.
TIMESTAMP | Not supported TIMESTAMP is vertically partitioned out of all SQL Server CE Subscriptions.
TINYINT (INT 1) | TINYINT (INT 1)
UNIQUEIDENTIFIER | UNIQUEIDENTIFIER
VARBINARY (n) | VARBINARY(n) or IMAGE If the length of the data is 510 bytes or less, SQL Server CE replication maps the SQL Server VARBINARY data to SQL Server CE VARBINARY; otherwise, it maps it to SQL Server CE IMAGE. If the length of the IMAGE data exceeds the length of the VARBINARY column, synchronization will fail when the data is sent from the SQL Server CE subscription to the SQL Server publication.

Choose data types that are supported by both SQL Server and SQL Server CE. By doing this, you make it unnecessary for replication to perform data mapping. When this is not possible, your application should validate the values stored in SQL Server CE to ensure that replication can map these values between SQL Server and SQL Server CE.

You cannot publish a table having an INDEX on columns of type CHAR, NCHAR, VARCHAR, or NVARCHAR with lengths greater than 255. Creation of the SQL Server CE subscription will fail because these column types are mapped to NTEXT, and a PRIMARY KEY cannot be created on a NTEXT column.

See Also

Limitations on Published Data


Limitations on Published Data

SQL Server CE replication has the following limitations:

  • Ranged identity columns

    SQL Server CE identity columns must have a data type of INTEGER (I4). SQL Server CE identity columns cannot have a data type of BIGINT, SMALLINT, TINYINT, DECIMAL or NUMERIC. If you subscribe to a publication having an identity column other than INTEGER (I4), the creation of that subscription will fail on SQL Server CE.

    SQL Server CE allows you to modify the identity SEED and identity INCREMENT values at the subscriber by using the ALTER TABLE table_name ALTER COLUMN column_name IDENTITY (seed,increment) statement. This allows you to manage identity ranges manually, if you want. However, if your publication includes an identity column and the AutoIdentityRange property at the publisher is TRUE, you should not modify the identity SEED or identity INCREMENT values at the Subscriber. If you specify an identity SEED that is above your allocated range identity, SQL Server CE will return an error when you attempt to insert a new record in the table. When you next synchronize, the Publisher will correct the problem by assigning your Subscriber a new identity range.

  • Dynamic filters

    SQL Server CE does not support the "Validate Subscriber Information" option. When configuring a Publication with dynamic filters, you can specify the "Validate Subscriber Information" option. However, SQL Server CE ignores the option and does not validate the subscriber information. Synchronization always uses the HostName property value specified when the subscription was initially created. If you want to specify a new HostName property, you must call the Reinitialize method prior to synchronizing.

  • Information that is not propagated to the SQL Server CE Subscriber

    You can include the following items in a SQL Server publication, but these items are not propagated to the SQL Server CE Subscriber:

    CHECK constraints

    DEFAULT definitions for columns

    Stored procedures

    Views

    User-defined functions

    Triggers

    Extended properties

    Because SQL Server CE replication cannot propagate CHECK constraints, DEFAULTs, stored procedures, user-defined functions, and triggers, you should implement equivalent logic in your SQL Server CE application. This will ensure that your SQL Server CE database remains consistent with your SQL Server database.

    If your SQL Server database includes a CHECK constraint, your SQL Server CE application should implement the corresponding check in application code.

    If your SQL Server database includes a trigger that modifies published data, the modification is not replicated to the SQL Server CE subscription. This occurs because SQL Server does not track changes made by SQL Server triggers. SQL Server assumes that a replicated trigger exists on the SQL Server subscription and has already performed the modification. You must implement the function performed by the trigger in your SQL Server CE application.

  • Case Sensitivity

    SQL Server CE databases are not case-sensitive. You cannot perform replication between SQL Server CE and a case-sensitive SQL Server database.

  • UNIQUE Constraints

    SQL Server and SQL Server CE differ slightly in the way they implement UNIQUE constraints. SQL Server allows a single NULL value in a column with a UNIQUE constraint; SQL Server CE does not allow a NULL value in this case. If you subscribe to a publication that contains a NULL value in a column with a UNIQUE constraint, the creation of that subscription will fail on SQL Server CE.

  • Snapshots

    SQL Server CE can only subscribe to publications that support the default snapshot location. SQL Server CE cannot consume a snapshot that exists in an alternate location, including both UNC and FTP, or a compressed snapshot.

  • Tables and Columns

    The following limitation is imposed on all replication tables:

    Number of Columns available = 252 = 255 - (3 system columns)

See Also

IDENTITY

Reinitialize Subscription Method


Schema Changes on Publication Databases

You can add and drop columns in a base table of an existing SQL Server publication without dropping and recreating the publication. When you add or drop a column in a published SQL Server table, that schema change will be published to the SQL Server CE subscription database when the publication is next synchronized. You must make schema changes to a published table through the replication publication properties dialog box in SQL Server Enterprise Manager or through replication stored procedures. You cannot make schema changes to published tables in any other way. For more information, see "Schema Changes on Publication Databases" in SQL Server Books Online.

Any changes made to a dropped column in the SQL Server CE subscription database that have not already been propagated to the Publisher are discarded during synchronization.

You can add articles to an existing publication. When an article is added, the SQL Server CE Subscriber must be reinitialized from the Windows CE device.


Security

SQL Server CE replication uses authentication and authorization to control which Windows CE users can replicate data with SQL Server.

SQL Server CE replication security depends on IIS and SQL Server security. You must understand IIS and SQL Server security to understand SQL Server CE replication security.

For more detailed information about IIS security and SQL Server security, see the documentation for Microsoft Internet Information Services and Microsoft SQL Server 2000.

For an overview of IIS and SQL Server security and an explanation of how replication interacts with IIS and SQL Server security, see Planning for Security. For understanding the specific configuration requirements for replication, see Implementing Replication.


Implementing Replication

Implementing SQL Server CE replication involves the following steps:

  1. Configuring SQL Server

  2. Configuring IIS

These steps are described in detail in the following sections.

See Also

Configuring SQL Server

Configuring IIS


Configuring SQL Server

Configuring SQL Server involves the following steps:

  1. Updating SQL Server system stored procedures

  2. Creating the publication

  3. Securing the publication

  4. Configuring the snapshot folder

  5. Checking the status of the Snapshot Agent

See Also

Updating SQL Server System Stored Procedures

Creating the Publication

Securing the Publication

Configuring the Snapshot Folder

Checking the Status of the Snapshot Agent


Updating SQL Server System Stored Procedures

To use replication with SQL Server 2000, you must upgrade system stored procedures in the master database by running the sp_MSmakegeneration.sql script. The upgrade only affects replication with SQL Server CE.

Important Do not perform this step with future service pack releases.

The system administrator can run this script by using the osql utility. To run osql, the computer must be installed as a client workstation for SQL Server. The system administrator should back up the master database before running sp_MSmakegeneration.sql. The sp_MSmakegeneration.sql file is installed with the Development Tools Setup option in \Program Files\Microsoft SQL Server CE\Inc.

At the command prompt, use the osql utility to run the sp_MSmakegeneration.sql script. For example:

C:> OSQL -Usa -P sa_password -S server_name -i location\sp_MSmakegeneration.sql

sa_password is the system administrator password, server_name is the name of the server on which an instance of SQL Server 2000 is installed, and location is the path of sp_MSmakegeneration.sql. sp_MSmakegeneration.sql is located in the SQL Server CE installation directory (the default location is C:\Program Files\Microsoft SQL Server CE\Inc). To use osql with Integrated Windows Authentication, use the -E option instead of -U and -P (SQL Server Authentication).

sp_MSmakegeneration.sql fails when there is not enough space available in the master database to update the system stored procedures.


Creating the Publication

You create publications for SQL Server CE by using standard SQL Server replication tools and techniques. The easiest way to create a publication is through the Create Publication Wizard.

To create a publication with the Create Publication Wizard:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  2. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing the database you want to publish, and then Databases.

  3. Right-click the database you want to publish and click New then Publication.

  4. On the Welcome to the Create Publication Wizard sheet, click Next.

  5. If this is the first publication created for this server, the wizard will ask you to configure the Distributor. On the Select Distributor sheet, select the SQL Server that will act as the Distributor. By default, the system will act as its own Distributor. Click Next.

  6. If you have not previously configured the SQL Server Agent, the Configure SQL Server Agent sheet will be displayed. Select whether you want the SQL Server Agent to start automatically. Because the replication SQL Server Agents that synchronize subscriptions run unattended, it is recommended that you configure the SQL Server Agent to start automatically. Click Next.

  7. If this is the first publication created for this server, the wizard will ask you to configure the snapshot folder location. The snapshot folder holds the snapshot files that contain the schema and data for published tables. The SQL Server CE Replication Provider must be able to read these snapshot files so it can download the initial subscription to the Windows CE device. It is recommended that you use an explicit share instead of the default administration share (for example, C$) for which you cannot grant specific permissions. The administrative share is used as a default only because it will always exist on Microsoft Windows NT 4.0 and Windows 2000, but it can only be accessed by an administrator account. To create an explicit share:
    1. Start Windows Explorer by double-clicking My Computer. Create a new NTFS or FAT file system directory to contain the snapshot folder. Place the directory on any drive you want and give it any name you want.

    2. Right-click the new directory, click Properties, and click the Sharing property tab.

    3. Click Share this folder. Enter any name you want for Share name. You can optionally enter a Comment describing the share.

    4. Click the Permissions button to display the Share Permissions sheet.

    5. Click the Add button to grant the following permission to the share.
      User | Required permissions
      Grant the SQL Server Service account and SQL Server Agent Service account full control. | Full Control
      For IIS Anonymous Authentication, grant computername\IUSR_computername or the configured IIS anonymous user account read permission.

      If IIS and the SQL Server Distributor are located on different systems, you must configure the IIS anonymous user account as a domain user account and grant that user read access. The default anonymous user computername\IUSR_computername cannot be used because it is a machine local account.

               Read
      For IIS Basic or Integrated Windows Authentication, grant the client's user or group read access. | Read

    6. Click OK to close the Share Permissions sheet.

    7. Click OK to close the property sheets.

    8. On the Specify Snapshot Folder sheet, enter the share name that you have just created. Click Next.
  8. On the Choose Publication Database sheet, select the name of the database you want to publish, and click Next. If you have published this database before, you will be asked if you want to use the existing publication as a template.

  9. On the Select Publication Type sheet, select Merge publication and click Next. SQL Server CE only supports merge publications.

  10. On the Specify Subscriber Types sheet, select the Devices running SQL Server CE check box. If you want to support subscribers other than Windows CE devices, you can select the check boxes for those subscriber types also. Click Next.

  11. On the Specify Articles sheet, select the tables you want to publish and click Next.

  12. On the Select Publication Name and Description sheet, enter a publication name and description. By default, the system uses the database name as the publication name and generates a brief publication description. You can enter a more meaningful name and description. Click Next.

  13. On the Customize the Properties of the Publication sheet, click Yes to define filters or customize other properties. Otherwise, click No. Click Next.

  14. If you chose to define filters, you can enable vertical or horizontal filtering on the Filter Data sheet. For more information about filtering, see SQL Server Books Online. Click Next.

  15. If you chose to define filters, the Allow Anonymous Subscriptions sheet will be displayed and the Yes, allow anonymous subscriptions option will automatically be selected. SQL Server CE subscribers are always anonymous subscribers. If this sheet is displayed, click Next.

  16. On the Set Snapshot Agent Schedule sheet, you can change the Snapshot Agent schedule. If you configured an explicit share for the snapshot folder or if IIS and the SQL Server Distributor are located on the same system, select the Create the first snapshot immediately check box and click Next. This will create a snapshot file that you can immediately download to your Windows CE device

    If IIS and the SQL Server Distributor are on different systems and you did not configure an explicit share for the snapshot folder, you must configure the snapshot folder before you create the initial snapshot. Leave the check box unchecked and click Next. You will configure the snapshot folder and create the snapshot when you reach the step Configuring the Snapshot Folder.

  17. On the Completing the Create Publication Wizard sheet, click Finish to create your publication.

  18. When the Create Publication Wizard finishes, click Close and close Enterprise Manager.

See Also

Securing the Publication

Configuring the Snapshot Folder

Checking the Status of the Snapshot Agent


Securing the Publication

Securing the SQL Server publication involves the following steps:

  1. Configuring Database Access

  2. Configuring the publication access list

  3. Configuring the Check Permissions option (optional)


Configuring Database Access

To add a user to the Publication Access List, you must first grant Database Access based on how you configured IIS and SQL Server Authentication.

To configure the Database Access option:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  2. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Security, and then left-click Logins.

  3. In the right pane, right-click the user ID under which the Merge Agent executes and select Properties. The Merge Agent's user ID depends on how you configured IIS and SQL Server Authentication.
    IIS authentication mode | SQL Server authentication mode | Must grant database access to
    Anonymous Authentication | Integrated Windows Authentication | computername\IUSR_computername or the configured IIS anonymous user account.
    Basic Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Integrated Windows Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Anonymous, Basic, or Integrated Windows Authentication | SQL Server Authentication | The user specified in the DistributorLogin or PublisherLogin property of the Replication Object.

  4. Click the Database Access tab.

  5. Select the Permit check box for your database.

  6. Click OK to close the SQL Server Login Properties sheets and then close Enterprise Manager.


Publication Access List

When you create a publication, SQL Server creates a publication access list (PAL) for the publication. The PAL is similar to a SQL Server access control list. It contains the list of logins that have been granted access to the publication. When replication is invoked, SQL Server checks the PAL for the IIS user, in the case of Windows Authentication, or the SQL Server login, in the case of SQL Server Authentication.

By default, the PAL contains the members of the sysadmin fixed server role and the login of the user who created the publication. You can expand or restrict access to a publication by adding or deleting logins from the PAL. You must grant access to the publication based on how you configured IIS and SQL Server Authentication.

To grant or revoke access to a publication:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  2. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Databases, the database you are publishing, and then Publications.

  3. Right-click your publication name, click Properties and then click the Publication Access List tab.

  4. Use the Add or Remove buttons to add or delete logins from the PAL. Remember that you must add the user to SQL Server before you can add the user to the PAL. For more information, see "Adding a Windows NT User or Group" in SQL Server Books Online.
    IIS authentication mode | SQL Server authentication mode | The PAL must grant access to
    Anonymous Authentication | Integrated Windows Authentication | computername\IUSR_computername or the configured IIS anonymous user account.
    Basic Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Integrated Windows Authentication | Integrated Windows Authentication | The IIS client's user or group.
    Anonymous, Basic, or Integrated Windows Authentication | SQL Server Authentication | The user specified in the DistributorLogin or PublisherLogin property of the Replication Object.

  5. Click OK to close the Publication Access List property sheets and then close Enterprise Manager.

    Note If your Publisher and Distributor are different, the new logins must exist in the PALs for both the Publisher and the Distributor. If the IIS user, in the case of Windows Authentication, or the SQL Server login, in the case of SQL Server Authentication, is not contained in the PAL, an error appears at the Subscriber.


Check Permissions

You can use the Check Permissions option to provide an enhanced level of security to your publication. The Check Permissions option ensures that the Merge Agent has the authority to upload data changes to a Publisher. When you specify this option, SQL Server verifies that the Merge Agent login has the permissions to perform INSERT, UPDATE, and DELETE statements on the publication database.

Using Check Permissions is optional. When you specify Check Permissions, both Check Permissions validation and PAL verification is performed.

If you set the Check Permissions option after the initial snapshot has been generated, a new snapshot must be generated and reapplied at the Subscriber for permissions to be validated when data changes are merged.

Configuring Check Permissions

To configure the Check Permissions option:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  2. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Databases, the database you are publishing, and then Publications.

  3. Right-click your publication name, click Properties, and click the Articles tab.

  4. Click the properties button (...) for the published article you want to configure. This displays the Table Article Properties sheets.

  5. Click the Merging Changes tab.

  6. Within Check permissions, you can select the INSERT, UPDATE, and DELETE check boxes. When these boxes are selected, SQL Server verifies that the Merge Agent is running under a user identity that has permission to insert, update, or delete data on the Publisher. If you specify Check permissions, you must grant Database Access based on how you configured IIS and SQL Server Authentication. This is described next.

  7. Click OK to close the Table Article Properties sheets.

  8. Click OK to close the Publication Properties sheets.

  9. Close Enterprise Manager.


Configuring the Snapshot Folder

If you configured an explicit share for the snapshot folder when you created your publication, you can skip this step and proceed directly to Checking the Status of the Snapshot Agent.

The snapshot folder holds the snapshot files containing the schema and data for published tables. The SQL Server CE Replication Provider must be able to read these snapshot files so that it can copy the initial subscription to the Windows CE device. You control access to the snapshot folder by assigning file system access permissions to it.

When you assign permissions to the snapshot folder, remember that the identity under which the SQL Server CE Replication Provider runs depends upon how IIS authentication is configured.

  • When IIS is configured to use Anonymous Authentication, the SQL Server CE Replication Provider runs under the identity of the Internet Guest Account (IUSR_computername). If you configure another Windows user account as the IIS anonymous user account, the SQL Server CE Replication Provider runs under the identity of that account.

  • When IIS is configured to use Basic Authentication, the SQL Server CE Replication Provider runs under the identity of the Windows user account for which the client supplied the Internet user name and password.

  • When IIS is configured to use Windows Integrated Authentication, the SQL Server CE Replication Provider runs under the client's identity.

When you configure the snapshot folder, you must also consider where IIS and the SQL Server Distributor are located. If IIS and the SQL Server Distributor are located on the same system, configure the snapshot folder as described in Configuring a Local Snapshot Folder. Otherwise, configure the snapshot folder as described in Configuring a Remote Snapshot Folder.


Configuring a Local Snapshot Folder

No snapshot folder configuration is required if IIS and the SQL Server Distributor are located on the same system and the snapshot folder is located on a FAT file system. You can skip this step and proceed directly to Checking the Status of the Snapshot Agent.

If IIS and the SQL Server Distributor are located on the same system and your snapshot folder is located on an NTFS file system, you must secure the snapshot folder so that the SQL Server CE Replication Provider can access it.

To secure the snapshot folder:

  1. Start Windows Explorer by double-clicking My Computer.

  2. Locate the snapshot folder, right-click it, and select Properties. The default location of the snapshot folder is drive\Program Files\Microsoft SQL Server\Mssql\Repldata\Unc.

  3. Click the Security tab. (If the Security tab is not displayed, you are using a FAT file system and can skip this step and proceed directly to Checking the Status of the Snapshot Agent.) Set the NTFS file system directory permissions as follows.
    User | Required permissions
    Always grant the SQL Server Service account and SQL Server Agent Service account Full Control. | Full Control
    For IIS Anonymous Authentication, grant computername\IUSR_computername or the configured IIS anonymous user account read permission. If IIS and the SQL Server Distributor are located on different systems, you must configure the IIS anonymous user account as a domain user account and grant that user read access. The default anonymous user computername\IUSR_computername cannot be used because it is a machine local account. | Read
    For IIS Basic or Integrated Windows Authentication, grant the client's user or group read permission. | Read

See Also

Checking the Status of the Snapshot Agent


Configuring a Remote Snapshot Folder

If IIS and the SQL Server Distributor are located on different systems, you must explicitly configure the snapshot folder. This is necessary because SQL Server places the snapshot folder in the drive$ share by default. The drive$ share is a special administration-only share, and you cannot grant rights to it; only administrators on the computer can access it. You must create and secure a non-administrative network share for the snapshot folder so that the Server SQL Server CE Replication Provider can read it remotely

To create and secure a non-administrative network share:

  1. Start Windows Explorer by double-clicking My Computer. Create a new NTFS or FAT file system directory to contain the snapshot folder. You may place the directory on any drive you want and give it any name you want.

  2. Right-click the new directory, click Properties, and click the Sharing tab.

  3. Click Share this folder. Enter any name you want for Share name. You can optionally enter a comment describing the share.

  4. Click the Permissions button to display the Share Permissions sheet.

  5. Use the Add button to grant the following permissions to the share.
    User | Required permissions
    Always grant the SQL Server Service account and SQL Server Agent Service account Full Control. | Full Control
    For IIS Anonymous Authentication, you must configure the IIS anonymous user account as a domain user account and grant that user read permission. The default anonymous user computername\IUSR_computername cannot be used because it a machine local account. | Read
    For IIS Basic or Integrated Windows Authentication, grant the client's user or group read permission. | Read

  6. Click OK to close the Share Permissions sheet.

  7. Click OK to close the property sheets.

  8. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, Microsoft SQL Server, and then Enterprise Manager.

  9. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing the publication, Replication, and then Publications.

  10. Right-click the publication, click Properties, and click the Snapshot Location tab.

  11. Clear the Generate snapshots in the normal snapshot folder check box. Select the Generate snapshots in the following location check box. You might be prompted to confirm that you want to change this property. If so, respond Yes. Enter the name of the newly created network share in the Folder box. You can clear the Subscribers can access this folder using FTP check box.

  12. Click OK.

  13. In the left pane, expand Replication Monitor, then Agents, and left-click Snapshot Agents.

  14. In the right pane, right-click the publication and left-click Start Agent. This will start the Snapshot Agent and create the initial snapshot.

  15. Close Enterprise Manager.


Checking the Status of the Snapshot Agent

You can use the Replication Monitor in SQL Server 2000 Enterprise Manager to check the status of the Snapshot Agent and ensure that the snapshot has been created.

To check the status of the Snapshot Agent:

  1. Start SQL Server 2000 Enterprise Manager by clicking Start, Programs, SQL Server Tools, and then Enterprise Manager.

  2. In the left pane of SQL Server 2000 Enterprise Manager, expand Microsoft SQL Servers, SQL Server Group, the computer containing the Distributor for the publication, Replication Monitor, and then Agents.

  3. In the left pane, select Snapshot Agents . The status of the snapshot agent will be displayed in the right pane.

  4. You can display more information about an entry listed in the right pane by double-clicking it.


Managing Replication

This section describes how changes are tracked and how conflicts are detected, resolved, and reported in SQL Server CE. It details some conflict resolver restrictions that are unique to SQL Server CE.


Replication Conflict Detection and Resolution

When Publishers and Subscribers are reconnected and synchronization occurs, the Merge Agent running on the Publisher detects conflicts and then determines which data will be accepted and propagated to other sites based on a resolver specified when the publication was implemented.

In SQL Server CE replication, a conflict exists when changes are made to a row in both replicas. SQL Server CE implements row-level tracking only, so regardless if the Publisher is configured with column-level tracking, a conflict occurs even if the columns affected in the corresponding rows are not the same

Note Although a Subscriber is merging with the Publisher, a conflict typically occurs between updates made at different Subscribers and not necessarily at a Subscriber and at the Publisher.

After a conflict is detected, the Merge Agent launches the conflict resolver selected for the article. The accepted changes are chosen according to the rules of the conflict resolver. SQL Server CE Subscriber conflicts are always detected, resolved, and logged at the Publisher. See SQL Server Books Online for more information about default and customer conflict resolvers.


Row-Level Tracking

SQL Server CE supports row-level tracking only. The SQL Server CE Database Engine invokes tracking when a row is inserted, updated, or deleted. When conflicts are detected at the row level, changes made to corresponding rows are considered a conflict, regardless of whether the changes are made to the same column. For example, a change is made to the address column of a Publisher row, and another change is made to the phone number column of the corresponding Subscriber row in the same table. With row-level tracking, a conflict is detected because changes were made to both rows.

Note Even if the Publisher is configured with column-level tracking, SQL Server CE masks the row as if every column has changed. Row-level tracking involves less tracking overhead, preserving valuable storage space on the device.


Building Applications

There are multiple ways to build applications with SQL Server CE. The method you choose depends on your setup and needs. This section discusses building applications with Microsoft® CE Data Access 3.1 (ADOCE), OLE DB for Windows® CE (OLE DB/CE), remote data access (RDA), and replication.


ADOCE

This section contains the Programmer's Guide for ADOCE, which discusses how to use Microsoft® CE Data Access 3.1 (ADOCE) to create, access, and modify SQL Server CE databases.


Programmer's Guide for ADOCE

This section discusses how to use ADOCE to create, access, and modify SQL Server CE databases.

Microsoft® ActiveX® Data Objects (ADO) is a strategic, high-level interface to all types of data. ADO provides consistent, high-performance access to data, whether you are creating a front-end database client or a middle-tier business object by using an application, tool, language, or Internet browser. ADO, along with OLE DB, is part of the Microsoft Universal Data Access model.

Microsoft® CE Data Access 3.1 (ADOCE) provides a subset of the desktop ADO specifically engineered to work with Windows CE. ADOCE includes its own internal database provider and enables you to have access to databases stored locally on a Windows CE device instead of working with databases stored remotely on desktop computers. The ADOCE 3.1 control can also work with data sources that use an OLE DB provider.

For detailed information on ADOCE, see the Microsoft CE Data Access 3.1 documentation.


Setting Up a Project

Before your applications can work with ADOCE and SQL Server, you need to configure your projects so that they have references to these objects.

Adding the ADOCE Control to an Application

Before you can use the ADOCE control in Microsoft® eMbedded Visual Basic®, you must create a reference to the control in the integrated development environment (IDE).

To create a reference to the ADOCE control in the IDE:

  1. On the Project menu, click References.

  2. Select the Microsoft CE ADO Control 3.1 check box.

  3. Click OK.

    Note Previous versions of the ADOCE control did not have a version number in the programmatic identifiers (ProgIDs). If you do not specifically update your previous code to refer to version 3.1 of the control, an earlier version of the control may be instantiated if it exists in a device's ROM. If the device's ROM does not contain an earlier version, you will get an "Invalid procedure call or argument: 'CreateObject'" error when you execute your application.

The following ProgIDs are used with the ADOCE 3.1 control.

ADOCE object | ProgID
Connection | ADOCE.Connection.3.1
Recordset | ADOCE.Recordset.3.1

Adding a Reference to SQL Server CE to an Application

Once SQL Server CE has been installed on a Windows CE device it can be used from a program. However, defining a reference in your project will force the SQL Server CE files to be copied to a device on which they do not already exist.

To create a reference to the SQL Server CE control in the eMbedded Visual Basic 3.0 IDE:

  1. On the Project menu, click References.

  2. Select the Microsoft CE SQL Server Control 1.0 check box.

  3. Click OK.


Connecting to a SQL Server CE Database

Before you can manipulate information in a database, you must open a connection to a valid data source. The Connection object is used to represent a connection to a data source. To open a connection to a data source, create a variable that represents the connection and then create an ADOCE Connection object by using the Set statement and CreateObject function. The following code sample shows how to do this:

Dim cn As ADOCE.Connection
Set cn = CreateObject("ADOCE.Connection.3.1")

Note When using the CreateObject function to create a reference to the ADOCE 3.1 control, you must include the version number. If the version number is omitted from the string, an earlier version of the control is used. If no earlier version of the control exists on the device, an error is returned. SQL Server CE can only be accessed through ADOCE 3.1 or later.

Once a Connection object is created, you can use the properties and methods of the Connection object to open, close, and manipulate a connection. The following code shows how to open a connection to a database on the device by using the Open method:

Set cn = CreateObject("ADOCE.Connection.3.1")
cn.ConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.1.0; data source=\Northwind.sdf"
cn.Open

Caution If you don't specify a provider string in the Open method, Open defaults to using the CEDB provider. It will create a CEDB called Test.sdf. You must specify the SQL Server CE provider string when opening an SSCE database.

In this sample, the connection string property is set before the Open method is executed. The Open method is used without any parameters. A connection string can also be used as a parameter of the Open method. When connecting to a SQL Server CE database, you must specify both the provider and data source properties in the connect string. The data source property must be set with the full path and database name.


Using ADOCE Batch Update

ADOCE exposes the ability to "batch" a series of changes to be sent to a provider at once. This is useful in client-server database engines because sending individual changes over the network can have poor performance. Since SQL Server CE is running locally, all changes are done within the scope of the current machine. SQL Server CE implements updatable cursors in a very fast, efficient mechanism directly against the local storage engine. This provides good performance, but it imposes the restriction that only a single row can be updated in a batch. If updating more than one record is required, transactions can be used to logically batch a series of changes inside the engine.


Using ADOCE from eVC

When programming in eVC to SQL Server CE, we recommend using OLEDB CE. It is also possible, however, to access SQL Server CE using eVC through ADOCE with the following steps:

  1. To generate the necessary include files, first copy Adocec31.idl, Adoce31.idl, and Adoxce31.idl from the Include directory of the Dataaccess31 install, by default \Windows CE Tools\dataaccess31\include, to the include directory of your SDK. For the Pocket PC SDK, this is \Windows CE Tools\wce300\MS Pocket PC\include, by default.

  2. In a command window, run the WceXXX.bat file in the EVC install directory that matches the OS version and processor type of your device. If you are using a Windows CE 3.0 ARM device, the default path is C:\Program Files\Microsoft eMbedded Tools\EVC\WCE300\BIN\wcearm.bat. You should use the WCEXXX subdirectory that matches your version of Windows CE and the WceXXX.bat file that matches the processor type of your device.

  3. In the command window, run midl first on the Adocec31.idl file and then on the Adoce31.idl file. You need to run midl on Adoxce31.idl only if you plan to use ADOXCE. This step will generate the include files necessary to use ADOCE through eVC.

The following code uses ADOCE to insert into a base table. For an example of error handling, see "Error Handling with ADOCE."

// You must include wceatl.h before any ADO includes.
#include <wceatl.h>

#include ".\inc\ADOCE31.h"
#include ".\inc\ADOCE31_i.c"
#include ".\inc\ADOXCE31.h"
#include ".\inc\ADOXCE31_i.c"
#include ".\inc\ADOCEc31.h"
#include ".\inc\ADOCEc31_i.c"

//--------------------------------------------------------------------
// Function: InsertData()
//
// Description:
//   Inserts a row consisting of one integer value into a base table
//   using the ADOCE Recordset object.
//
//--------------------------------------------------------------------
HRESULT InsertData(int data, BSTR bstrTableName, BSTR bstrConnectionString)
   {
   HRESULT hr = S_OK;

   IADOCERecordset   * pIADOCERecordset   = NULL;

   SAFEARRAYBOUND  bound[1];

   SAFEARRAY *      pOrdinals   = NULL;
   SAFEARRAY *      pData      = NULL;

   VARIANT   *      pvSave      = NULL;
   VARIANT *      pvData      = NULL;
   VARIANT   *      pvOrdinals   = NULL;

   VARIANT         vtOrdinals;
   VARIANT         vtData;
   VARIANT         vtConnectString;
   VARIANT         vtBaseTableName;

   VariantInit(&vtConnectString);
   VariantInit(&vtBaseTableName);
   VariantInit(&vtOrdinals);
   VariantInit(&vtData);

   // For the insert, we represent the row as field
   // number, field value pairs held in the ordinal and data arrays.

   // First, create the arrays that will hold ordinals and data.
   //
   bound[0].lLbound = 0;
   bound[0].cElements = 1;
   pOrdinals = SafeArrayCreate(VT_VARIANT, 1, bound);
   pData = SafeArrayCreate(VT_VARIANT, 1, bound);
   if(!pOrdinals || !pData)
      {
      hr = E_OUTOFMEMORY;
      goto errorInsert;
      }

   vtOrdinals.vt = VT_ARRAY | VT_VARIANT;
   vtOrdinals.parray = pOrdinals;

   vtData.vt = VT_ARRAY | VT_VARIANT;
   vtData.parray = pData;

   pvOrdinals = (VARIANT *)pOrdinals->pvData;
   pvData = (VARIANT *)pData->pvData;

   // Fill in the field num / data val pairs
   // for the row we will insert.
   //
   VariantInit(&pvData[0]);
   VariantInit(&pvOrdinals[0]);

   // We will insert the data at ordinal 0.
   //
   pvData[0].vt = VT_I4;
   pvData[0].intVal = data;

   pvOrdinals[0].vt = VT_I4;
   pvOrdinals[0].lVal = 0;

   // Get the base table rowset.
   //
   hr = CoCreateInstance(CLSID_ADOCERecordset,
               NULL,
               CLSCTX_INPROC_SERVER,
               IID_IADOCERecordset,
               (void**)&pIADOCERecordset);
   CHECK(hr,errorInsert);
   ASSERT(NULL != pIADOCERecordset);

   vtConnectString.vt      = VT_BSTR;
   vtConnectString.bstrVal = bstrConnectionString;

   vtBaseTableName.vt      = VT_BSTR;
   vtBaseTableName.bstrVal = bstrTableName;

   // Open the base table and insert our row.
   //
   hr = pIADOCERecordset->Open(vtBaseTableName,
                        vtConnectString,
                        adOpenDynamic,
                        adLockOptimistic,
                        adCmdTableDirect);
   CHECK(hr,errorInsert);

   hr = pIADOCERecordset->AddNew(vtOrdinals, vtData);
   CHECK(hr,errorInsert);

   hr = pIADOCERecordset->Close();

errorInsert:

   // Release the Recordset Object after checking for errors.
   //
   if(pIADOCERecordset)
      {

      // If we have an error, attempt to get extended error
      // information.
      if(S_OK != hr)
         {
         VARIANT vConnection;
         VariantInit(&vConnection);

         pIADOCERecordset->get_ActiveConnection(&vConnection);

         if(VT_EMPTY != vConnection.vt)
            {
            ShowADOErrors((IADOCEConnection *) vConnection.byref);
            }
         VariantClear(&vConnection);
         }

      pIADOCERecordset->Release();
      pIADOCERecordset = NULL;
      }

   // Release the Ordinals Array.
   //
   if(pOrdinals)
      {
      SafeArrayDestroy(pOrdinals);
      }

   // Release the Data Array.
   //
   if(pData)
      {
      SafeArrayDestroy(pData);
      }

   VariantClear(&vtConnectString);
   VariantClear(&vtBaseTableName);
   VariantClear(&vtOrdinals);
   VariantClear(&vtData);

   return hr;
}


Disconnecting from a Database

After you have made and saved your modifications to the database, close the connection to the data source. The following code example shows how to use the Close method to close a connection:

cn.Close
Set cn = Nothing

Note You can have only one open connection to a SQL Server CE database at a time, and this connection must be closed before invoking replication or RDA.


OLE DB/CE

This section contains a programmer's reference and guide for OLE DB for Windows® CE (OLE DB/CE). The Programmer's Reference for OLE DB/CE describes the OLE DB Provider for SQL Server CE. The Programmer's Guide for OLE DB/CE discusses a variety of details concerning the OLE DB Provider for SQL Server CE.

For more information about OLE DB, see the OLE DB Programmer's Reference in MSDN.


Programmer's Reference for OLE DB/CE

This reference supplements the OLE DB Programmer's Reference in MSDN

The SQL Server CE OLE DB Provider is an OLE DB version 2.5 -compliant provider.


Supported OLE DB Interfaces

The SQL Server CE OLE DB Provider supports the following OLE DB interfaces on the Data Source Object. Check each object to see which interface it supports.

Data Source Object

IDBCreateSession

IDBDataSourceAdmin

IDBInitialize

IDBInfo

IDBProperties

ISupportErrorInfo

Session Object

IOpenRowset

ITableDefinition

ITableDefinitionWithConstraints

ITableCreation

ITransactionLocal

IIndexDefinition

IDBSchemaRowset

IGetDataSource

ISessionProperties

IDBCreateCommand

IAlterIndex

IAlterTable

ISupportErrorInfo

Command Object

ICommand

ICommandText

ICommandPrepare

IColumnsInfo

ICommandProperties

IConvertType

IAccessor

ISupportErrorInfo

Rowset Object

IRowset

IAccessor

IColumnsInfo

IConvertType

IRowsetChange

IRowsetInfo

IRowsetIndex

IRowsetCurrentIndex

IRowsetBookmark

IRowsetUpdate

ISupportErrorInfo


SQL Server CE OLE DB Provider-Specific Interfaces

The SQL Server CE OLE DB Provider supports the following SQL Server CE-specific OLE DB interfaces:

Data Source Object

ISSCECompact

Rowset Object

IRowsetPosition

ISSCECompact

ISSCECompact is used to compact SQL Server CE databases, perform database repair, and manage compaction-related properties, such as database encryption.

This interface is defined under the DataSource cotype in the Microsoft OLE DB Programmer's Reference, "Cotypes, Structures, and Enumerated Types."

When to Implement

The SQL Server CE OLE DB Provider implements ISSCECompact.

Method | Description
Compact | Compacts or repairs a database, creating a new copy

ISSCECompact::Compact

Compact compacts or repairs a database by creating a new database. The old database is retained and is unchanged.

Syntax
HRESULT ISSCECompact::Compact(
         ULONG cPropertySets,
         DBPROPSET rgPropertySets[]);
Parameters

cPropertySets [in]

The number of DBPROPSET structures in rgPropertySets. If this is zero, the provider ignores rgPropertySets and the method does nothing.

rgPropertySets [in/out]

An array of DBPROPSET structures containing properties and values to be set. If the data source object or enumerator is uninitialized, the properties specified in these structures must belong to the Initialization property group. If the data source object is initialized, the properties must belong to the Data Source property group. If the enumerator is initialized, it is an error to call this method. If the same property is specified more than once in rgPropertySets, the value used is provider-specific. If cPropertySets is zero, this parameter is ignored.

Return Value

S_OK

The method succeeded.

E_INVALIDARG

cPropertySets was not equal to zero and rgPropertySets was a null pointer. In an element of rgPropertySets, cProperties was not zero and rgProperties was a null pointer.

DB_E_OBJECTOPEN

The database cannot be opened exclusively.

DB_SEC_E_PERMISSIONDENIED

The user does not have sufficient rights to compact the database.

DB_E_DUPLICATEDATASOURCE

A destination database with the same name already exists.

DB_S_ERRORSOCCURRED

One or more properties were not set. Properties not in error remain set. The consumer checks dwStatus in the DBPROP structures to determine which properties were not set. See IDBProperties::SetProperties for the complete description of this return code.

E_FAIL

An error occurred during compaction.

Comments

Compact removes extraneous space from a database by making a new copy of the database. Compact attempts to eliminate any corruption it finds while creating the new database. The original database is left unchanged.

Before calling Compact, ensure that adequate space exists for the newly created database. Ensure that the database is not already open in write mode; Compact fails if the database is already open in write mode. Note that the data source object does not need to be initialized to call Compact.

Compact determines the properties of the new database based on the properties of the existing database and the initialization properties passed to Compact in the data source object. The caller need only set properties that are unique for the new database. Typically only DBPROP_INIT_DATASOURCE must be passed to Compact to specify the new name for the compacted database. Compact ignores any unneeded properties.

A database can be compacted in either encrypted or non-encrypted form. This is controlled via the DBPROP_SSCEOLEDB_ENCRYPTDATABASE (Boolean) property. Note that encrypted databases must have a database password. The database password is specified by DBPROP_SSCEOLEDB_DBPASSWORD.

IRowsetPosition

IRowsetPosition is used to return exact row count and position information for the rowset. This allows providers who do not support IRowsetLocate or IRowsetScroll to expose row count and position information. This interface returns exact counts, which is not guaranteed with IRowsetLocate or IRowsetScroll

When to Implement

The SQL Server CE OLE DB Provider implements IRowsetPosition.

Method | Description
GetRecordCount | Used to retrieve the number of rows in the current rowset
GetCurrentPosition | Gets the number of the current row

IRowsetPosition::GetRecordCount

GetRecordCount retrieves the number of rows in the current rowset.

Syntax

HRESULT IRowsetPosition::GetRecordCount(
         ULONG * pcRows,
         );
Parameters

pcRows [in/out]

A pointer to an unsigned long value. This long must be allocated by the client.

Return Value

S_OK

The method succeeded.

E_INVALIDARG

pcRows was null.

E_UNEXPECTED

The rowset is in a zombied state.

Comments

This is an exact count of the number of records in the rowset.

IRowsetPosition:: GetCurrentPosition

GetCurrentPosition retrieves the number of the current row in the rowset.

Syntax
HRESULT IRowsetPosition:: GetCurrentPosition (
      ULONG * pulPosition,
          );
Parameters

pulPosition [in/out]

A pointer to an unsigned long value. This long must be allocated by the client.

Return Value

S_OK

The method succeeded.

E_INVALIDARG

pulPosition was null.

E_UNEXPECTED

The rowset is in a zombied state.

Comments

This returns the current location of the "next fetch position" in the rowset. The valid range is 1 to GetCurrentPosition. If there is no current row pulPosition is 0.


Differences in SQL Server CE OLE DB Interfaces

Some SQL Server CE OLE DB interfaces differ from the generic interfaces described in the OLE DB specification. These differences are described in this section.

IAccessor

The SQL Server CE IAccessor::CreateAccessor method ignores the DBACCESSOR_OPTIMIZED flag. The DBACCESSOR_OPTIMIZED flag has no effect on the performance of either row or parameter accessors because SQL Server CE does not use an internal row cache. All accessors provide equally good performance; thus, there is no need to optimize accessors performance when using the SQL Server CE OLE DB Provider.

IAlterTable

IAlterTable changes a table's name and properties. See Table Properties for more information about the properties that can be changed. Note that SQL Server CE supports changing the seed of an autoincrement column, but not changing a column to or from autoincrement.

IDBDataSourceAdmin

Note that SQL Server CE only supports the CreateDataSource method on this interface. This call is used to create a new database.

IOpenRowset

This interface is used to open base tables and integrated indexes. This interface cannot be used to open views.

IRowset
  • Regular Rowset

  • Becoming a Zombie

    Rowsets can become zombies if the internal resource on which they depend goes away because a transaction aborts.

  • Data Type Coercion

    We recommend that the client always bind as the native type.

  • No "By Reference" Data Binding

    The SQL Server CE OLE DB Provider supports data binding "by value" but not "by reference".

  • BLOB Support

    The SQL Server CE OLE DB Provider supports two structured storage interfaces for accessing long text and long binary data: ISequentialStream and ILockBytes.

  • IRowset::GetNextRows

    You should retrieve rows sequentially by calling GetNextRows(NULL, 0, 1...).

  • IRowset::RestartPosition

    RestartPosition is efficient when used with scrollable cursors, but it can cause query re-execution when used with nonscrollable cursors.

IRowsetChange

This interface is supported on base table cursors.

ITableDefinition

All ITableDefinition methods open tables for exclusive access. If another method already has the table open, the ITableDefinition method call will fail.

ITransactionLocal

SQL Server CE only supports the Transaction Isolation Level "Read Committed". Attempting to specify a lower Transaction Isolation Level is ignored and results in a Transaction Isolation Level of "Read Committed". Attempting to specify a higher Transaction Isolation Level will cause StartTransaction to fail.

SQL Server CE only supports single-phase commit.


SQL Server CE Cursors

SQL Server CE supports three cursor types: Base Table, Forward-Only, and Scrollable. With each of these cursors, the client can have at most one open row. This means for all supported cursor types DBPROP_CANHOLDROWS is FALSE and DBPROP_MAXOPENROWS is 1. Note also that for all cursor types DBPROP_CANSCROLLBACKWARDS is FALSE, meaning that the lRowsOffset parameter of GetNextRows must be non-negative.

Base Table

This is the fastest of the three supported cursors and the only cursor that interacts directly with the storage engine. This cursor supports updates and bookmarks, as well as Seek, SetRange, and Indices. The base table cursor also optionally supports delayed update mode by exposing the IRowsetUpdate interface when the client passes DBPROP_IRowsetUpdate as TRUE. Note that this cursor has dynamic membership, meaning both DBPROP_OTHERINSERT and DBPROP_OTHERUPDATEDELETE are TRUE.

Base Table cursors can only be opened using IOpenRowset::OpenRowset. Using a "Select * from Table" will yield a query processor cursor (Forward Only or Scrollable) and not a Base Table cursor. This is important to note because only Base Table cursors support updates.

Forward-Only

This forward-only read-only cursor is the fastest query processor cursor and the second fastest cursor overall. While this cursor is fast, it provides the least amount of functionality. It does not support bookmarks or updates.

Scrollable

This read-only scrollable cursor is the most functional query processor cursor type. The result set of this query processor cursor is cached. This provides fast cursor restarts but makes this cursor more resource intensive, especially for queries with large result sets. Note that data values will not be refreshed to changes in the underlying data; since the results are cached, changes to the underlying base tables for a query are not reflected in the query results unless the query is re-executed.

Properties

The following table shows the minimal set of properties for each cursor type.

 | Base Table | Forward-Only | Scrollable
DBPROP_BOOKMARKS | TRUE | FALSE | TRUE
DBPROP_OWNUPDATEDDELETE | TRUE | FALSE | FALSE
DBPROP_OWNINSERT | TRUE | FALSE | FALSE
DBPROP_OTHERUPDATEDELETE | TRUE | FALSE | FALSE
DBPROP_OTHERINSERT | TRUE | FALSE | FALSE
DBPROP_CANFETCHBACKWARDS | TRUE | FALSE | TRUE
DBPROP_QUICKRESTART | TRUE | FALSE | TRUE


SQL Server CE Data Types

SQL Server CE data type | OLE DB data type | OLE DB properties | SQL Server CE specifics
BIGINT | DBTYPE_I8 |  |
BINARY | DBTYPE_BYTES | DBPROP_COL_FIXEDLENGTH = VARIANT_TRUE |
BIT | DBTYPE_BOOL |  |
DATETIME | DBTYPE_DBTIMESTAMP |  | Valid year range 1753-9999; valid second range 0-59
DOUBLE PRECISION | DBTYPE_R8 |  |
FLOAT | DBTYPE_R8 |  |
IMAGE | DBTYPE_BYTES |  |
INTEGER | DBTYPE_I4 |  |
MONEY | DBTYPE_CY |  |
NATIONAL CHARACTER | DBTYPE_WSTR | DBPROP_COL_FIXEDLENGTH = VARIANT_TRUE |
NATIONAL CHARACTER VARYING | DBTYPE_WSTR | DBPROP_COL_FIXEDLENGTH = VARIANT_FALSE |
NTEXT | DBTYPE_WSTR |  |
NUMERIC | DBTYPE_NUMERIC |  |
REAL | DBTYPE_R4 |  |
SMALLINT | DBTYPE_I2 |  |
UNIQUEIDENTIFIER | DBTYPE_GUID |  |
TINYINT | DBTYPE_UI1 |  |
VARBINARY | DBTYPE_BOOL | DBPROP_COL_FIXEDLENGTH = VARIANT_FALSE |


SQL Server CE Schema Rowsets

This section describes the schema rowsets that the SQL Server CE OLE DB Provider uses to expose SQL Server CE-specific functionality.

OLE DB schema name | ADO schema name | Description and GUID (if needed)
DBSCHEMA_COLUMNS | adSchemaColumns | The COLUMNS rowset identifies the columns of tables defined in the catalog that are accessible to a given user.
DBSCHEMA_INDEXES | adSchemaIndexes | The INDEXES rowset identifies the indexes defined in the catalog that are owned by a given user.
DBSCHEMA_KEY_COLUMN_USAGE | adSchemaKeyColumnUsage | The KEY_COLUMN_USAGE rowset identifies the columns defined in the catalog that are constrained as keys by a given user.
DBSCHEMA_PROVIDER_TYPES | adSchemaProviderTypes | The PROVIDER_TYPES rowset identifies the (base) data types supported by the data provider.
DBSCHEMA_TABLE_CONSTRAINTS | adSchemaTableConstraints | The TABLE_CONSTRAINTS rowset identifies the table constraints defined in the catalog that are owned by a given user.
DBSCHEMA_TABLES | adSchemaTables | The TABLES rowset identifies the tables defined in the catalog that are accessible to a given user.
DBSCHEMA_TABLES_INFO | adSchemaTablesInfo | The TABLES_INFO rowset identifies the tables defined in the catalog that are accessible to a given user.


SQL Server CE OLE DB Properties Reference

The OLE DB specification allows data providers to implement provider-specific properties. These properties allow the programmer to have access to functionality that is outside the boundaries of the OLE DB specification. This section describes the properties that are exposed by the SQL Server CE OLE DB Provider.

Column Properties

The DBPROPSET_COLUMN property set contains the following properties. All of these properties are in the Column property group.

Property ID | Description
DBPROP_COL_AUTOINCREMENT | Type: VT_BOOL Typical R/W: R/W Description: Autoincrement Specifies whether the values of the identity column are autoincrementing. There may be only one autoincrementing column per table
DBPROP_COL_DEFAULT | Type: Any Typical R/W: R/W Description: Default Specifies the default value for this column. This may be a constant, an expression, or the getdate() function. Queries are not supported as default values. Note that string literals must be quoted: for example, 'default'
DBPROP_COL_FIXEDLENGTH | Type: VT_BOOL Typical R/W: R/W Description: Fixed Length
DBPROP_COL_INCREMENT | Type: VT_BOOL Typical R/W: R/W Only used if autoincrement is true
DBPROP_COL_ISLONG | Type: VT_BOOL Typical R/W: R/W Description: Is Long
DBPROP_COL_NULLABLE | Type: VT_BOOL Typical R/W: R/W Description: Nullable SQL Server CE supports all types as nullable.
DBPROP_COL_SEED | Type: VT_BOOL Typical R/W: R/W Only used if autoincrement is true

Data Source Information Properties

The DBPROPSET_DATASOURCEINFO property set contains the following properties. All of these properties are in the Data Source Information property group. These properties are read-only in the SQL Server CE OLE DB Provider and constitute a set of static information about the provider and data store.

Property ID | Description
DBPROP_DBMSNAME | Type: VT_BSTR Typical R/W: R only Description: DBMS Name Specifies the name of the product accessed by the provider. For this provider, the string is "SQL Server for Windows CE".
DBPROP_DBMSVER | Type: VT_BSTR Typical R/W: R only Description: DBMS Version Specifies the version of the product accessed by the provider. For this provider, the string is "1.00.0000".
DBPROP_DSOTHREADMODEL | Type: VT_I4 Typical R/W: R only Description: Data Source Object Threading Model Specifies the threading model of the data source object. For this provider, the value is DBPROPVAL_RT_FREETHREAD.
DBPROP_IDENTIFIERCASE | Type: VT_I4 Typical R/W: R only Description: Identifier Case Sensitivity Specifies how identifiers respond to case. For this provider, the value is DBPROPVAL_IC_MIXED, which indicates that identifiers in SQL are case-insensitive and are stored in mixed case in the system catalog.
DBPROP_MULTIPLESTORAGEOBJECTS | Type: VT_BOOL Typical R/W: R only Description: Multiple Storage Objects For this provider, the value is always VARIANT_FALSE, which indicates that the provider supports only one open storage object at a time.
DBPROP_NULLCOLLATION | Type: VT_I4 Typical R/W: R only Description: NULL Collation Order For this provider, the value is always DBPROPVAL_NC_LOW, which indicates that null values are sorted at the low end of the list.
DBPROP_OLEOBJECTS | Type: VT_I4 Typical R/W: R only Description: OLE Object Support Specifies a bitmask that indicates the ways in which the provider supports access to BLOBs and COM objects stored in columns. For this provider, the value is always DBPROPVAL_OO_BLOB, which indicates that the provider supports access to BLOBs as structured objects. The consumer determines what interfaces are supported through DBPROP_STRUCTUREDSTORAGE.
DBPROP_PROVIDERFILENAME | Type: VT_BSTR Typical R/W: R only Description: Provider Name Specifies the file name of the provider. (Prior to MDAC 2.5, this property was named DBPROP_PROVIDERNAME.)
DBPROP_PROVIDEROLEDBVER | Type: VT_BSTR Typical R/W: R only Description: OLE DB Version This provider returns 02.50.00
DBPROP_STRUCTUREDSTORAGE | Type: VT_I4 Typical R/W: R only Description: Structured Storage Specifies a bitmask that indicates which interfaces on a storage object are supported by the rowset; that is, zero or more of: DBPROPVAL_SS_ISEQUENTIALSTREAM DBPROPVAL_SS_ILOCKBYTES
DBPROP_SUPPORTEDTXNDDL – supported | Type: VT_I4 Typical R/W: R only Description: Transaction DDL Specifies whether Data Definition Language (DDL) statements are supported in transactions. For this provider, the value is always DBPROPVAL_TC_ALL, which indicates that transactions can contain DDL and DML statements in any order.
DBPROP_SUPPORTEDTXNISOLEVELS | Type: VT_I4 Typical R/W: R only Description: Isolation Levels This provider supports only DBPROPVAL_TI_READCOMMITTED
DBPROP_SUPPORTEDTXNISORETAIN | Type: VT_I4 Typical R/W: R only Description: Isolation Retention This provider supports DBPROPVAL_TR_COMMIT_DC, which indicates that the transaction preserves its isolation across a retaining commit. DBPROPVAL_TR_ABORT_DC, which indicates that the transaction may either preserve or dispose of its isolation across a retaining abort.
DBPROP_COLUMNDEFINITION | Type: VT_I4 R/W: R Description: Column Definition For this provider, the value is always DBPROPVAL_CD_NOTNULL.
DBPROP_PROVIDERVER | Type: VT_BSTR R/W: R Description: Provider Version For this provider, the version returned is 01.00.0000
DBPROP_PERSISTENTIDTYPE | Type: VT_I4 R/W: R Description: Persistent ID Type For this provider, the value is DBPROPVAL_PT_NAME
DBPROP_ALTERCOLUMN | Type: VT_I4 R/W: R Description: Alter Column Support This provider returns DBCOLUMNDESCFLAGS_DBCID and DBCOLUMNDESCFLAGS_PROPERTIES. Note that the only properties that can be altered are DBPROP_COL_SEED, DBPROP_COL_INCREMENT, and DBPROP_COL_DEFAULT. DBPROP_COL_SEED and DBPROP_COL_INCREMENT can only be set on an identity column.
DBPROP_OPENROWSETSUPPORT | Type: VT_I4 R/W: R Description: Open Rowset Support This provider supports DBPROPVAL_ORS_TABLE and DBPROPVAL_ORS_INTEGRATEDINDEX.

Index Properties

The DBPROPSET_INDEX property set contains the following properties. All of these properties are in the Index property group.

Property ID | Description
DBPROP_INDEX_AUTOUPDATE | Type: VT_BOOL Typical R/W: R only Description: Auto Update For this provider, the value is always VARIANT_TRUE, which indicates that the index is automatically maintained.
DBPROP_INDEX_NULLCOLLATION | Type: VT_I4 Typical R/W: R only Description: NULL Collation Specifies how null values are collated in the index. For this provider, the value is always DBPROPVAL_NC_LOW, which indicates that null values are collated at the low end of the list.
DBPROP_INDEX_NULLS | Type: VT_I4 Typical R/W: R/W Description: NULL Keys Specifies whether null keys are allowed. For this provider, the value is always DBPROPVAL_IN_DISALLOWNULL, which indicates that the index does not allow entries where the key columns are NULL. If the consumer attempts to insert an index entry with a null key, the provider returns an error. This provider supports indexes that are nullable and indexes where nulls are disallowed.
DBPROP_INDEX_TYPE | Type: VT_I4 Typical R/W: R only Description: Index Type Specifies the type of the index. For this provider, the value is always DBPROPVAL_IT_BTREE, which indicates that the index is a B+- tree.
DBPROP_INDEX_UNIQUE | Type: VT_BOOL Typical R/W: R/W Description: Unique Specifies whether index keys must be unique. One of the following: VARIANT_TRUE, which indicates that the index keys must be unique. VARIANT_FALSE, which indicates that duplicate keys are allowed.

Initialization Properties

The DBPROPSET_DBINIT property set contains the following properties. All of these properties are in the Initialization property group.

Property ID (properties not supported in DBPROPSET_DBINIT) | Description
DBPROP_INIT_DATASOURCE | Type: VT_BSTR Typical R/W: R/W Description: Data Source Specifies the name of the data store to which to connect.
DBPROP_INIT_LCID | Type: VT_I4 Typical R/W: R/W Description: Locale Identifier The locale ID (LCID) of preference for the consumer. Consumers specify the LCID at initialization. This provides a method by which the server can determine the consumer's LCID of choice. This property does not guarantee that all text returned to the consumer will be translated according to the LCID.
DBPROP_INIT_MODE | Type: VT_I4 Typical R/W: R Description: Mode For this provider the mode is: DB_MODE_READWRITE | DB_MODE_SHARE_EXCLUSIVE

Provider-Defined Properties in DBPROPSET_SSCEOLEDB_DBINIT

The following table lists and describes DBPROPSET_SSCEOLEDB_DBINIT properties that are specific to the SQL Server CE OLE DB Provider.

Property ID | Description
DBPROP_SSCEOLEDB_DBPASSWORD | Type: VT_BSTR Typical R/W: R/W Description: SQL Server CE OLEDB:Database Password Password used to open the database. This differs from the user password in that the database password is per file, while a user password is per user.
DBPROP_SSCEOLEDB_ENCRYPTDATABASE | Type: VT_BOOL Typical R/W: R/W Description: SQL Server CE OLEDB:Encrypt Database Determines whether a compacted or a newly created database should be encrypted.

Rowset Properties

The DBPROPSET_ROWSET property set contains the following properties. All of these properties are in the Rowset property group. Additional properties are defined in DBPROPSET_SSCEOLEDB_ROWSET.

Property ID | Description
DBPROP_ABORTPRESERVE | Type: VT_BOOL Typical R/W: R only Description: Preserve on Abort For this provider, the value is always VARIANT_FALSE, which indicates that, after an abort or an abort that preserves, the only operations allowed on a rowset are to release row and accessor handles and to release the rowset.
DBPROP_BLOCKINGSTORAGEOBJECTS | Type: VT_BOOL Typical R/W: R only For this provider, the value is always VARIANT_TRUE.
DBPROP_BOOKMARKS | Type: VT_BOOL Typical R/W: R/W Description: Use Bookmarks Specifies whether the rowset supports bookmarks; that is: VARIANT_TRUE, which indicates that the rowset supports bookmarks. Column 0 is the bookmark for the rows. Getting this column obtains a bookmark value, which can be used to reposition to the row. VARIANT_FALSE, which indicates that the rowset does not support bookmarks. The rowset is sequential, and the values of the DBPROP_LITERALBOOKMARKS and DBPROP_ORDEREDBOOKMARKS properties are ignored.
DBPROP_BOOKMARKTYPE | Type: VT_I4 Typical R/W: R only Description: Bookmark Type Specifies the bookmark type supported by the rowset. For this provider, the value is always DBPROPVAL_BMK_NUMERIC, which indicates that the bookmark type is numeric. Numeric bookmarks are based on a row's properties that are not dependent on the values of the row's columns. For instance, a numeric bookmark can be based on the absolute position of the row within the rowset or on a row ID that the storage engine assigned to a tuple when it was created. The validity of numeric bookmarks is not changed by modifying the row's columns.
DBPROP_CANFETCHBACKWARDS | Type: VT_BOOL Typical R/W: R/W Description: Fetch Backward Specifies whether the rowset can fetch backward; that is: VARIANT_TRUE, which indicates that cRows in IRowset::GetNextRows, IRowsetLocate::GetRowsAt, and IRowsetScroll::GetRowsAtRatio can be negative. When it is negative, these methods fetch rows backward from the specified row. VARIANT_FALSE, which indicates that cRows must be non-negative.
DBPROP_CANHOLDROWS | Type: VT_BOOL Typical R/W: R Description: Hold Rows For this provider, this property is always VARIANT_FALSE.
DBPROP_CANSCROLLBACKWARDS | Type: VT_BOOL Typical R/W: R Description: Scroll Backward For this provider, this property is always VARIANT_FALSE, which indicates that IRowsOffset must be non-negative.
DBPROP_CHANGEINSERTEDROWS | Type: VT_BOOL Typical R/W: R/W Description: Change Inserted Rows For this provider, the value is always VARIANT_TRUE, which indicates that the consumer can call IRowsetChange::DeleteRows or IRowsetChange::SetData for newly inserted rows. A newly inserted row is defined as a row for which the insertion has been transmitted to the data store, as opposed to a pending insert row.
DBPROP_COMMITPRESERVE | Type: VT_BOOL Typical R/W: R only Description: Preserve On Commit For this provider, the value is always VARIANT_TRUE, which indicates that after a commit that preserves, the rowset remains active. That is, it is possible to fetch new rows, update, delete, and insert rows, and so on.
DBPROP_DEFERRED | Type: VT_BOOL Typical R/W: R only Description: Defer Column For this provider, the value is always VARIANT_TRUE, which indicates that the data in the column is not fetched until an accessor is used on the column.
DBPROP_DELAYSTORAGEOBJECTS | Type: VT_BOOL Typical R/W: R only Description: Delay Storage Object Updates For this provider, the value is always VARIANT_TRUE: Storage objects are also used in delayed update mode.
DBPROP_IAccessor DBPROP_IColumnsInfo DBPROP_IConvertType DBPROP_IRowset DBPROP_IRowsetChange DBPROP_IRowsetInfo DBPROP_IRowsetUpdate DBPROP_ISupportErrorInfo DBPROP_IRowsetIndex DBPROP_IRowsetCurrentIndex DBPROP_IRowsetBookmark | Type: VT_BOOL Typical R/W: R/W, except as noted below. Description: If the value of any of these properties is set to VARIANT_TRUE, the rowset supports the specified interface. These properties are primarily used to request interfaces through ICommandProperties::SetProperties. The following properties are read-only and are always VARIANT_TRUE. DBPROP_Iaccessor DBPROP_IColumnsInfo DBPROP_IConvertType DBPROP_IRowset DBPROP_IRowsetInfo DBPROP_ISupportErrorInfo Setting DBPROP_IRowsetUpdate to VARIANT_TRUE automatically sets DBPROP_IRowsetChange to VARIANT_TRUE. Setting DBPROP_IRowsetCurrentIndex to VARIANT_TRUE automatically sets DBPROP_IRowsetIndex to VARIANT_TRUE.
DBPROP_ILockBytes DBPROP_IsequentialStream | Type: VT_BOOL Typical R/W: R/W Description: ILockBytes ISequentialStream If the value of this property is set to VARIANT_TRUE, the specified column is treated as a storage object that exposes the specified interface.
DBPROP_IMMOBILEROWS | Type: VT_BOOL Typical R/W: R only Description: Immobile Rows For this provider, the value is always VARIANT_FALSE, which indicates that, if the rowset is ordered, inserted rows and updated rows (where one or more of the columns in the ordering criteria are updated) obey the ordering criteria of the rowset. If the rowset is not ordered, inserted rows are not guaranteed to appear in a determinate position and the position of updated rows is not changed. This property is meaningful only if DBPROP_OWNINSERT is VARIANT_TRUE.
DBPROP_MAXOPENROWS | Type: VT_I4 Typical R/W: R Description: Maximum Open Rows This value is 1 for SQL Server CE.
DBPROP_MAXROWS | Type: VT_I4 Typical R/W: R only Description: Maximum Rows Specifies the maximum number of rows that can be returned in a rowset. If there is no limit, this value is 0. For this provider, the value is always 0.
DBPROP_OTHERINSERT | Type: VT_BOOL Typical R/W: R/W Description: Base Tables are True; others are False.
DBPROP_OTHERUPDATEDELETE | Type: VT_BOOL Typical R/W: R/W Description: Others' Changes Visible Specifies values as either: VARIANT_TRUE, which indicates that the rowset can see updates and deletes made by someone other than a consumer of the rowset. For example, suppose someone other than a consumer of the rowset updates the data underlying a row or deletes the row. If the row is released completely, any consumer of the rowset will see that change the next time it fetches the row. This includes updates and deletes made by other parties in the same transaction as well as updates and deletes by parties outside the transaction. The transaction isolation level does not affect the ability of the rowset to see updates or deletes by other parties in the same transaction, such as other rowsets in the same session. However, it does restrict the ability of the rowset to see updates or deletes by parties outside the transaction. VARIANT_FALSE, which indicates that the rowset cannot see updates and deletes by others.
DBPROP_OWNINSERT | Type: VT_BOOL Typical R/W: R/W Description: Own Inserts Visible
DBPROP_OWNUPDATEDELETE | Type: VT_BOOL Typical R/W: R/W Description: Own Changes Visible
DBPROP_QUICKRESTART | Type: VT_BOOL Typical R/W: R / W Description: Quick Restart
DBPROP_REMOVEDELETED | Type: VT_BOOL Typical R/W: R Description: Remove Deleted Rows For this provider, the value is always VARIANT_TRUE.
DBPROP_REPORTMULTIPLECHANGES | Type: VT_BOOL Typical R/W: R only Description: Report Multiple Changes For this provider, the value is always VARIANT_TRUE.
DBPROP_ROWTHREADMODEL | Type: VT_I4 Typical R/W: R only Description: Row Threading Model Specifies the threading model of the rowsets generated by the command. For this provider, the value is always DBPROPVAL_RT_FREETHREAD.
DBPROP_UPDATABILITY | Type: VT_I4 Typical R/W: R/W Description: Updatability
DBPROP_ACCESSORDER | Type: VT_I4 R/W: R Description: Access Order For this provider, the value is always DBPROPVAL_AO_RANDOM.
DBPROP_LOCKMODE | TYPE: VT_I4 R/W: R Description: Lock Mode For this provider, the value is always UNDONE.
DBPROP_SERVERDATAONINSERT | TYPE: VT_BOOL R/W: R Description: Server Data on Insert For this provider the value is always VARIANT_TRUE.

Provider-Defined Properties in DBPROPSET_SSCEOLEDB_SESSION

The DBPROPSET_SSCEOLEDB_SESSION property set contains the following properties.

Property ID | Description
DBPROP_SSCEOLEDB_MAXBUFFERSIZE | Type: VT_I4 Typical R/W: R/W Description: SQL Server CE OLE DB:Max Buffer Size The largest amount of memory, in kilobytes, that SQL Server CE can use before it starts flushing changes to disk.

Table Properties

The DBPROPSET_TABLE property set contains the following properties. All of these properties are in the Table property group.

Property ID | Description
DBPROP_TBL_TEMPTABLE | Type: VT_BOOL Typical R/W: R/W Description: Temporary Table Users should refrain from creating temporary tables in SQL Server CE.


SQL Server CE Limitations

Database Catalog

SQL Server CE has no notion of a catalog as defined in OLE DB. The DBPROP_DATASOURCE property defines the database to use, and the SQL Server CE OLE DB Provider treats this database as the current catalog. The DBPROP_CURRENTCATALOG property does not provide additional information to users about the current data store. Also, the SQL Server CE OLE DB Provider does not support the ability to change the current data store. Clients wanting to change the data store should uninitialize the data source object, set the new data store name, and reinitialize the data source object.

SQL Server CE Database, Page, and BLOB Sizes
  • SQL Server CE has a page size of 4 KB.

  • The size of a SQL Server CE database increases in 1-page increments.

  • The maximum size of a SQL Server CE database is 2 GB.

  • The maximum size of a SQL Server CE BLOB column is 1 GB.

  • SQL Server CE can support a maximum of 128 sessions.
Features not supported
DBPROP_CONCATNULLBEHAVIOR – not supported | Type: VT_I4 Typical R/W: R only Description: Null Concatenation Behavior Specifies how the data store handles concatenation of null-valued and non-null-valued character data type columns, that is: DBPROPVAL_CB_NON_NULL, which indicates that the result is the concatenation of the non-null-valued column or columns.
DBPROP_AUTH_PERSIST_ENCRYPTED – not supported | Type: VT_BOOL Typical R/W: R only Description: Persist Encrypted For this provider, the value is always VARIANT_FALSE, which indicates that the data source object can persist sensitive authentication information without encryption.
DBPROP_CACHEDEFERRED – not supported | Type: VT_BOOL Typical R/W: R only Description: Cache Deferred Columns For this provider, the value is always VARIANT_FALSE, which indicates that the provider does not cache the value of a deferred column and multiple calls to IRowset::GetData because the column can return different values.


SQL Server CE Data Type Mapping from ADOX

adSmallInt | smallint |
adInteger | integer |
adSingle | real |
adDouble | float |
adCurrency | money |
adBoolean | bit |
adUnsignedTinyInt | tinyint |
adBigInt | bigint |
adGUID | uniqueidentifier |
adVarBinary | varbinary |
adBinary | binary |
adVarWChar | nvarchar | Note that you must specify the size of this column.
adWChar | nchar | Note that you must specify the size of this column.
adNumeric | numeric | You must specify the precision.
adDBTimestamp | datetime |
adLongVarBinary | IMAGE |
adLongVarWChar | NTEXT |


Programmer's Guide for OLE DB/CE

This guide discusses a variety of details about the SQL Server CE OLE DB Provider. It is targeted towards direct clients of the OLE DB Provider.


SQL Server CE-Specific Interfaces and Concerns

Compacting Databases

SQL Server CE exposes an interface to compact databases. This is useful to reclaim lost space in the database and correct corruption errors. Compaction of SQL Server CE databases is essential to maintain good performance. It also provides an opportunity to manage global database settings, such as sort orders, the database password, or the use of encryption. Users should compact SQL Server CE databases regularly.

Compact1 example:

   [Initialize database normally, but do not create any Sessions]
   // Get ISSCECompact interface
   hr = pIDBProperties->QueryInterface(IID_ISSCECompact, (void **) &pISSCECompact);

   // Initialize Property with name of new compacted database
   compactdbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
   compactdbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   compactdbprop[0].vValue.vt = VT_BSTR;
   compactdbprop[0].vValue.bstrVal = SysAllocString(L"ssce-compacteddb.sdf"); // new name for compacted database

   // Initialize property set
   compactdbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
   compactdbpropset[0].rgProperties = compactdbprop;
   compactdbpropset[0].cProperties = sizeof(compactdbprop)/sizeof(compactdbprop[0]);

   // Compact the database using the provider-specific interface
hr = pISSCECompact->Compact(sizeof(compactdbpropset)/sizeof(compactdbpropset[0]), compactdbpropset);

Compacting requires that no sessions exist against the database.

Changing the Sort Order of a Database

Microsoft SQL Server CE uses UNICODE as its text string data format. An LCID is used to encapsulate sort order. These are exposed through the DBPROP_INIT_LCID property on the Data Source object in OLE DB. When compacting databases, it is possible to specify a new sort order for the resulting database by specifying this property and value when calling ISSCECompact::Compact.


OLE DB Objects in Depth

SQL Server CE manages a subset of SQL Server 2000 objects.


OLE DB Properties for Opening Databases

While the SQL Server OLE DB Provider uses a number of different properties to specify a server and database to open as a data source, SQL Server CE uses only a single property to specify the data source. This property is DBPROP_INIT_DATASOURCE, and it should include the full path to the database file to be opened. For example, to open the database file \Windows\Northwind.sdf, pass the string \Windiws\Northwind.sdf in the DBPROP_INIT_DATASOURCE property when calling IDBProperties::SetProperties. In most cases, this should be sufficient to open the database.

SQL Server CE also supports a file-level access control mechanism called a database password. This password must be passed each time the database is opened to be able to use the database. The property DBPROP_SSCE_DBPASSWORD in the provider-specific property set DBPROPSET_SSCE_DBINIT should be used to specify this property. When creating a database, this property can be used to specify a database password on a new database. When compacting a database, this property can be used to change the database password to a new value.

Dbpassword example:

[Instantiate the provider, as in other examples]

   // Initialize Property with name of database
   dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
   dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   dbprop[0].vValue.vt = VT_BSTR;
   dbprop[0].vValue.bstrVal = SysAllocString(L"mypasswordprotecteddatabase.sdf");

   // Second property set has one property containing the provider-specific
   // database password property.
   dbprop2[0].dwPropertyID = DBPROP_SSCE_DBPASSWORD;
   dbprop2[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   dbprop2[0].vValue.vt = VT_BSTR;
   dbprop2[0].vValue.bstrVal = SysAllocString(L"mypassword");

   // Initialize property set
   dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
   dbpropset[0].rgProperties = dbprop;
   dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

   // Initialize provider-specific property set
   dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
   dbpropset[1].rgProperties = dbprop2;
   dbpropset[1].cProperties = sizeof(dbprop2)/sizeof(dbprop2[0]);

   // Set properties into the provider's DSO object
   hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]), dbpropset);


Session Properties

SQL Server CE supports a property to modify the amount of memory that the engine uses for caching. To change this value, pass the DBPROP_SSCE_MAXBUFFERSIZE property in the DBPROPSET_SSCE_SESSION property set to the ISessionProperties interface. The following code sample demonstrates how to restrict the amount of cache the engine uses to 128 KB.

Sessionproperties example:

// Create a session object
   hr = pIDBCreateSession->CreateSession(NULL, IID_ISessionProperties, (IUnknown**) &pISessionProperties);

   // Initialize Property to change the maximum number of locks per file
   sessiondbprop[0].dwPropertyID = DBPROP_SSCE_MAXBUFFERSIZE;
   sessiondbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   sessiondbprop[0].vValue.vt = VT_I4;
   sessiondbprop[0].vValue.lVal = 128; // limit cache usage to 128K

   // Initialize session property set
   sessiondbpropset[0].guidPropertySet = DBPROPSET_SSCE_SESSION;
   sessiondbpropset[0].rgProperties = sessiondbprop;
   sessiondbpropset[0].cProperties = sizeof(sessiondbprop)/sizeof(sessiondbprop[0]);

   // Set session property
   hr = pISessionProperties->SetProperties(sizeof(sessiondbpropset)/sizeof(sessiondbpropset[0]),sessiondbpropset);


Transactions

Transactions provide a mechanism to group a series of changes to a database in one atomic operation. A transaction is started through ITransactionLocal::StartTransaction. After changes have been made to the database, these changes can be committed (using ITransaction::Commit) or aborted (using ITransaction::Abort). The ability to participate in distributed transactions in OLE DB also exists but requires functionality that SQL Server CE does not expose. Distributed transactions are exposed through the ITransactionJoin interface and require that a provider be able to support two-phased commit transactions. Since SQL Server CE only provides the ability to have single-phase commit transactions, the OLE DB Provider for SQL Server CE does not expose this functionality.

SQL Server CE exposes a unique combination of functionality in its transaction model. For example, transactions can be nested to a depth of five levels. Most other providers cannot provide this functionality. Users can determine if they have reached the maximum level of transaction nesting when StartTransaction returns an error indicating that no further transactions can be started. The transaction isolation model exposed in SQL Server CE is "Read Committed," meaning that SQL Server CE can isolate users from uncommitted changes in a database. This functionality is described generically through the DBPROP_SUPPORTEDTXNISOLEVELS property and is useful if a client needs to make particular assumptions about the transaction model. It should be noted that SQL Server CE's transaction model differs somewhat from that of Microsoft SQL Server. Clients who want to port applications to run on both engines need to be aware of the differences described in this section.

One important detail about transactions is how the completion of a transaction (either abort or commit) affects cursors and objects created within the transaction. For example, if a user opens a cursor inside a transaction, then aborts the transaction, what happens to the cursor is not guaranteed. In some cases, the rowset may cease to be valid once a transaction is aborted. OLE DB describes this behavior through the DBPROP_ABORTPRESERVE and DBPROP_COMMITPRESERVE properties. SQL Server CE returns that cursors are not preserved when a transaction over the creation of the cursor is aborted. Users who want to continue using a cursor after an abort should open the cursor outside the scope of the transaction to minimize issues resulting from this behavior. The following ADO code illustrates the example.

Sub Transaction example:

    Dim cn As ADOCE.Connection
    Dim rs As ADOCE.Recordset
    Set cn = CreateObject("ADOCE.Connection.3.1")
    Set rs = CreateObject("ADOCE.Recordset.3.1")
    cn.Open "provider=Microsoft.SQLSERVER.OLEDB.CE.1.0;data source=\mydb.sdf;"

    ' Begin a transaction
    cn.BeginTrans
    ' Commit that transaction
    cn.CommitTrans

    ' Demonstrate that opening a table outside of the transaction
    ' avoids potential problems with DBPROP_ABORTPRESERVE
    rs.Open "helloworld", cn, adOpenDynamic, adLockOptimistic
    cn.BeginTrans
    cn.RollbackTrans
    rs.MoveFirst    ' recordset is still functional
    rs.Close

    ' opening a rowset within a transaction that is aborted
    ' will zombie the rowset in the OLE DB Provider for Microsoft
    ' SQL Server CE.  This is published in DBPROP_ABORTPRESERVE and
    ' can be accessed in ADO through the "Preserve on Abort" property
    cn.BeginTrans
    rs.Open "helloworld", cn, adOpenDynamic, adLockOptimistic
    MsgBox rs.Properties("Preserve on Abort")
    MsgBox rs.State
    cn.RollbackTrans
    rs.MoveFirst
End Sub

Transactions also interact with the locking schemes for each provider to different degrees. The DBPROP_SUPPORTEDTXNDDL property describes the scope of a provider's locking scheme while doing DDL operations in a transaction. SQL Server CE holds an exclusive lock on a table that has been altered in a transaction until that transaction completes. Further attempts to open the table or perform modifications on it will fail until the lock in the transaction can be freed. In general, it is not recommended that DDL operations be performed inside transactions because of the potential for locking conflicts.


Managing Database Objects by Using DDL

SQL Server CE requires that objects be opened exclusively to modify those objects. For example, if a user attempted to add a column to a table by using ITableDefinition::AddColumn while a cursor was open on that table, the attempt to modify the definition of the column would fail with a locking error. You should be aware of locking issues when designing your application.


Databases

The OLE DB Provider for SQL Server CE exposes the ability to manage databases through the IDBDataSourceAdmin interface. This interface lets you create .sdf files. While the interface exposes the ability to delete databases, the OLE DB Provider for SQL Server CE does not support this functionality due to security issues. If you have access to the file system on the computer, you can simply delete .sdf files that are no longer needed.

The following example demonstrates how a data source can be created using the OLE DB Provider for SQL Server CE.

Createdb example:

   // Creates a database
   // Requires calling IDBDataSourceAdmin::CreateDataSource with the name
   // of the database to create

   // Set up properties for call to CreateDataSource
   dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
   dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   dbprop[0].vValue.vt = VT_BSTR;
   dbprop[0].vValue.bstrVal = SysAllocString(L"newdb.sdf");

   dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
   dbpropset[0].rgProperties = dbprop;
   dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

   // Call CreateDataSource to create the database
   hr = pIDBDataSourceAdmin->CreateDataSource(1, dbpropset, NULL, IID_IDBProperties, NULL);
   // Done creating database


Tables

SQL Server CE supports a subset of the SQL Server capability with table creation and manipulation in the database.


ITableDefinition

SQL Server CE contains an upwardly compatible subset of data types. Using OLE DB DDL interfaces, such as ITableDefinition, should provide a consistent programming paradigm compared to the SQL Server OLE DB provider. There are some differences, however. Not all data types in SQL Server are supported in SQL Server CE. For example, non-unicode text columns (varchar, char, text) and smallmoney are not supported (although nvarchar, nchar, ntext, and money are supported). Also, the maximum sizes of variable-length columns differ between SQL Server and SQL Server CE. While SQL Server supports variable-length nvarchar and varbinary types up to 4000 bytes long, SQL Server CE supports a maximum size of 510 bytes. The appropriate larger types (ntext and image) can be used to store more data in a column, if necessary. See the PROVIDER_TYPES schema rowset for generically exposed type information about the SQL Server CE Provider.


IAlterTable

IAlterTable does not guarantee that you can modify every detail about a table. It provides the mechanism for a provider to expose any table altering functionality that exists in a provider. As such, not every provider may be able to modify the same things about tables in their data stores. SQL Server CE supports changing the name of an existing table or column in addition to a number of column properties. See the Programmer's Reference for OLE DB/CE for more information about how to use the IAlterTable interface.

Some information about columns can also be modified using IAlterTable::AlterColumn. Since columns have more items that could potentially be modified, the property DBPROP_ALTERCOLUMN describes the portions of the DBCOLUMNDESC structure defining the column that can be modified. However, even if the provider supports modifying properties, that does not imply that all properties can be modified. The following properties can be modified through the OLE DB Provider for SQL Server CE:

DBPROP_COL_DEFAULT

DBPROP_COL_SEED (only on identity columns)

DBPROP_COL_INCREMENT (only on identity columns)


Indexes

SQL Server CE has several restrictions that it places on how indexes are created. The most noteworthy restrictions regarding indexes with Microsoft SQL Server CE are:

  • A maximum of 32 indexes per table.

  • A maximum of 10 columns in an index.

  • Only the first 510 bytes of data can be indexed in any column. Columns of type ntext and image cannot be indexed.

The following example creates a simple index over two columns in a table.

Indexdef example:

   // Prepare table name DBID
   TableName.eKind = DBKIND_NAME;
   TableName.uName.pwszName = L"indexdeftable";

   // Prepare index name DBID
   IndexName.eKind = DBKIND_NAME;
   IndexName.uName.pwszName = L"indexdeftableindex1";

   // Set up properties for IIndexDefinition::CreateIndex call

   // For this index, we enforce uniqueness via the DBPROP_INDEX_NULLS property.
   indexdbprop[0].dwPropertyID = DBPROP_INDEX_NULLS;
   indexdbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
   indexdbprop[0].vValue.vt = VT_I4;
   indexdbprop[0].vValue.lVal = DBPROPVAL_IN_DISALLOWNULL;
   indexdbprop[0].colid = DB_NULLID; // Index properties must have colid set to DB_NULLID

   // This index should also be automatically maintained (All SQL Server CE indexes are automatically maintained in all cases - not
   // all providers do this, though, so request functionality if needed in an application.).
   indexdbprop[1].dwPropertyID = DBPROP_INDEX_AUTOUPDATE;
   indexdbprop[1].dwOptions = DBPROPOPTIONS_REQUIRED;
   indexdbprop[1].vValue.vt = VT_BOOL;
   indexdbprop[1].vValue.boolVal = VARIANT_TRUE;
   indexdbprop[1].colid = DB_NULLID; // Index properties must have colid set to DB_NULLID

   // Initialize property set
   indexdbpropset[0].guidPropertySet = DBPROPSET_INDEX;
   indexdbpropset[0].rgProperties = indexdbprop;
   indexdbpropset[0].cProperties = sizeof(indexdbprop)/sizeof(indexdbprop[0]);

   // Set up DBINDEXCOLUMNDESC structures to define the columns in the index and the
   // ordering for each column within that index
   rgIndexColumnDescs[0].eIndexColOrder = DBINDEX_COL_ORDER_ASC;  // ascending column
   rgIndexColumnDescs[0].pColumnID = &dbidColumn1;

   rgIndexColumnDescs[1].eIndexColOrder = DBINDEX_COL_ORDER_DESC;  // descending column
   rgIndexColumnDescs[1].pColumnID = &dbidColumn2;

   dbidColumn1.eKind = DBKIND_NAME;
   dbidColumn1.uName.pwszName = L"col1";

   dbidColumn2.eKind = DBKIND_NAME;
   dbidColumn2.uName.pwszName = L"col2";

   // Create an index over the table `indexdeftable` called `indexdeftableindex1` that contains 2 columns.
   hr = pIIndexDefinition->CreateIndex(&TableName, &IndexName, sizeof(rgIndexColumnDescs)/sizeof(rgIndexColumnDescs[0]), rgIndexColumnDescs, sizeof(indexdbpropset)/sizeof(indexdbpropset[0]), indexdbpropset, NULL);

The only characteristic of an index that can be modified using IAlterIndex::AlterIndex against the OLE DB Provider for Microsoft SQL Server CE is the name of the index.


Constraints

SQL Server CE supports constraints to enforce data integrity rules in the database. These include the PRIMARY KEY, UNIQUE, and FOREIGN KEY constraints. Note that SQL Server CE does not support CHECK constraints. Other details of constraints include:

  • Microsoft SQL Server CE does not support a cascading update or delete rule to set a field to the default value.

  • The MatchType element of the DBCOLUMNDESC structure should always be set to "full".

  • Constraints in Microsoft SQL Server CE cannot be deferred.

  • Since PRIMARY KEY, UNIQUE, AND FOREIGN KEY constraints use indexes in SQL Server CE to enforce the constraint, they are subject to the same limitations as indexes described above.

Constraint example:

   // Prepare constraint name DBID
   ConstraintName.eKind = DBKIND_NAME;
   ConstraintName.uName.pwszName = L"tableconstraint";

   // Prepare the column list that makes up the unique constraint
   rgColumnList[0].eKind = DBKIND_NAME;
   rgColumnList[0].uName.pwszName = L"testcolumnname"; // this is the name of the column we create in the createtable example

   // Build DBCONSTRAINTDESC structure to create a constraint on our column
   rgConstraintDescs[0].pConstraintID = &ConstraintName;
   rgConstraintDescs[0].ConstraintType = DBCONSTRAINTTYPE_UNIQUE;
   rgConstraintDescs[0].cColumns = 1;
   rgConstraintDescs[0].rgColumnList = rgColumnList;
   rgConstraintDescs[0].pReferencedTableID = NULL;         // not used in UNIQUE constraints
   rgConstraintDescs[0].cForeignKeyColumns = 0;         // not used in UNIQUE constraints
   rgConstraintDescs[0].rgForeignKeyColumnList = NULL;      // not used in UNIQUE constraints
   rgConstraintDescs[0].pwszConstraintText = NULL;         // not used in UNIQUE constraints
   rgConstraintDescs[0].UpdateRule = DBUPDELRULE_NOACTION;   // not used in UNIQUE constraints
   rgConstraintDescs[0].DeleteRule = DBUPDELRULE_NOACTION;   // not used in UNIQUE constraints
   rgConstraintDescs[0].MatchType = DBMATCHTYPE_NONE;      // not used in UNIQUE constraints
   rgConstraintDescs[0].Deferrability = 0;               // SQL Server CE constraints are not deferrable

   // Create a table using the column information retrieved from the PROVIDER_TYPES schema rowset
   hr = pITableDefinitionWithConstraints->CreateTableWithConstraints(NULL, &TableName, 1, rgColumnDescs, 1, rgConstraintDescs, IID_IRowset, 0, NULL, NULL, NULL);


Commands

SQL Server CE supports a subset of the SQL Server query grammar through its command objects (with a few minor exceptions). This means that, for the most part, queries that can be run on SQL Server CE will also run on SQL Server 2000. Queries in the SQL Server CE Provider lack T-SQL support. Furthermore, only a single statement can be executed in a single command. SQL Server CE also does not support parameterized queries in version 1.0, nor does it support output parameters to queries. For more information about the exact query grammar, see SQL Reference for SQL Server CE.


Preparing Commands

Database engines must do some preparation work to be able to execute a query. Often, this work can be done once if the command is to be executed multiple times, potentially saving time. If clients expect to run a query more than once, it is recommended that the command be prepared once, then call Execute multiple times. This should maximize performance by avoiding query recompilation.


Rowsets

There are properties that correspond to various interfaces that can be supported on a rowset. For example, the property DBPROP_IRowsetIndex can be set for a client to request the ability to access the IRowsetIndex interface on a resulting rowset. It is important to understand that clients that do not request the interfaces that they want to use on the resulting interface through the property mechanism will not necessarily be able to access those interfaces even if the cursor type selected could actually support that functionality. Even if a base table had an index defined on it, it would not be accessible through a rowset unless that rowset had been opened with the DBPROP_IRowsetIndex propertry set to VARIANT_TRUE.


Using Rowsets Efficiently

Compared to determining a cursor type, providing rowset functionality, such as getting and setting data, is relatively simple. Since most of the differences in functionality are described in the properties of the rowset, client code can write generically to these properties without knowledge of the various cursor types in each provider.

One common question asked to provider writers is, "How many rows should I fetch at a time?" Unfortunately, the answer to this varies from provider to provider. If the provider is a client-server relational database engine existing on a different machine on a network, it is generally best to fetch rows in batches of something like 50 so that these can minimize user latency over the network. For SQL Server CE, the largest cost involved in fetching multiple rows is reading and writing to the disk, which is affected directly by how much the underlying cursor is moved. Therefore, it is generally best to only request one row at a time.

When changing or inserting data into a rowset, performance will also vary based on the type of the provider. When using deferred update mode in OLE DB, specified by DBPROP_IRowsetUpdate being true, SQL Server CE can only have one pending change at a time. This uses a fast mechanism to update internally.

Some providers, including the OLE DB Provider for SQL Server CE, support using special interfaces to access large data values in the provider. Access to SQL Server CE's image and ntext data types can use structured storage interfaces to read these arbitrarily large data values in chunks, avoiding potential errors if the system tried to read the value into memory in one complete piece. The SQL Server CE Provider supports ISequentialStream and ILockBytes to allow access to long-value data in pieces. ISequentialStream, as the name implies, allows clients to read parts of a long-value column in a sequential, forward-only manner, while ILockBytes can access data in a random fashion. Clients should request this functionality from the provider if they want to use it, as demonstrated by the following example.

ILockBytes example:

   // Create a DBID for the database table
   TableID.eKind = DBKIND_NAME;
   TableID.uName.pwszName = L"ntexttable";

   // Set up properties to request functionality on the rowset.
   rowsetdbpropset[0].cProperties = sizeof(rowsetdbprop)/sizeof(rowsetdbprop[0]);
   rowsetdbpropset[0].rgProperties = rowsetdbprop;
   rowsetdbpropset[0].guidPropertySet = DBPROPSET_ROWSET;

   // Request ILockBytes interface
   dwIndex = 0;
   rowsetdbprop[dwIndex].dwPropertyID = DBPROP_ILockBytes;
   rowsetdbprop[dwIndex].dwOptions = DBPROPOPTIONS_REQUIRED;
   rowsetdbprop[dwIndex].vValue.vt = VT_BOOL;
   rowsetdbprop[dwIndex].vValue.boolVal = VARIANT_TRUE;

   // Open the base table, requesting ILockBytes capability
   hr = pIOpenRowset->OpenRowset(NULL, &TableID, NULL, IID_IRowset, 1, rowsetdbpropset, (IUnknown **) & pIRowset);

// Retrieve a single row in a forward-only traversal of the rowset.  Since this
   // is the absolute minimum operation that can be supported by a rowset, it will
   // always be supported.
   hr = pIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &prghRows);

 [build accessor to retrieve IUnknown binding for ILockBytes]

   // Retrieve data using the accessor - this instantiates the interface we want
   hr = pIRowset->GetData(rghRows[0], hAccessor, pData);

   // Get the ILockBytes pointer from the buffer
   pILockBytes = *(ILockBytes**)(pData + rgBinding[0].obValue);

   // Initialize Offset
   ulOffset.QuadPart = 0;

   // Retrieve data from the interface in chunks.
   for(;;)
      {
      ULONG cbRead;

      // Read data at the specified offset - note that this is in bytes, not characters
      hr = pILockBytes->ReadAt(ulOffset, pBuffer, sizeof(pBuffer)-sizeof(WCHAR), &cbRead);
      [process data]
      if(cbRead < sizeof(pBuffer)-sizeof(WCHAR) || FAILED(hr))
         break;

      ulOffset.QuadPart += cbRead;
      }


Rowset Capabilities

The OLE DB Specification allows for a wide array of varying rowset behaviors. Not every provider supports all defined functionality depending on needs and capabilities. Since this may differ from one provider to another, it is important to understand how some of these interact with the OLE DB Provider for SQL Server CE.

SQL Server CE supports OLE DB data type coersions to and from DBTYPE_WSTR. It is recommended that you use native data type bindings where possible to maximize performance against this engine.


Rowset Properties

The property DBPROP_SERVERDATAONINSERT publishes whether a provider returns values for computed columns while inserting new rows. This is important because, in many cases, server databases do not send this information to the client. However, the SQL Server CE database engine always returns these values on inserted rows, allowing clients to immediately retrieve this information. This allows the client to view any identity column value for the new row even before the row has been committed to the data store. This is an efficient way to perform the same function as "SELECT @@IDENTITY;" in SQL Server.


Using Indexes

SQL Server CE supports indexes and a number of index-based operations to improve application performance. This section defines useful information for indexes:

  • SQL Server CE only supports "integrated indexes" as defined in OLE DB. This means that the index is logically part of the Rowset and is used to order the rowset - no separate index rowset is used to provide ordering.

  • Indexes are only exposed on base tables. This means that IOpenRowset::OpenRowset must be used to open the table to use an index for ordering, seeking, or using index ranges. Query result sets do not expose base table indexes.

  • Indexes in SQL Server CE have slightly different creation properties from SQL Server. See CREATE INDEX for more information.


IRowsetIndex

To enable the ability to do Seek and SetRange, you must request the property DBPROP_IRowsetIndex with a value of VARIANT_TRUE when opening the base table rowset. Also, if you want to dynamically change the index while the rowset is open, you must also request DBPROP_IRowsetCurrentIndex. If you request these properties, you can call QueryInterface to retrieve the IRowsetIndex or IRowsetCurrentIndex methods, respectively.


Seek

The most widely used method by clients on SQL Server CE indexes is Seek. This provides the ability to find rows on a cursor very quickly. Seek requires that an index be defined on the column(s) in the search key to work properly. Most seek operations are for a particular value, but it is also possible to seek using other comparison operators, such as "greater than" or "less than".

IRowsetIndex::Seek passes values to the provider by using the accessor mechanism in OLE DB that is used to get and set data. Accessors used against the Seek method have additional restrictions over accessors for IRowset::GetData and IRowset::SetData. The accessor must bind columns in the order they appear in the index key. For complete details, see the Microsoft OLE DB Programmer's Reference.

Seek1 example:

[Open a base table using IOpenRowset requesting DBPROP_IRowsetIndex]

   // Prepare structures to create the accessor
   // (we already know the layout of the table/index)
   // This will be used to seek
   rgBinding[0].iOrdinal = 1;
   rgBinding[0].dwPart = DBPART_VALUE | DBPART_STATUS | DBPART_LENGTH;
   rgBinding[0].obLength = 0;
   rgBinding[0].obStatus = rgBinding[0].obLength + sizeof(ULONG);
   rgBinding[0].obValue = rgBinding[0].obStatus + sizeof(DBSTATUS);
   rgBinding[0].wType = DBTYPE_I4;
   rgBinding[0].pTypeInfo = NULL;
   rgBinding[0].pObject = NULL;
   rgBinding[0].pBindExt = NULL;
   rgBinding[0].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
   rgBinding[0].cbMaxLen = sizeof(ULONG);

   // Create the accessor to describe the seek key buffer
   hr = pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA, 1, rgBinding, 0, &hAccessor, NULL);

   // Set up data buffer for seek operation
   *(ULONG*)(pData+rgBinding[0].obLength) = 4;
   *(ULONG*)(pData+rgBinding[0].obStatus) = DBSTATUS_S_OK;
   *(LONG*)(pData+rgBinding[0].obValue) = 1;

   // Seek for (col1=1)
   hr = pIRowsetIndex->Seek(hAccessor, 1, pData, DBSEEK_FIRSTEQ);


Changing Indexes

Some restrictions are imposed on clients when attempting to change the current index through IRowsetCurrentIndex:

  • All accessor handles must be released.

  • All row handles must be released.

  • No pending changes should be outstanding.


Remote Data Access (RDA)

This section describes how you can write applications that use SQL Server CE remote data access (RDA). The Programmer's Guide describes how to develop an application that makes use of the SQL Server CE RDA Object. The Programmer's Reference describes each of the RDA Object's methods and properties.


Programmer's Guide

The SQL Server CE ActiveX Control Remote Data Access Object (RDA Object) provides a means of programmatically accessing a Microsoft® SQL Server™ 2000, Microsoft SQL Server 7.0, or Microsoft SQL Server 6.5 database from a Microsoft® eMbedded Visual Basic® or Microsoft® eMbedded Visual C++® program running on a Windows CE platform.

This section provides an overview of the RDA Object; describes what is required to develop, test, and deploy an application that uses the RDA Object; and shows an example of pulling and pushing data between a SQL Server database and a SQL Server CE database.


Overview

RDA is always initiated and controlled by the Windows CE application program. The application program is responsible for pulling the table from a SQL Server table and if the table is tracked, periodically pushing the changed data back to the SQL Server table. A table must be deleted and repulled to refresh the local table data with data from the SQL Server table. Finally, the application is responsible for deleting the table from the SQL Server CE database when it is no longer needed.

The application developer should shield the user from the details of RDA. When an application is installed and run on the Windows CE device, the application should use the SQL Server CE ActiveX Control RDA Object to automatically pull the tables required in the application. If the table pulled from SQL Server was marked as tracked, the application should use the SQL Server CE ActiveX Control RDA Object to initiate table level synchronization whenever synchronization is required. The application might trigger synchronization, for example, when it detects that the Windows CE device is reconnected to the network, when the application has updated critical table information, when the user requests synchronization, or when a certain time period has elapsed.


Developing an eMbedded Visual Basic Program

This section describes how you can develop, debug, and deploy an eMbedded Visual Basic application that uses RDA. SQL Server CE should already be installed.

Developing an eMbedded Visual Basic Application

You must add Ssceconsts.bas to your eMbedded Visual Basic project to incorporate the SQL Server CE enumerations on Windows CE versions 2.11 and 2.12. You must also add the reference to Microsoft CE SQL Server Control 1.0 under the eVB Project/References menu item.

Debugging an eMbedded Visual Basic Application

eMbedded Visual Basic automatically downloads and registers Ssce10.dll and Ssceca10.dll to the Windows CE device when you run or debug your application. Ssce10.dll implements the SQL Server CE database. The SQL Server CE Client Agent, Ssceca10.dll, implements the RDA Object.

eMbedded Visual Basic automatically downloads Ssceinet.dll and Sscesock.dll on Windows CE 2.11 devices. These DLLs correct known deficiencies in the original Wininet.dll and Winsock.dll.

You can test your application using the emulator; however, you cannot use Secure Sockets Layer (SSL) encryption when running through the emulator.

Deploying an eMbedded Visual Basic Application

See Installing SQL Server CE, to fully understand the file requirements.

Sample eMbedded Visual Basic Applications

SQL Server CE includes an RDA sample eMbedded Visual Basic application. This sample application illustrates:

  • Using the Pull method to retrieve data from a SQL Server table and store the data in a SQL Server CE table.

  • Using the Push method to transfer changed data from a tracked SQL Server CE table back to a SQL Server table.

  • Using the SubmitSQL method to execute a SQL statement against a remote SQL Server database.

The SQL Server CE sample application is installed in the \Samples\Northwind subdirectory of your SQL Server CE installation, by default in \Program Files\Microsoft SQL Server CE.

See Also

Pull Method

Push Method

SubmitSQL Method


Developing an eMbedded Visual C++ Program

This section describes how you can develop, debug, and deploy an eMbedded Visual C++ application that uses RDA. SQL Server CE should already be installed.

Developing an eMbedded Visual C++ Application

You must include the following files in your eMbedded Visual C++ project when writing an eMbedded Visual C++ CE application that invokes the RDA Object:

  • Ca_mergex.h

  • Ca_mergex.lib

  • Ole32.lib

  • Oleaut32.lib

You must supply all required parameters for your eMbedded Visual C++ application. A compilation error will occur if all required parameters are not supplied with a method call since default parameter values for method calls are not supported.

Debugging an eMbedded Visual C++ Application

You must manually download and register Ssceca10.dll on the Windows CE device before you run or debug your application. Ssce10.dll implements the SQL Server CE database. The SQL Server CE Client Agent, Ssceca10.dll, implements the RDA Object.

You must download Ssceinet.dll and Sscesock.dll on Windows CE 2.11 devices when using SSL. These DLLs correct known deficiencies in the original Wininet.dll and Winsock.dll.

You can test your application by using the emulator; however, you cannot use SSL encryption when running through the emulator.

Deploying an eMbedded Visual C++ Application

See Installing SQL Server CE and Deploying SQL Server CE Applications to fully understand the file requirements.


RDA Programming

This section describes how your Windows CE applications can use the Microsoft SQL Server CE RDA ActiveX control.


Pull

Applications call the Pull method to extract data from a SQL Server database and store it in a SQL Server CE database table.

SQL Server CE is capable of tracking changes to the resulting SQL Server CE table. When the TRACKINGON option is specified, SQL Server CE tracks all inserts, updates, and deletes made to the local SQL Server CE table. The application may then call the Push method to propagate these changes back to the original SQL Server table.

RDA tracked Pull and Push methods use optimistic concurrency control. SQL Server does not keep pulled records locked. When the application calls Push, the changes made to the local SQL Server CE database are unconditionally applied to the SQL Server database. This may cause changes made by other users of the SQL Server database to be lost.

You should use tracked Pull and Push methods when the records you are updating are naturally partitioned and conflicts are unlikely. For example, tracked Pull and Push methods might be used in a field service application when each technician has a unique list of service calls.

You can make the following schema changes to a SQL Server CE table created with a tracked Pull:

  • Change the seed or increment of the IDENTITY column

  • Add or drop DEFAULTs

  • Add or drop foreign keys

  • Add or drop indexes

  • Drop the table

You cannot make any of the following schema changes to a SQL Server table while a tracked Pull is outstanding. To make these SQL Server table schema changes, you must drop the SQL Server CE table and repull the changed SQL Server table.

  • Add, drop, or rename columns

  • Rename the table

  • Drop a primary key

  • Alter a data type definition


Using Pull in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application calls the Pull method. The example assumes that the SQL Server CE Server Agent is configured with the IIS virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication. It assumes that the SQL Server database is located on server "SampleServer". The LocalConnectionString property specifies the name of the SQL Server CE database that will receive the pulled table. By convention, SQL Server CE databases are assigned the file extension .sdf.

   ' Declare the SQL Server CE ActiveX Control RDA Object Control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA Object
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0")

   ' Set RDA properties
   ceRDA .InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "MyInternetPassword"
   ceRDA .LocalConnectionString = "Data Source=\NorthwindRDA.sdf"

   ' Pull the database
   ceRDA .Pull "Customers", "SELECT * FROM Customers", "Provider=sqloledb;Data Source=SampleServer;Initial Catalog=Northwind;user id=SampleUser;password=SamplePassword", TRACKINGON, "tblErrCustomers"

   Set ceRDA = Nothing


Push

Applications call the Push method to transmit changes from a pulled tracked SQL Server CE table back to a SQL Server table. The application must have created the local SQL Server CE table by calling the Pull method with the RDA_TRACKOPTION set to TRACKINGON.


Using Push in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application calls the Push method. The example assumes that the SQL Server CE Server Agent is configured with the IIS virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication.

   ' Declare the SQL Server CE ActiveX Control RDA Object Control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA Object
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0")

   ' Set RDA properties
   ceRDA .InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "MyInternetPassword"
   ceRDA .LocalConnectionString = "Data Source=\NorthwindRDA.sdf"

   ' Push the tracked SQL Server CE table changes back to the SQL Server table
   ceRDA .Push "Customers", "Provider=sqloledb;Data Source=SampleServer;Initial Catalog=Northwind;user id=SampleUser;password=SamplePassword"

   Set ceRDA = Nothing


SubmitSQL

Applications call the SubmitSQL method to submit SQL statements for execution on a remote SQL Server database.


Using SubmitSQL in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application calls the SubmitSQL Method. The example assumes that the SQL Server CE Server Agent is configured with the IIS virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication.

   ' Declare the SQL Server CE ActiveX Control RDA Object Control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA Object
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0")

   ' Set RDA properties
   ceRDA .InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "MyInternetPassword"

   ' Update the Employees table in the Northwind database on the SQL Server
   ceRDA .SubmitSQL "UPDATE Employees SET City='Redmond' WHERE LastName='Davolio'", "Provider=sqloledb;Data Source=SampleServer;Initial Catalog=Northwind;user id=SampleUser;password=SamplePassword"

   Set ceRDA = Nothing


Handling RDA Errors

This section provides code samples to capture and display errors that occur when executing RDA methods.


Handling RDA Errors in eMbedded Visual Basic

The following eMbedded Visual Basic sample takes the SSCEErrors collection as an input parameter and displays each of the SSCEError Objects in the collection.

Sub ShowErrors(ErrColl As SSCEErrors)

    'Initailize error variables to view error collection
    Dim ErrRec As Object    'SSCE.ErrorRecords
    Dim param As Object
    Dim strErr As String

    strErr = ""

    For Each ErrRec In ErrColl
         strErr = strErr & "Source: " & ErrRec.Source & vbCrLf
         strErr = strErr & "Number: " & Hex(ErrRec.Number) & vbCrLf
         strErr = strErr & "NativeError: " & ErrRec.NativeError & vbCrLf
         strErr = strErr & "Description: " & ErrRec.Description & vbCrLf
         For Each param In ErrRec.Params
            strErr = strErr & "Param" & " = " & param.Param & vbCrLf
         Next param
         strErr = strErr & vbCrLf
    Next ErrRec

    MsgBox strErr, vbOKOnly

End Sub

The following sample illustrates how to call the ShowErrors routine. The sample assumes that the InternetURL has not been set; therefore, the Pull method will fail.

    Dim ceRDA As SSCE.RemoteDataAccess
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.1.0")
   ceRDA.LocalConnectionString = "data source=\NorthwindRDA.sdf"

    On Error Resume Next
    ceRDA .Pull "Customers", "SELECT * FROM Customers", "Provider=sqloledb;Data Source=SampleServer;Initial Catalog=Northwind;user id=SampleUser;password=SamplePassword", TRACKINGOFF

    If ceRDA.ErrorRecords.Count > 0 Then
         ShowErrors ceRDA.ErrorRecords
    End If

   Set ceRDA = Nothing


Programmer's Reference

The Programmer's Reference provides a detailed description of the RDA Object's methods and properties.


RDA Object

Applications use the RDA Object to access a remote SQL Server database.


RDA Object Methods

The RDA Object supports the following methods.

Method | Description
Pull | Extracts data from a SQL Server database and stores that data in a SQL Server CE database table.
Push | Sends changes from a locally tracked SQL Server CE table back to an existing SQL Server table.
SubmitSQL | Submits SQL statements for execution on a remote SQL Server database.


Pull Method

Applications call the Pull method to extract data from a SQL Server database and store it in a SQL Server CE database table.

Applies To

SQL Server CE RDA Object

Syntax

object.Pull(LocalTableName, SQLSelectString, OLEDBConnectionString, RDA_TRACKOPTION, ErrorTableName)

Part | Description
object | A SQL Server CE RDA Object.
LocalTableName | The name of the SQL Server CE table that will receive the extracted SQL Server records.
SQLSelectString | The string that specifies which table, columns, and records to extract from the SQL Server database and store in the SQL Server CE database. This string can be any valid TSQL statement that is row-returning, including SELECT statements or stored procedures.
OLEDBConnectionString | The OLE DB connection string used when connecting to the SQL Server database.
RDA_TRACKOPTION | An option that indicates whether SQL Server CE should track changes made to the pulled table.
ErrorTableName | The name of the local error table that will be created if an error occurs when the Push method is later called to send changes back to SQL Server. This option can only be specified when the RDA_TRACKOPTION value is TRACKINGON.

The RDA_TRACKOPTION enum specifies if the table being pulled to the device is tracked or not tracked.

Constant | Value | Description
TRACKINGON | 1 | SQL Server CE tracks all changes to the pulled table.
TRACKINGOFF | 0 | SQL Server CE does not track changes to the pulled table.

Remarks

The InternetURL property must contain the URL of the Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE device.

The InternetLogin and InternetPassword properties must be specified if the Server Agent is configured to use HTTP Basic Authentication

The LocalTableName is the new table that will be created in the SQL Server CE database. An error will occur if the table already exists.

SQLSelectString controls which data is pulled from the SQL Server table. An error will occur if the resulting recordset contains an unsupported data type, such as TIMESTAMP. The SQLSelectString can specify a WHERE clause to control which records are returned. For example, "SELECT * FROM Customers WHERE State='CA'" would retrieve customers who live in California only. SQLSelectString also supports row-returning stored procedures or views.

RDA_TRACKOPTION specifies whether SQL Server CE should track changes to the pulled table. You should specify TRACKINGON if you want to update the pulled table on the Windows CE device and then push changed records back to the original SQL Server table. When the TRACKINGON option is specified, SQL Server CE keeps track of every record that is inserted, updated, or deleted in the local table. When the application calls the Push method, SQL Server CE uses the change tracking information to locate the inserted, updated, and deleted records in the local SQL Server CE table and propagate these changes back to SQL Server.

The following restrictions apply when RDA_TRACKOPTION is set to TRACKINGON:

  • An error will occur if the SELECT statement returns a nonupdateable recordset.

  • A primary key must be defined on the updateable recordset returned by the SELECT statement.

  • The SELECT statement can reference a view or stored procedure, but the view or stored procedure must only reference one table and must be updateable.

ErrorTableName specifies the name of the table in which Push errors should be stored. If an error arises when the application calls the Push method, SQL Server CE will create the error table and insert a record in the table for each error that occurs. When the Push method completes, the application can examine the error table to determine whether errors have occurred. ErrorTableName can only be specified when TRACKINGON is also specified.

The client must have the appropriate security privileges to read the SQL Server table.

If SQL Server Authentication is used, the user ID specified in OLEDBConnectionString must have the authority to read the SQL Server table.

If SQL Server Integrated Windows Authentication is used by setting INTEGRATED="SSPI" in the OLEDBConnectionString property, the Internet user must have the authority to read the SQL Server table.

  • When IIS is configured to use Anonymous Authentication, the Internet user runs under the identity of the Internet Guest Account (IUSR_computername). If you configure another Windows user account as the IIS anonymous user account, the Internet user runs under the identity of that account.

  • When IIS is configured to use Basic Authentication, the Internet user runs under the identity of the Windows user account for which the client supplied the Internet user name and password.

  • When IIS is configured to use Windows Integrated Authentication, the Internet user runs under the client's identity.

See Also

RDA Object Methods


Push Method

Applications call the Push method to transmit changes from a pulled tracked SQL Server CE table back to the originating SQL Server table.

Applies To

SQL Server CE RDA Object

Syntax

object.Push(LocalTableName, OLEDBConnectionString)

Part | Description
object | A SQL Server CE RDA Object.
LocalTableName | The name of the pulled tracked SQL Server CE table containing updated records to be sent back to the SQL Server table.
OLEDBConnectionString | The OLE DB connection string for the SQL Server database.

Remarks

The InternetURL property must contain the URL of the Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE device.

The InternetLogin and InternetPassword properties must be specified if the Server Agent is configured to use HTTP Basic Authentication.

Applications call the Push method to transmit changes from a pulled tracked SQL Server CE table back to a SQL Server table. The application must have created the local SQL Server CE table by calling the Pull method with RDA_TRACKOPTION set to TRACKINGON.

OLEDBConnectionString specifies all the connect information used while connecting to SQL Server. The connection string passed must allow for appropriate security privileges on the table referenced in the SQL statement.

If ErrorTableName was specified when the Pull method was called, any errors that are detected during the Push will be logged in the error table.

The client must have the appropriate security privileges to read and update the SQL Server table.

If SQL Server Authentication is used, the user ID specified in OLEDBConnectionString must have the authority to read and update the SQL Server table.

If SQL Server Integrated Windows Authentication is used by setting INTEGRATED="SSPI" in the OLEDBConnectionString property, the Internet user must have the authority to read and update the SQL Server table.

  • When IIS is configured to use Anonymous Authentication, the Internet user runs under the identity of the Internet Guest Account (IUSR_computername). If you configure another Windows user account as the IIS anonymous user account, the Internet user runs under the identity of that account.

  • When IIS is configured to use Basic Authentication, the Internet user runs under the identity of the Windows user account for which the client supplied the Internet user name and password.

  • When IIS is configured to use Windows Integrated Authentication, the Internet user runs under the client's identity.

See Also

RDA Object Methods


SubmitSQL Method

Applications call the SubmitSQL method to submit SQL statements for execution on a remote SQL Server database.

Applies To

SQL Server CE RDA Object

Syntax

object.SubmitSQL (SQLString, OLEDBConnectionString)

Part | Description
object | A SQL Server CE RDA Object.
SQLString | Any non-row-returning SQL statement.
OLEDBConnectionString | The OLE DB connection string for the remote SQL Server database.

Remarks

The InternetURL property must contain the URL of the Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE device.

The InternetLogin and InternetPassword properties must be specified if the Server Agent is configured to use HTTP Basic Authentication.

The client must have the appropriate security privileges to execute the statement specified in the SubmitSQL method.

If SQL Server Authentication is used, the user ID specified in OLEDBConnectionString must have the authority to execute the SQL statement.

If SQL Server Integrated Windows Authentication is used by setting INTEGRATED="SSPI" in the OLEDBConnectionString property, the Internet user must have the authority to execute the SQL statement.

  • When IIS is configured to use Anonymous Authentication, the Internet user runs under the identity of the Internet Guest Account (IUSR_computername). If you configure another Windows user account as the IIS anonymous user account, the Internet user runs under the identity of that account.

  • When IIS is configured to use Basic Authentication, the Internet user runs under the identity of the Windows user account for which the client supplied the Internet user name and password.

  • When IIS is configured to use Windows Integrated Authentication, the Internet user runs under the client's identity.

See Also

RDA Object Methods


RDA Object Properties

The RDA Object supports the following properties.

Property | Pull | Push | SubmitSQL
ErrorRecords | Read-only | Read-only | Read-only
InternetURL | Required | Required | Required
InternetLogin | Optional | Optional | Optional
InternetPassword | Optional | Optional | Optional
InternetProxyServer | Optional | Optional | Optional
InternetProxyLogin | Optional | Optional | Optional
InternetProxyPassword | Optional | Optional | Optional
LocalConnectionString | Required | Required | N/A


ErrorRecords Property

The ErrorRecords property contains the SSCEErrors collection for the SQL Server CE RDA Object.

Applies To

SQL Server CE RDA Object

Syntax

object.ErrorRecords [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The error records string

Remarks

The ErrorRecords collection is loaded when a SQL Server CE RDA Object method call fails. The error records in the collection remain available until the next SQL Server CE RDA Object method is called.

Data Type

SSCEErrors

Modifiable

Read-only

Prototype eVC++

HRESULT get_ErrorRecords(SSCEErrors *pVal);

See Also

RDA Object Properties

SSCEError Object


InternetURL Property

The InternetURL property specifies the URL used to connect to the Server Agent. The Server Agent is the IIS ISAPI DLL that connects the SQL Server CE client to the SQL Server system.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetURL [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The URL string, including the name of the Server Agent DLL (Sscesa10.dll)

Remarks

This property must be specified.

Example

http://www.mycompany.com/sqlce/sscesa10.dll

Data Type

String containing a URL.

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetURL(BSTR *pVal);

HRESULT put_ InternetURL (BSTR newVal);

See Also

RDA Object Properties


InternetLogin Property

The InternetLogin property specifies the login name used when connecting to the Server Agent.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetLogin [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The IIS login name

Remarks

This property is required if the Server Agent is configured to use HTTP Basic Authentication or Integrated Windows Authentication.

The default is no login.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetLogin(BSTR *pVal);

HRESULT put_ InternetLogin (BSTR newVal);

See Also

RDA Object Properties


InternetPassword Property

The InternetPassword property specifies the password used when connecting to the Server Agent.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetPassword [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The IIS password string

Remarks

This property is required if the Server Agent is configured to use HTTP Basic Authentication or Integrated Windows Authentication.

When using Basic Authentication, you should configure IIS to use SSL or Private Communication Technology (PCT) encryption to safeguard user passwords. In the absence of SSL or PCT encryption, Basic Authentication transmits passwords across the network in clear text form. This is unsafe; therefore, we strongly recommend that you always use SSL or PCT encryption to safeguard passwords when using Basic Authentication.

The default is no password.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetPassword(BSTR *pVal);

HRESULT put_InternetPassword(BSTR newVal);

See Also

RDA Object Properties


InternetProxyServer Property

The InternetProxyServer property specifies the proxy server to use when accessing the HTTP resource specified in the InternetURL property.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetProxyServer [= value]

Part | Description
object | The SQL Server CE RDA Object
value | ProxyServerName:Port

Remarks

Both the name (or IP address) of the proxy machine and the port number must be specified using the format ProxyServerName:Port.

If SQL Server CE Relay is properly configured on a desktop for serial, USB, or IR synchronization, the InternetProxyServer property must be set to "ppp_peer:nn" where "nn" is a specified client port number.

If the InternetProxyServer property is not set or is empty, no proxy server will be used.

Example

exampleproxy:80

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyServer(BSTR *pVal);

HRESULT put_ InternetProxyServer (BSTR newVal);

See Also

RDA Object Properties

SQL Server CE Relay


InternetProxyLogin Property

The InternetProxyLogin property specifies the login name used when connecting to a proxy server, defined in the InternetProxyServer property, that requires authentication.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetProxyLogin [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The proxy server login name

Remarks

This property is required if the proxy server is configured to use Basic Authentication or Integrated Windows Authentication, even if SQL Server CE Relay has been configured.

The default is no login.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyLogin(BSTR *pVal);

HRESULT put_ InternetProxyLogin (BSTR newVal);

See Also

RDA Object Properties


InternetProxyPassword Property

The InternetProxyPassword property specifies the password used when connecting to a proxy server, defined in the InternetProxyServer property, that requires authentication.

Applies To

SQL Server CE RDA Object

Syntax

object.InternetProxyPassword [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The proxy server password string

Remarks

This property is required if the proxy server is configured to use Basic Authentication or Integrated Windows Authentication, even if SQL Server CE Relay has been configured.

The default is no password.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyPassword(BSTR *pVal);

HRESULT put_InternetProxyPassword(BSTR newVal);

See Also

RDA Object Properties


LocalConnectionString Property

The LocalConnectionString property specifies the OLE DB connection string for the SQL Server CE database on the Windows CE device.

Applies To

SQL Server CE RDA Object

Syntax

object.LocalConnectionString [= value]

Part | Description
object | The SQL Server CE RDA Object
value | The OLE DB connection string for the SQL Server CE database.

Remarks

The following connection properties are supported. All other connection properties are ignored.

Property | Required or Optional | Description
Provider | Optional | Indicates the name of the data source provider. If the provider is not specified, Microsoft.sqlserver.oledb.ce.1.0 is assumed.
Data source | Required | Indicates the name of the database. By convention, you should give your SQL Server CE databases the file extension .sdf.
SSCE:Database Password | Optional | Indicates the database password. This property must be specified if the database was created with a password.

Example

Object.LocalConnectionString = "Data Source=\NorthwindRDA.sdf; SSCE:Database Password=mypassword"

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_LocalConnectionString(BSTR *pVal);

HRESULT put_LocalConnectionString(BSTR newVal);

See Also

RDA Object Properties


Replication

This section describes how you can write applications that use SQL Server CE replication. The Programmer's Guide describes how to develop an application that makes use of the SQL Server CE Replication Object. The Programmer's Reference describes each of the Replication Object's methods and properties.

This material supplements the information contained in SQL Server 2000 Books Online particularly "Programming Replication ActiveX Controls" and "Replication ActiveX Control Interface Reference".


Programmer's Guide

Windows CE applications written in Microsoft® eMbedded Visual Basic or Microsoft® eMbedded Visual C++ initiate and control replication by using the SQL Server CE ActiveX Control Replication Object (Replication Object).

This section provides an overview of the Replication Object; describes what is required to develop, test, and deploy an application that uses the Replication Object; and describes and shows an example of creating, synchronizing, reinitializing, and dropping a subscription by using the Replication Object.


Overview

SQL Server CE replication is always initiated and controlled by the Windows CE application. The application is responsible for creating the subscription to the SQL Server publication, downloading the initial snapshot of the publication to the SQL Server CE Subscriber database on the Windows CE device, and periodically synchronizing the SQL Server CE Subscriber database with the SQL Server publication. The application is responsible for reinitializing and downloading the Subscriber database if this is necessary. Finally, the application is responsible for deleting the Subscriber database from the Microsoft® Windows® CE device when it is no longer needed.

The application initiates and controls all replication functions by using the Replication Object. SQL Server CE provides no administrative means to create, synchronize, or manage replicated SQL Server data on the Windows CE device. SQL Server CE provides no automatic means to periodically initiate synchronization. Initiating and controlling replication are the sole responsibility of the application.

The application developer should shield the user from the details of replication. When an application is installed and run on the Windows CE device, the application should use the Replication Object to automatically subscribe to and download any publications the application needs. The application should use the Replication Object to initiate database synchronization whenever synchronization is required. The application might trigger synchronization, for example, when it detects that the Windows CE device is reconnected to the network, when the application has updated critical database information, when the user requests synchronization, or when a certain time period has elapsed. If an application is deleted from the Windows CE device, it should delete any Subscriber databases that it no longer needs from the device.


Using the Replication Object

SQL Server CE applications use the Replication Object for the following purposes:

  • To create a new anonymous subscription to an existing SQL Server publication and to download the subscription from the SQL Server Distributor to the Windows CE device. The application does this by creating the Replication Object, setting the appropriate Replication Object properties, and calling the AddSubscription, Initialize, Run, and Terminate Replication Object methods.

  • To synchronize an existing SQL Server CE subscription with the SQL Server publication. SQL Server CE subscriptions must always be synchronized with the original Publisher; two SQL Server CE subscriptions cannot be directly synchronized with one another. The application initiates synchronization by creating the Replication Object, setting the appropriate Replication Object properties, and calling the Initialize, Run, and Terminate Replication Object methods.

  • To force a subscription to be reinitialized and downloaded from the Publisher. This is especially useful when the SQL Server CE subscription contains read-only data that is periodically updated at the Publisher. The application does this by creating the Replication Object, setting the appropriate Replication Object properties, and calling the ReinitializeSubscription, Initialize, Run, and Terminate Replication Object methods.

  • To delete an existing SQL Server CE subscription from the Windows CE device. The application does this by creating the Replication Object, setting the appropriate Replication Object properties, and calling the DropSubscription Replication Object method.

See Also

Replication Object Methods


Developing an eMbedded Visual Basic Program

This section describes how you can develop, debug, and deploy an eMbedded Visual Basic application that uses replication. SQL Server CE should already be installed.

Developing an eMbedded Visual Basic Application

You must add the Ssceconsts.bas module to your eMbedded Visual Basic project to incorporate the SQL Server CE enumerations on Windows CE 2.11 and 2.12.

Debugging an eMbedded Visual Basic Application

eMbedded Visual Basic automatically downloads and registers Ssce10.dll and Ssceca10.dll to the Windows CE device when you run or debug your application. Ssce10.dll implements the SQL Server CE database. The SQL Server CE Client Agent, Ssceca10.dll, implements the Replication Object.

eMbedded Visual Basic automatically downloads Ssceinet.dll and Sscesock.dll on Windows CE 2.11 devices. These DLLs correct known deficiencies in the original Wininet.dll and Winsock.dll.

You can test your application using the emulator; however, you cannot use SSL encryption when running through the emulator.

Deploying an eMbedded Visual Basic Application

See Installing SQL Server CE to fully understand the file requirements.

Sample eMbedded Visual Basic Applications

SQL Server CE includes a sample eMbedded Visual Basic application for replication. This sample application illustrates:

  • Using the AddSubscription method to create a subscription.

  • Using the Initialize, Run, and Terminate methods to synchronize the subscription with the SQL Server Publisher.

The SQL Server CE sample application is installed in the \Samples\Northwind subdirectory of your SQL Server CE installation, by default in \Program Files\Microsoft SQL Server CE.

See Also

Replication Object Methods


Developing an eMbedded Visual C++ Program

This section describes how you can develop, debug, and deploy an eMbedded Visual C++ application that uses replication. SQL Server CE should already be installed.

Developing an eMbedded Visual C++ Application

You must include the following files in your eMbedded Visual C++ project when writing an eMbedded Visual C++ application that invokes the Replication Object:

  • Ca_mergex.h

  • Ca_mergex.lib

  • Ole32.lib

  • Oleaut32.lib

You must supply all required parameters for your eMbedded Visual C++ application. A compilation error will occur if all required parameters are not supplied with a method call because default parameter values for method calls are not supported.

Debugging an eMbedded Visual C++ Application

You must manually download and register Ssceca10.dll on the Windows CE device before you run or debug your application. Ssce10.dll implements the SQL Server CE database. The SQL Server CE Client Agent, Ssceca10.dll, implements the Replication Object.

You must download Ssceinet.dll and Sscesock.dll on Windows CE 2.11 devices when using SSL. These DLLs correct known deficiencies in the original Wininet.dll and Winsock.dll.

You can test your application using the emulator; however, you cannot use SSL encryption when running through the emulator.

Deploying an eMbedded Visual C++ Application

See Installing SQL Server CE and Deploying SQL Server CE Applications to fully understand the file requirements.


Replication Programming

The following sections provide code examples of the properties and methods exposed through the Replication Object.


Creating a Subscription on a Windows CE Device

Before you can create a subscription, you must configure SQL Server replication, create the SQL Server publication, and enable the publication for anonymous subscriptions as described in Configuring SQL Server. You must also configure the SQL Server CE Server Agent as an IIS ISAPI Server Extension as described in Configuring IIS

Once the publication is enabled for anonymous subscriptions and IIS is properly configured, you can create a SQL Server CE subscription in either of the following two ways.

Creating a Subscription by Calling AddSubscription

SQL Server CE applications use the Replication Object to programmatically create an anonymous subscription and download that subscription to a SQL Server CE database on a Windows CE device. The application does this by creating the Replication Object, setting the appropriate Replication Object properties, and calling the AddSubscription, Initialize, Run, and Terminate methods. The following examples show how this is done in eMbedded Visual Basic and eMbedded Visual C++.

Creating a Subscription by Copying an Existing Subscription

You can create a new subscription by copying an existing subscription from one Windows CE device to another. This makes it easy to deploy a Windows CE application on many devices when all of the Subscribers are using the same publication. You can create the initial subscription on one Windows CE device by calling the AddSubscription, Initialize, Run, and Terminate methods. You can then deploy the application by copying the application and the initial subscription to as many devices as you want. When your application first synchronizes, SQL Server CE automatically recognizes it as a new Subscriber and creates a new subscription. By copying the initial subscription to a device, you avoid downloading the initial subscription to the device over the network.

SQL Server CE supports both CompactFlash memory and CompactFlash disk drives. One efficient way to deploy large SQL Server CE databases is to distribute them on these storage devices.

Note These devices have relatively long access times when compared to RAM. Using these devices may affect the performance of your application.

See Also

Replication Object Methods


Creating a Subscription in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application subscribes to an existing SQL Server publication that has been enabled for anonymous subscriptions. The example assumes that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication. The example also assumes that the SQL Server Publisher uses SQL Server Authentication and the SQL Server Distributor is located on the same server as the Publisher. The SubscriberConnectionString property specifies the name of the new SQL Server CE database. By convention, SQL Server CE databases are assigned the file extension .sdf. See Handling Replication Errors in eMbedded Visual Basic to see how to handle errors by using the ShowReplErrors subroutine.

' Declare the Replication Object.
   Dim ce As SSCE.Replication

' Create the Replication Object
  Set ce = CreateObject("SSCE.Replication.1.0")

' Set Internet properties
  ce.InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
  ce.InternetLogin = "MyInternetLogin"
  ce.InternetPassword = "MyInternetPassword"

  ' Set Publisher properties
  ce.Publisher = "SamplePublisher"
  ce.PublisherDatabase = "Nwind_SQLCEReplDemo"
  ce.Publication = "SQLCEReplDemo"
  ce.PublisherSecurityMode = DB_AUTHENTICATION
  ce.PublisherLogin = "MySqlPublisherLogin"
  ce.PublisherPassword = "MySqlPublisherPassword"

  ' Set Subscriber properties
  ce.SubscriberConnectionString = "data source=\NorthwindRepl.sdf"
  ce.Subscriber = "SQLCE Sub #1"

  ' Create the new anonymous subscription
  ce.AddSubscription CREATE_DATABASE

  ' Perform the first synchronization to download the initial snapshot by
  ' calling the Initialize, Run Terminate methods
  On Error Resume Next
  ce.Initialize
  If ce.ErrorRecords.Count > 0 Then
    ShowErrors ce.ErrorRecords
  Else
    On Error Resume Next
    ce.Run
    If ce.ErrorRecords.Count > 0 Then
      ShowErrors ce.ErrorRecords
    End If
    ce.Terminate

  End If

  Set ce = Nothing

See Also

SubscriberConnectionString Property


Creating a Subscription in eMbedded Visual C++

The following example illustrates how an eMbedded Visual C++ application subscribes to an existing SQL Server publication that has been enabled for anonymous subscriptions. The example assumes that the SQL Server CE Server Agent is configured with the IIS virtual directory name "sqlce" and that it was configured to require Windows NT or Windows 2000 Integrated Authentication (NTLM). The example assumes that the SQL Server Publisher also uses Integrated Authentication. The SubscriberConnectionString property specifies the name of the new SQL Server CE database. By convention, SQL Server CE databases are assigned the file extension .sdf. See Handling Replication Errors in eMbedded Visual C++ to see how to handle errors by using the ShowErrors method.

   ISSCEMerge      *pISSCEMerge = NULL;
   ISSCEErrors  *pISSCEErrors = NULL;
   HRESULT          hr;
   BSTR            bstr = NULL;
   BOOL            fInitialized = FALSE;
   LONG            lPubChanges;
   LONG            lPubConflicts;
   LONG            lSubChanges;

   /* Create the Replication Object */
   CoCreateInstance(CLSID_Replication, NULL, CLSCTX_INPROC_SERVER,
      IID_ISSCEMerge, (LPVOID *) &pISSCEMerge);

  /* Set Internet properties */
   bstr = SysAllocString
     (L"http://www.mycompany.com/sqlce/sscesa10.dll");
   pISSCEMerge->put_InternetURL(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"MyInternetLogin");
   pISSCEMerge->put_InternetLogin(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"MyInternetPassword");
   pISSCEMerge->put_InternetPassword(bstr);
   SysFreeString(bstr);

   /* Set Publisher properties */
   bstr = SysAllocString(L"SamplePublisher");
   pISSCEMerge->put_Publisher(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"Nwind_SQLCEReplDemo");
   pISSCEMerge->put_PublisherDatabase(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"SQLCEReplDemo");
   pISSCEMerge->put_Publication(bstr);
   SysFreeString(bstr);

   pISSCEMerge->put_PublisherSecurityMode(NT_AUTHENTICATION);

   /* Set Subscriber properties */
   bstr = SysAllocString(L"Data Source=\\NorthwindRepl.sdf");
   pISSCEMerge->put_SubscriberConnectionString(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"SQLCE Sub #1");
   pISSCEMerge->put_Subscriber(bstr);
   SysFreeString(bstr);

   /* Create the new anonymous subscription */
   pISSCEMerge->AddSubscription(CREATE_DATABASE);

   /* Perform the first synchronization to download the initial replica */
   hr = pISSCEMerge->Initialize();
   if (SUCCEEDED(hr))
      {
      fInitialized = TRUE;
      hr = pISSCEMerge->Run();
      }

   if (SUCCEEDED(hr))
      {
      pISSCEMerge->get_PublisherChanges(&lPubChanges);
      pISSCEMerge->get_PublisherConflicts(&lPubConflicts);
      pISSCEMerge->get_SubscriberChanges(&lSubChanges);
      }
   else
      {
   if(SUCCEEDED(hr = pISSCEMerge->get_ErrorRecords(&pISSCEErrors)))
      {
      ShowErrors(pISSCEErrors);
      pISSCEErrors->Release();
      };
      }

   if (fInitialized)
      {
      (void)pISSCEMerge->Terminate();
      }

See Also

SubscriberConnectionString Property


Synchronizing a Subscription

Applications use the Replication Object to synchronize an existing SQL Server subscription. The application must call the Initialize, Run, and Terminate methods in succession on a single instance of the Replication Object.

See Also

Initialize Method

Run Method

Terminate Method


Synchronizing a Subscription in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application initiates synchronization. The example assumes that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication. The example also assumes that the SQL Server Publisher uses SQL Server Authentication and the SQL Server Distributor is located on the same server as the Publisher. See Handling Replication Errors in eMbedded Visual Basic to see how to handle errors using the ShowReplErrors subroutine.

   ' Declare the Replication Object.
   Dim ce As SSCE.Replication

   ' Create the Replication Object
  Set ce = CreateObject("SSCE.Replication.1.0")

  ' Set Internet properties
  ce.InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
  ce.InternetLogin = "MyInternetLogin"
  ce.InternetPassword = "MyInternetPassword"

  ' Set Publisher properties
  ce.Publisher = "SamplePublisher"
  ce.PublisherDatabase = "Nwind_SQLCEReplDemo"
  ce.Publication = "SQLCEReplDemo"
  ce.PublisherSecurityMode = DB_AUTHENTICATION
  ce.PublisherLogin = "MySqlPublisherLogin"
  ce.PublisherPassword = "MySqlPublisherPassword"

  ' Set Subscriber properties
  ce.SubscriberConnectionString = "data source=\NorthwindRepl.sdf"
  ce.Subscriber = "SQLCE Sub #1"

  ' Call the Initialize, Run, and Terminate methods to synchronize the subscription
  On Error Resume Next
  ce.Initialize
  If ce.ErrorRecords.Count > 0 Then
    ShowErrors ce.ErrorRecords
  Else
    On Error Resume Next
    ce.Run
    If ce.ErrorRecords.Count > 0 Then
      ShowErrors ce.ErrorRecords
    End If
    ce.Terminate

  End If

  Set ce = Nothing


Synchronizing a Subscription in eMbedded Visual C++

The following example illustrates how an eMbedded Visual C++ application initiates synchronization. The example assumes that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication. The example also assumes that the SQL Server Publisher uses SQL Server Authentication and the SQL Server Distributor is located on the same server as the Publisher. See Handling Replication Errors in eMbedded Visual C++ to see how to handle errors using the ShowErrors method.

   ISSCEMerge      *pISSCEMerge = NULL;
   ISSCEErrors  *pISSCEErrors = NULL;
   HRESULT          hr;
   BSTR            bstr = NULL;
   BOOL            fInitialized = FALSE;
   LONG            lPubChanges;
   LONG            lPubConflicts;
   LONG            lSubChanges;

   /* Create the Replication Object */
   CoCreateInstance(CLSID_Replication, NULL, CLSCTX_INPROC_SERVER,
      IID_ISSCEMerge, (LPVOID *) &pISSCEMerge);

  /* Set Internet properties */
   bstr = SysAllocString
     (L"http://www.mycompany.com/sqlce/sscesa10.dll");
   pISSCEMerge->put_InternetURL(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"MyInternetLogin");
   pISSCEMerge->put_InternetLogin(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"MyInternetPassword");
   pISSCEMerge->put_InternetPassword(bstr);
   SysFreeString(bstr);

   /* Set Publisher properties */
   bstr = SysAllocString(L"SamplePublisher");
   pISSCEMerge->put_Publisher(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"Nwind_SQLCEReplDemo");
   pISSCEMerge->put_PublisherDatabase(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"SQLCEReplDemo");
   pISSCEMerge->put_Publication(bstr);
   SysFreeString(bstr);

   pISSCEMerge->put_PublisherSecurityMode(NT_AUTHENTICATION);

   /* Set Subscriber properties */
   bstr = SysAllocString(L"Data Source=\\NorthwindRepl.sdf");
   pISSCEMerge->put_SubscriberConnectionString(bstr);
   SysFreeString(bstr);

   bstr = SysAllocString(L"SQLCE Sub #1");
   pISSCEMerge->put_Subscriber(bstr);
   SysFreeString(bstr);

   /* Perform the synchronization */
   hr = pISSCEMerge->Initialize();
   if (SUCCEEDED(hr))
      {
      fInitialized = TRUE;
      hr = pISSCEMerge->Run();
      }

   if (SUCCEEDED(hr))
      {
      pISSCEMerge->get_PublisherChanges(&lPubChanges);
      pISSCEMerge->get_PublisherConflicts(&lPubConflicts);
      pISSCEMerge->get_SubscriberChanges(&lSubChanges);
      }
   else
      {
   if(SUCCEEDED(hr = pISSCEMerge->get_ErrorRecords(&pISSCEErrors)))
      {
      ShowErrors(pISSCEErrors);
      pISSCEErrors->Release();
      };
      }

   if (fInitialized)
      {
      (void)pISSCEMerge->Terminate();
      }


Reinitializing a Subscription

Applications use the Replication Object to reinitialize an existing SQL Server subscription. The application must call the ReinitializeSubscription, Initialize, Run, and Terminate methods in succession on a single instance of the Replication Object. This is essential because when the application calls ReinitializeSubscription, the existing replica is simply marked for reinitialization. Only when the application calls Initialize, Run, and Terminate is the existing replica deleted and a new replica of the publication downloaded from the Publisher to the Windows CE device.

Any unmerged changes that were present in the replica are discarded when the existing replica is deleted. SQL Server CE replication makes no attempt to merge the changes into the SQL Server publication before deleting the replica. If you want to merge the change from the replica into the SQL Server publication, you should perform synchronization rather than reinitialization.

See Also

ReinitializeSubscription Method

Initialize Method

Run Method

Terminate Method


Reinitializing a Subscription in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application reinitializes a subscription. The example assumes that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name "sqlce" and that it was configured to require HTTP Basic Authentication. The example also assumes that the SQL Server Publisher uses SQL Server Authentication and the SQL Server Distributor is located on the same server as the Publisher. See Handling Replication Errors in eMbedded Visual Basic to see how to handle errors using the ShowReplErrors Subroutine.

   ' Declare the Replication Object
   Dim ce As SSCE.Replication

   ' Create the Replication Object
  Set ce = CreateObject("SSCE.Replication.1.0")

  ' Set Internet properties
  ce.InternetURL = "http://www.mycompany.com/sqlce/sscesa10.dll"
  ce.InternetLogin = "sample_internetlogin"
  ce.InternetPassword = "sample_internetpwd"

  ' Set Publisher properties
  ce.Publisher = "SamplePublisher"
  ce.PublisherDatabase = "Nwind_SQLCEReplDemo"
  ce.Publication = "SQLCEReplDemo"
  ce.PublisherSecurityMode = DB_AUTHENTICATION
  ce.PublisherLogin = "MySqlPublisherLogin"
  ce.PublisherPassword = "MySqlPublisherPassword"

  ' Set Subscriber properties
  ce.SubscriberConnectionString = "data source=\NorthwindRepl.sdf"
  ce.Subscriber = "SQLCE Sub #1"

  ' Mark the anonymous subscription for re-initialization
   ' The bUploadBeforeReinit parameter is FALSE, so changed data is not uploaded
  ce.ReinitializeSubscription FALSE

  ' Download the most current snapshot for the subscription
  ' Call the Initialize, Run Terminate methods to synchronize the subscription
  On Error Resume Next
  ce.Initialize
  If ce.ErrorRecords.Count > 0 Then
    ShowErrors ce.ErrorRecords
  Else
    On Error Resume Next
    ce.Run
    If ce.ErrorRecords.Count > 0 Then
      ShowErrors ce.ErrorRecords
    End If
    ce.Terminate

  End If

  Set ce = Nothing


Dropping a Subscription

SQL Server CE applications can use the Replication Object to drop an anonymous subscription and optionally delete the SQL Server CE database from the Windows CE device.


Dropping a Subscription in eMbedded Visual Basic

The following example illustrates how an eMbedded Visual Basic application drops an existing subscription and deletes the SQL Server CE database from the Windows CE system.

   ' Declare the Replication Object.
   Dim ce As SSCE.Replication

   ' Create the Replication Object
  Set ce = CreateObject("SSCE.Replication.1.0")

  ' Set Subscriber properties
  ce.SubscriberConnectionString = "data source=\NorthwindRepl.sdf"

  ' Drop the anonymous subscription and delete the SQL Server CE database
  ce.DropSubscription DROP_DATABASE

  Set ce = Nothing


Dropping a Subscription in Visual C++

The following example illustrates how an eMbedded Visual C++ application drops an existing subscription and deletes the SQL Server CE database from the Windows CE system.

   ISSCEMerge      *pISSCEMerge = NULL;
   BSTR            bstr = NULL;

   /* Create the Replication Object */
   CoCreateInstance(CLSID_Replication, NULL, CLSCTX_INPROC_SERVER,
      IID_ISSCEMerge, (LPVOID *) &pISSCEMerge);

   /* Set Subscriber properties */
   bstr = SysAllocString(L"data source=\\NorthwindRepl.sdf");
   pISSCEMerge->put_SubscriberConnectionString(bstr);
   SysFreeString(bstr);

   /* Drop the subscription and delete the database */
   pISSCEMerge->DropSubscription(DROP_DATABASE));


Handling Replication Errors

This section illustrates how to capture and display replication errors.


Handling Replication Errors in eMbedded Visual Basic

The following eMbedded Visual Basic sample takes the SSCEErrors Collection as an input parameter and displays each of the SSCEError Objects in the collection.

Sub ShowErrors(ErrColl As SSCEErrors)

  'Initialize error variables to view error collection
  Dim ErrRec As Object  'SSCE.ErrorRecords
  Dim param As Object
  Dim strErr As String

  strErr = ""

  For Each ErrRec In ErrColl
     strErr = strErr & "Source: " & ErrRec.Source & vbCrLf
     strErr = strErr & "Number: " & Hex(ErrRec.Number) & vbCrLf
     strErr = strErr & "NativeError: " & ErrRec.NativeError & vbCrLf
     strErr = strErr & "Description: " & ErrRec.Description & vbCrLf
     For Each param In ErrRec.Params
      strErr = strErr & "Param" & " = " & param.Param & vbCrLf
     Next param
     strErr = strErr & vbCrLf
  Next ErrRec

  MsgBox strErr, vbOKOnly

End Sub

The following sample illustrates how to call the ShowErrors routine. It assumes that the AddSubscription method call fails because a database with the same name already exists.

   Dim ce As SSCE.Replication
  Set ce = CreateObject("SSCE.Replication.1.0")
  ce.SubscriberConnectionString = "data source=\NorthwindRepl.sdf"

   On Error Resume Next
   ce.AddSubscription CREATE_DATABASE

   If ce.ErrorRecords.Count > 0 Then
      ShowErrors ce.ErrorRecords
   End If

  Set ce = Nothing

See Also

SSCEErrors Collection

SSCEError Object

AddSubscription Method


Handling Replication Errors in eMbedded Visual C++

The following eMbedded Visual C++ example retrieves and displays replication errors.

#define       INC_OLE2
#define      INITGUID
#include    <windows.h>
#include    <ole2.h>
#include      <stdio.h>
#include    "ca_mergex.h"

void   ShowErrors(ISSCEErrors* pISSCEErrors)
   {
   HRESULT         hr;
   LONG            cbBuf;
   LONG            i;
   LONG            lErrorCount;
   LONG            lErrorIndex;
   LONG            lParamCount;
   LONG            lParamIndex;
   VARIANT         var;
   VARIANT         varParam;
   WCHAR            wszBuff[4096];
   WCHAR*         pwszBuffPos = &wszBuff[0];
   BSTR            bstr;
   ISSCEError*      pISSCEError = NULL;
   ISSCEParams*   pISSCEParams = NULL;
   ISSCEParam*      pISSCEParam = NULL;
   BOOL            fSuccess = FALSE;

   // Initialize variants
   VariantInit(&var);
   VariantInit(&varParam);

   // Get count of errors
   if(FAILED(hr = pISSCEErrors->get_Count(&lErrorCount))) goto Exit;
   if (lErrorCount <= 0)
      {
      MessageBox(NULL, L"No extended error information.",L"ShowErrors", MB_OK);
      fSuccess = TRUE;
      goto Exit;
      }

   // Display errors, one at a time
   for (lErrorIndex = 0; lErrorIndex < lErrorCount; lErrorIndex++)
      {
      cbBuf = swprintf(pwszBuffPos, L"E R R O R  %d of %d\r\n", lErrorIndex+1, lErrorCount);
      pwszBuffPos += cbBuf;

      // Get next error record
      var.vt = VT_I4;
      var.lVal = lErrorIndex;
      if(FAILED(hr = pISSCEErrors->get_Item(var, &pISSCEError))) goto Exit;

      // Error Description
      if (FAILED(hr = pISSCEError->get_Description(&bstr))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"DESCRIPTION: '%s'\r\n", bstr);
      pwszBuffPos += cbBuf;
      SysFreeString(bstr);

      // Error Number
      if (FAILED(hr = pISSCEError->get_Number(&i))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"NUMBER: %8.8X\r\n", i);
      pwszBuffPos += cbBuf;

      // Native Error
      if (FAILED(hr = pISSCEError->get_NativeError(&i))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"NATIVE_ERROR: %d\r\n", i);
      pwszBuffPos += cbBuf;

      // Error Source
      if (FAILED(hr = pISSCEError->get_Source(&bstr))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"SOURCE: '%s'\r\n", bstr);
      pwszBuffPos += cbBuf;
      SysFreeString(bstr);

      // Retrieve the Error Parameters
      if (FAILED(hr = pISSCEError->get_Params(&pISSCEParams))) goto Exit;

      // Get the number of Error Parameters
      if (FAILED(hr = pISSCEParams->get_Count(&lParamCount))) goto Exit;

      // Display the Value of Each Parameter
      for (lParamIndex = 0; lParamIndex < lParamCount; lParamIndex++)
         {

         // Get the parameter object
         var.vt = VT_I4;
         var.lVal = lParamIndex;
         if (FAILED(hr = pISSCEParams->get_Item(var, &pISSCEParam))) goto Exit;

         // Get and display the parameter value
         if (FAILED(hr = pISSCEParam->get_Param(&varParam))) goto Exit;
         if (VT_I4 == varParam.vt || VT_UI4 == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.lVal);
            }
         else if (VT_I2 == varParam.vt || VT_UI2 == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.iVal);
            }
         else if (VT_BSTR == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: '%s'\r\n", lParamIndex, varParam.bstrVal);
            }
         pwszBuffPos += cbBuf;

         // Clear variant
         VariantClear(&varParam);

         // Release the parameter object
         pISSCEParam->Release();
         pISSCEParam = NULL;
         }
      cbBuf = swprintf(pwszBuffPos, L"\r\n");
      pwszBuffPos += cbBuf;

      }

   // Display error information
   MessageBox(NULL, wszBuff,L"Error", MB_OK);
   fSuccess = TRUE;

Exit:
   // Release the parameter object
   if (pISSCEParam)
      {
      pISSCEParam->Release();
      pISSCEParam = NULL;
      }

   // Release the parameters object
   if (pISSCEParams)
      {
      pISSCEParams->Release();
      pISSCEParams = NULL;
      }

   // Release the error object
   if (pISSCEError)
      {
      pISSCEError->Release();
      pISSCEError = NULL;
      }

   // Errors object is released in calling routine
   if (!fSuccess)
      {
      MessageBox(NULL, L"Error while processing errors!",L"ShowErrors", MB_OK);
      }
   return;
   }


Programmer's Reference

This section provides a detailed description of the Replication Object's methods and properties.


Replication Object

Applications use the Replication Object to initiate and control replication. The object is used to:

  • Create a new anonymous subscription to an existing SQL Server publication.

  • Synchronize an existing SQL Server CE replica with the SQL Server publication.

  • Reinitialize an existing replica by replacing it with the latest version of the SQL Server publication.

  • Drop an existing SQL Server CE subscription and delete the SQL Server CE database containing the replica from the Windows CE device.


Replication Object Methods

The Replication Object supports the following methods:

Method | Description
AddSubscription Method | Creates a new anonymous subscription to an existing SQL Server publication.
DropSubscription Method | Drops the subscription to a SQL Server publication and optionally deletes the SQL Server CE database from the Windows CE device.
ReinitializeSubscription Method | Marks a subscription for reinitialization.
Initialize Method | Initializes merge replication.
Run Method | Invokes merge replication.
Terminate Method | Completes merge replication.


AddSubscription Method

Applications call the AddSubscription method to create a new anonymous subscription to an existing SQL Server publication. After calling the AddSubscription method, the application must call the Initialize, Run, and Terminate methods to download or synchronize the new subscription to the publication based on the latest snapshot.

Applies To

SQL Server CE Replication Object

Syntax

object.AddSubscription(DBADDOPTION)

Part | Description
object | SQL Server CE Replication Object
DBADDOPTION | Add subscription option

The DBADDOPTION specifies the source of the newly created SQL Server CE database.

Constant | Value | Description
EXISTING_DATABASE | 0 | Assumes the SQL Server CE database is already created.
CREATE_DATABASE | 1 | Causes the SQL Server CE database to be created on the Windows CE device (default).

Remarks

SQL Server CE replication only supports anonymous subscriptions.

The database administrator must configure SQL Server to support replication, create the SQL Server publication, and enable the publication for anonymous subscriptions before any SQL Server CE application can subscribe to the publication. The administrator does this on the SQL Server system using either the administrative or programmatic interfaces of SQL Server replication

DBADDOPTION specifies the source of the newly created SQL Server CE database. The DBADDOPTION parameter is optional. The parameter's default value is CREATE_DATABASE.

The DBADDOPTION value EXISITING_DATABASE specifies that the database already exists, but contents are obtained from the publisher via the network. In this case, the AddSubscription, Initialize, Run, and Terminate method calls create the SQL Server CE subscription and download the database contents from the SQL Server publisher.

The DBADDOPTION value CREATE_DATABASE specifies that the SQL Server CE database must first be created then the subscription contents are obtained from the publisher via the network. In this case, the AddSubscription, Initialize, Run, and Terminate method calls create the SQL Server CE database and download the database contents from the SQL Server publisher.

The DBADDOPTION parameter only affects how the SQL Server CE database is initially created and treated by the SQL Server CE Client Agent, therefore determining what data is downloaded to the Windows CE device from the Server.

SQL Server CE replication does not support the SubscriptionHost parameter.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Prototype eVC++

HRESULT AddSubscription(DBADDOPTION DBAddOption);

See Also

Replication Object Methods


DropSubscription Method

Applications call the DropSubscription method to drop the subscription to a Microsoft® SQL Server™ publication and optionally delete the SQL Server CE database from the Microsoft Windows® CE device.

Applies To

SQL Server CE Replication Object

Syntax

object.DropSubscription(DBDROPOPTION)

Part | Description
object | SQL Server CE Replication Object.
DBDROPOPTION | Indicates whether the SQL Server CE database should be deleted.

DBDROPOPTION specifies whether to delete or leave the SQL Server CE database.

Constant | Value | Description
DROP_DATABASE | 1 | Deletes the SQL Server CE database (default).
LEAVE_DATABASE | 0 | Deletes the replication system tables and 3 replication system columns in the user tables but does not delete the database.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Remarks

The DBDROPOPTION parameter is optional. The parameter's default value is DROP_DATABASE. If the DBDROPOPTION parameter is specified, its value can be DROP_DATABASE or LEAVE_DATABASE.

Prototype eVC++

HRESULT DropSubscription(DBDROPOPTION DBDropOption);

Replication Object Methods

SSCEErrors Collection


ReinitializeSubscription Method

Applications call the ReinitializeSubscription method to mark a subscription for reinitialization. After calling the ReinitializeSubscription method, the application must call the Initialize, Run, and Terminate methods to download a new subscription of the publication to the CE device based on the latest snapshot.

Applies To

SQL Server CE Replication Object

Syntax

object.ReinitializeSubscription(VARIANT_BOOL bUploadBeforeReInit)

Part | Description
object | SQL Server CE Replication Object.
bUploadBeforeReInit | Indicates whether the SQL Server CE database should upload a message before reinitializing the subscription. This is a BOOLEAN value. The default is FALSE, meaning not to upload.

Remarks

A flag is marked in the SQL Server CE subscription system table to signify that during the next synchronization, the subscription should be reinitialized. After calling the ReinitializeSubscription method, the application must call the Initialize, Run, and Terminate methods to delete the existing replica and download a new replica of the publication to the Windows CE device.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Prototype eVC++

HRESULT ReinitializeSubscription();

See Also

Replication Object Methods


Initialize Method

Applications call the Initialize method to prepare for synchronization.

Applies To

SQL Server CE Replication Object

Syntax

object.Initialize()

Part | Description
object | SQL Server CE Replication Object

Remarks

The application must call the Initialize method before calling the Run method. Specifically, the application must call the Initialize, Run, and Terminate methods in succession.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Prototype eVC++

HRESULT Initialize( );

See Also

Replication Object Methods


Run Method

Applications call the Run method to invoke merge replication.

Applies To

SQL Server CE Replication Object

Syntax

object.Run()

Part | Description
object | SQL Server CE Replication Object

Remarks

The application must call the Initialize method before calling the Run method and the Terminate method after calling the Run method. Specifically, the application must call the Initialize, Run, and Terminate methods in succession.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Prototype eVC++

HRESULT Run( );

See Also

Replication Object Methods


Terminate Method

Applications call the Terminate method to complete the merge replication process.

Applies To

SQL Server CE Replication Object

Syntax

object.Terminate()

Part | Description
object | SQL Server CE Replication Object

Remarks

The application must call the Terminate method after calling the Run method. Specifically, the application must call the Initialize, Run, and Terminate methods in succession.

Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

Prototype eVC++

HRESULT Terminate( );

See Also

Replication Object Methods


Replication Object Properties

The Replication Object supports the following properties.

PROPERTY | ADD SUBSCRIPTION | INITIALIZERUN TERMINATE | REINITIALIZE SUBSCRIPTION | DROP SUBSCRIPTION
Distributor Property | N/A | Optional | N/A | N/A
DistributorNetwork Property | N/A | Optional | N/A | N/A
DistributorAddress Property | N/A | Optional | N/A | N/A
DistributorSecurityMode Property | N/A | Optional | N/A | N/A
DistributorLogin Property | N/A | Optional | N/A | N/A
DistributorPassword Property | N/A | Optional | N/A | N/A
ErrorRecords Property | Read-only | Read-only | Read-only | Read-only
ExchangeType Property | N/A | Optional | N/A | N/A
HostName Property | N/A | Optional | N/A | N/A
InternetURL Property | N/A | Required | N/A | N/A
InternetLogin Property | N/A | Optional | N/A | N/A
InternetPassword Property | N/A | Optional | N/A | N/A
InternetProxyServer Property | N/A | Optional | N/A | N/A
InternetProxyLogin Property | N/A | Optional | N/A | N/A
InternetProxyPassword Property | N/A | Optional | N/A | N/A
LoginTimeout Property | N/A | Optional | N/A | N/A
ProfileName Property | N/A | Optional | N/A | N/A
Publisher Property | N/A | Required | N/A | N/A
PublisherNetwork Property | N/A | Optional | N/A | N/A
PublisherAddress Property | N/A | Optional | N/A | N/A
PublisherSecurityMode Property | N/A | Optional | N/A | N/A
PublisherLogin Property | N/A | Optional | N/A | N/A
PublisherPassword Property | N/A | Optional | N/A | N/A
PublisherDatabase Property | N/A | Required | N/A | N/A
Publication Property | N/A | Required | N/A | N/A
PublisherChanges Property | N/A | Read-only | N/A | N/A
PublisherConflicts Property | N/A | Read-only | N/A | N/A
QueryTimeout Property | N/A | Optional | N/A | N/A
Subscriber Property | N/A | Required | N/A | N/A
SubscriberConnectionString Property | Required | Required | Required | Required
SubscriberChanges Property | N/A | Read-only | N/A | N/A
SubscriberConflicts Property | N/A | Read-only | N/A | N/A
Validate Property | N/A | Optional | N/A | N/A

The following SQL Replication Object properties are not supported on SQL Server CE:

  • FTPAddress

  • FTPLogin

  • FTPPassword

  • FTPPort

  • SubscriptionName

  • SubscriberDatabase

  • SubscriberLogin

  • SubscriberSecurityMode

  • SubscriptionType

  • SubscriptionDataSourceType


Distributor Property

The Distributor property specifies the SQL Server replication Distributor.

Applies To

SQL Server CE Replication Object

Syntax

object.Distributor [= value]

Part | Description
object | SQL Server CE Replication Object
value | Name of the Distributor used by the Publisher

Remarks

The Distributor is the SQL Server computer where the snapshots are stored and where replication history and statistics are logged.

If the DistributorNetwork and DistributorAddress properties are specified, they will be used instead of the Distributor property when connecting to the Distributor.

The Distributor property is optional. If Distributor connection properties are not specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and Publisher connection properties will be used when connecting to the Distributor.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_Distributor(BSTR *pVal);

HRESULT put_Distributor(BSTR newVal);

See Also

Replication Object Properties


DistributorNetwork Property

The DistributorNetwork property specifies the network protocol used when the SQL Server CE Server Replication Agent communicates with the Distributor.

Applies To

SQL Server CE Replication Object

Syntax

object.DistributorNetwork [= value]

Part | Description
object | SQL Server CE Replication Object
value | NETWORK_TYPE specifies the network protocol used when the SQL Server CE Server Agent communicates with the Distributor

Remarks

This property must be specified when the SQL Server CE Server Agent must connect to the Distributor by using a network protocol other than the SQL Server Client Network Utility.

The DistributorNetwork property is optional. If Distributor connection properties are not specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and Publisher connection properties will be used when connecting to the Distributor.

The DistributorAddress property must be specified if the value of the DistributorNetwork property is not DEFAULT_NETWORK (default).

Data Type

The NETWORK_TYPE specifies the network protocol used when the SQL Server CE Server Agent communicates with the Distributor.

Constant | Value | Description
DEFAULT_NETWORK | 0 | Use the current configured client Net-Library (default).
MULTI_PROTOCOL | 2 | Multiprotocol Net Library.
TCPIP_SOCKETS | 1 | TCP/IP Sockets Net Library.

Modifiable

Read/write

Prototype eVC++

HRESULT get_DistributorNetwork(NETWORK_TYPE *pVal);

HRESULT put_DistributorNetwork(NETWORK_TYPE newVal);

See Also

Replication Object Properties


DistributorAddress Property

The DistributorAddress property specifies the network address used when connecting to the Distributor. It is specified when the DistributorNetwork property is specified.

Applies To

SQL Server CE Replication Object

Syntax

object.DistributorAddress [= value]

Part | Description
object | SQL Server CE Replication Object
value | Network address used when connecting to the Distributor

Remarks

This is a required property only when DistributorNetwork is set to a value other than DEFAULT_NETWORK.

Specify this property when you want to control how the SQL Server CE Server Agent communicates with the Distributor. For example, if the SQL Server CE Server Agent and the Distributor are located on two different systems and these systems communicate over the Internet, DistributorNetwork could be set to TCPIP_SOCKETS, and DistributorAddress could be set to a specific IP address. If the DistributorNetwork is TCP/IP_SOCKETS or MULTI_PROTOCOL using TCP/IP, then the DistributorNetwork value is in the form:

'IP address,socket' (i.e. '111.11.11.11,1433')

If Distributor connection properties are not specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and Publisher connection properties will be used when connecting to the Distributor.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_DistributorAddress(BSTR *pVal);

HRESULT put_DistributorAddress(BSTR newVal);

See Also

Replication Object Properties


DistributorSecurityMode Property

The DistributorSecurityMode property specifies the security mode used when connecting to the Distributor.

Applies To

SQL Server CE Replication Object

Syntax

object.DistributorSecurityMode [= value]

Part | Description
object | SQL Server CE Replication Object
value | SECURITY_TYPE constant that specifies the mode of security enforced at the Distributor

Remarks

If the value is DB_AUTHENTICATION (default), DistributorLogin and DistributorPassword will be used when connecting to the Distributor.

NT_AUTHENTICATION is not supported for DistributorSecurityMode unless the Distributor uses Windows NT 4.0 or Windows 2000.

If Distributor connection properties are not specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and Publisher connection properties will be used when connecting to the Distributor.

Data Type

The SECURITY_TYPE specifies the security type.

Constant | Value | Description
DB_AUTHENTICATION | 0 | Standard security (default)
NT_AUTHENTICATION | 1 | Integrated security

Modifiable

Read/write

Prototype eVC++

HRESULT get_DistributorSecurityMode(SECURITY_TYPE *pVal);

HRESULT put_DistributorSecurityMode(SECURITY_TYPE newVal);

See Also

Replication Object Properties


DistributorLogin Property

The DistributorLogin property specifies the login name used when connecting to the Distributor.

Applies To

SQL Server CE Replication Object

Syntax

object.DistributorLogin [= value]

Part | Description
object | SQL Server CE Replication Object
value | Distributor login name

Remarks

This is a required property if DistributorSecurityMode is set to DB_AUTHENTICATION.

If the Distributor connection properties are not specified, it is assumed that the Publisher and Distributor are the same instance of SQL Server and that the Publisher connection properties are used when connecting to the Distributor.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_DistributorLogin(BSTR *pVal);

HRESULT put_DistributorLogin(BSTR newVal);

See Also

Replication Object Properties


DistributorPassword Property

The DistributorPassword property specifies the login password used when connecting to the Distributor.

Applies To

SQL Server CE Replication Object

Syntax

object.DistributorPassword [= value]

Part | Description
object | SQL Server CE Replication Object
value | Distributor password string

Remarks

This property is used only when DistributorSecurityMode is set to DB_AUTHENTICATION.

If the Distributor connection properties are not specified, it is assumed that the Publisher and Distributor are the same instance of SQL Server and that Publisher connection properties will be used when connecting to the Distributor.

The default is no password.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_DistributorPassword(BSTR *pVal);

HRESULT put_DistributorPassword(BSTR newVal);

See Also

Replication Object Properties


ErrorRecords Property

The ErrorRecords property contains the SSCEErrors collection for the SQL Server CE Replication Object.

Applies To

SQL Server CE Replication Object

Syntax

object.ErrorRecords [= value]

Part | Description
object | SQL Server CE Replication Object
value | SSCEErrors collection containing the SSCEError Objects

Remarks

The ErrorRecords collection is loaded when a SQL Server CE Replication Object method call fails. The error records in the collection remain available until the next SQL Server CE Replication Object method is called.

Data Type

SSCEErrors

Modifiable

Read-only

Prototype eVC++

HRESULT get_ErrorRecords(SSCEErrors *pVal);

See Also

Replication Object Properties

SSCEError Object


ExchangeType Property

The ExchangeType property specifies how data is exchanged between the Publisher and the Subscriber. BIDIRECTIONAL specifies that data be sent in both directions. SQL Server CE replication supports BIDIRECTIONAL exchanges only.

Applies To

SQL Server CE Replication Object

Syntax

object.ExchangeType [= value]

Part | Description
object | SQL Server CE Replication Object
value | EXCHANGE_TYPE constant that specifies the direction in which data can be merged

Remarks

BIDIRECTIONAL is the default value. SQL Server CE does not support the Exchange_Type values DOWNLOAD or UPLOAD.

Data Type

EXCHANGE_TYPE specifies whether the changes should be merged up to the Publisher or in both directions.

Constant | Value | Description
BIDIRECTIONAL | 3 | Merge all changes between the Publisher and Subscriber (default).

Modifiable

Read/write

Prototype eVC++

HRESULT get_ExchangeType(EXCHANGE_TYPE *pVal);

HRESULT put_ExchangeType(EXCHANGE_TYPE newVal);

See Also

Replication Object Properties


HostName Property

The HostName property sets the host name used when connecting to the Publisher. It provides a value used when the publication is dynamically filtered using the SQL Server HOST_NAME( ) function.

Applies To

SQL Server CE Replication Object

Syntax

object.HostName [= value]

Part | Description
object | SQL Server CE Replication Object
value | Host name

Remarks

This property is optional.

Use the HostName property to set a value for HOST_NAME( ) in a dynamic filter. For example, if the subset filter clause

"LName = HOST_NAME( )"

is specified for an article and you set the HostName property to "Jones" before calling the Run method, only rows having "Jones" in the LName column will be present in the subscription.

Your application must call the ReinitializeSubscription method if it changes the value of the HostName property after the subscription is created.

The default is no HostName.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_Hostname(BSTR *pVal);

HRESULT put_ Hostname (BSTR newVal);

See Also

Replication Object Properties


InternetURL Property

The InternetURL property specifies the URL used to connect to the SQL Server CE Server Agent ISAPI DLL.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetURL [= value]

Part | Description
object | SQL Server CE Replication Object
value | URL string

Remarks

This property must be specified.

Data Type

String containing a URL.

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetURL(BSTR *pVal);

HRESULT put_ InternetURL (BSTR newVal);

See Also

Replication Object Properties


InternetLogin Property

The InternetLogin property specifies the login name used when connecting to the SQL Server CE Server Agent ISAPI DLL.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetLogin [= value]

Part | Description
object | SQL Server CE Replication Object
value | IIS login name

Remarks

This property is required if the SQL Server CE Server Agent is configured to use Basic Authentication.

The default is no login.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetLogin(BSTR *pVal);

HRESULT put_ InternetLogin (BSTR newVal);

See Also

Replication Object Properties


InternetPassword Property

The InternetPassword property specifies the password used when connecting to the SQL Server CE Server Agent.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetPassword [= value]

Part | Description
object | SQL Server CE Replication Object
value | IIS password string

Remarks

This property is required if the SQL Server CE Server Agent is configured to use Basic Authentication.

When using Basic Authentication, you should configure IIS to use SSL or Private Communication Technology (PCT) encryption to safeguard the user's password. In the absence of SSL or PCT encryption, Basic Authentication transmits passwords across the network in clear text form. This is clearly unsafe; therefore, we strongly recommend that you always use SSL or PCT encryption to safeguard passwords when using Basic Authentication.

The default is no password.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetPassword(BSTR *pVal);

HRESULT put_InternetPassword(BSTR newVal);

See Also

Replication Object Properties


InternetProxyServer Property

The InternetProxyServer property specifies the proxy server to use when accessing the HTTP resource specified in the InternetURL property.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetProxyServer [= value]

Part | Description
object | SQL Server CE Replication Object
value | ProxyServerName:Port

Remarks

Both the name (or IP address) of the proxy machine and the port number must be specified using the format "ProxyServerName:Port".

If SQL Server CE Relay is properly configured on a desktop for serial, USB, or IR synchronization, the InternetProxyServer property must be set to "ppp_peer:nn" where "nn" is a specified client port number.

If the InternetProxyServer property is not set or is empty, no proxy server will be used.

Example

exampleproxy:80

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyServer(BSTR *pVal);

HRESULT put_ InternetProxyServer (BSTR newVal);

See Also

Replication Object Properties

SQL Server CE Relay


InternetProxyLogin Property

The InternetProxyLogin property specifies the login name used when connecting to a proxy server, defined in the InternetProxyServer property, that requires authentication.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetProxyLogin [= value]

Part | Description
object | SQL Server CE Replication Object
value | The proxy server login name

Remarks

This property is required if the proxy server is configured to use Basic Authentication or Integrated Windows Authentication, even if SQL Server CE Relay has been configured.

The default is no login.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyLogin(BSTR *pVal);

HRESULT put_ InternetProxyLogin (BSTR newVal);

See Also

Replication Object Properties


InternetProxyPassword Property

The InternetProxyPassword property specifies the password used when connecting to a proxy server, defined in the InternetProxyServer property, that requires authentication.

Applies To

SQL Server CE Replication Object

Syntax

object.InternetProxyPassword [= value]

Part | Description
object | SQL Server CE Replication Object
value | The proxy server password string

Remarks

This property is required if the proxy server is configured to use Basic Authentication or Integrated Windows Authentication, even if SQL Server CE Relay has been configured.

The default is no password.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_InternetProxyPassword(BSTR *pVal);

HRESULT put_InternetProxyPassword(BSTR newVal);

See Also

Replication Object Properties


LoginTimeout Property

The LoginTimeout property specifies the maximum number of seconds to wait for connections to be established.

Applies To

SQL Server CE Replication Object

Syntax

object.LoginTimeout [= value]

Part | Description
object | SQL Server CE Replication Object
value | Number of seconds for connections to be established

Remarks

The default is 15 seconds. A value of 0 means logins can wait indefinitely.

Data Type

Integer

Modifiable

Read/write

Prototype eVC++

HRESULT get_LoginTimeout(short *pVal);

HRESULT put_LoginTimeout(short newVal);

See Also

Replication Object Properties


ProfileName Property

The ProfileName property specifies the name of the agent profile at the Distributor to be used by the Replication Object. A profile defines behavior such as timeout values. You can override the default values by creating a profile on the Distributor and specifying its name through the ProfileName property.

Applies To

SQL Server CE Replication Object

Syntax

object.ProfileName [= value]

Part | Description
object | SQL Server CE Replication Object
value | Agent profile name

Remarks

A profile contains a set of parameters that control the behavior of the SQL Server Reconciler. For example, the profile specifies the LoginTimeOut and QueryTimeOut values used by the SQL Server Reconciler. The profile is stored on the Distributor. The profile is read each time a subscription is synchronized.

The profile allows you to easily change key parameters for synchronization. For example, if you have five SQL Server CE clients who share a profile and you want to change the query time-out value, you simply change the QueryTimeOut value in the profile and all SQL Server CE clients will use the new QueryTimeOut value.

You can also create different profiles for different SQL Server CE clients. For example, a SQL Server CE client that uses a dial-up Internet connection might use one timeout value while a client that uses a high-speed intranet connection might use a different timeout value. The ProfileName property can be used to specify the name of the profile.

If the ProfileName property is not specified, the default profile values are used.

If the ProfileName property is specified, the LoginTimeOut and QueryTimeOut parameters specified in the profile override the LoginTimeOut and QueryTimeOut property values specified through the Replication Object.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_ProfileName(BSTR *pVal);

HRESULT put_ProfileName(BSTR newVal);

See Also

Replication Object Properties


Publisher Property

The Publisher property specifies the name of the Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.Publisher [= value]

Part | Description
object | SQL Server CE Replication Object
value | Publisher name

Remarks

This is a required property.

The Publisher is the SQL Server computer that contains the publication.

If the PublisherNetwork and PublisherAddress properties are specified, they will be used instead of the Publisher property when connecting to the Publisher.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_Publisher(BSTR *pVal);

HRESULT put_Publisher(BSTR newVal);

See Also

Replication Object Properties


PublisherNetwork Property

The PublisherNetwork property specifies the network protocol used when the SQL Server CE Server Agent communicates with the Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherNetwork [= value]

Part | Description
object | SQL Server CE Replication Object
value | NETWORK_TYPE specifies the network protocol used when the SQL Server CE Server Agent communicates with the Publisher

Remarks

This property must be specified when the SQL Server CE Server Agent must connect to the Publisher by using a network protocol other than the SQL Server Client Network Utility.

The PublisherAddress property must be specified if the value of the PublisherNetwork property is not DEFAULT_NETWORK (default).

Data Type

NETWORK_TYPE specifies the network protocol used when the SQL Server CE Server Agent communicates with the Publisher.

Constant | Value | Description
DEFAULT_NETWORK | 0 | Use the current configured client Net Library (default).
MULTI_PROTOCOL | 2 | Multiprotocol Net Library.
TCPIP_SOCKETS | 1 | TCP/IP Sockets Net Library.

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherNetwork(NETWORK_TYPE *pVal);

HRESULT put_PublisherNetwork(NETWORK_TYPE newVal);

See Also

Replication Object Properties


PublisherAddress Property

The PublisherAddress property specifies the network address used when connecting to the Publisher. It is specified when the PublisherNetwork property is specified.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherAddress [= value]

Part | Description
object | SQL Server CE Replication Object
value | Network connection string

Remarks

This property is a required when PublisherNetwork is set to a value other than DEFAULT_NETWORK.

Specify this property when you want to control how the SQL Server CE Replication Agent communicates with the Publisher. For example, if the SQL Server CE Replication Agent and the Publisher are located on two different systems and these two systems communicate over the Internet, PublisherNetwork could be set to TCPIP_SOCKETS, and PublisherAddress could be set to a specific IP address.

If the PublisherNetwork is TCP/IP_SOCKETS or MULTI_PROTOCOL using TCP/IP, then the PublisherNetwork value is in the form:

'IP address,socket' (i.e., '111.11.11.11,1433')

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherAddress(BSTR *pVal);

HRESULT put_PublisherAddress(BSTR newVal);

See Also

Replication Object Properties


PublisherSecurityMode Property

The PublisherSecurityMode property specifies the security mode used when connecting to the Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherSecurityMode [= value]

Part | Description
object | SQL Server CE Replication Object
value | Security mode

Remarks

If the PublisherSecurityMode property value is DB_AUTHENTICATION (default), then the PublisherLogin properties must be specified. The default for PublisherPassword is an empty string.

NT_AUTHENTICATION is only supported on Windows NT and Windows 2000.

Data Type

The SECURITY_TYPE specifies the security type.

Constant | Value | Description
DB_AUTHENTICATION | 0 | Standard security (default)
NT_AUTHENTICATION | 1 | Integrated security

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherSecurityMode(SECURITY_TYPE *pVal);

HRESULT put_PublisherSecurityMode(SECURITY_TYPE newVal);

See Also

Replication Object Properties


PublisherLogin Property

The PublisherLogin property specifies the login name used when connecting to the Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherLogin [= value]

Part | Description
object | SQL Server CE Replication Object
value |

Remarks

This is a required property if PublisherSecurityMode is set to DB_AUTHENTICATION.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherLogin(BSTR *pVal);

HRESULT put_PublisherLogin(BSTR newVal);

See Also

Replication Object Properties


PublisherPassword Property

The PublisherPassword property specifies the login password used when connecting to the Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherPassword [= value]

Part | Description
object | SQL Server CE Replication Object
value |

Remarks

The default is no password (empty string).

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherPassword(BSTR *pVal);

HRESULT put_PublisherPassword (BSTR newVal);

See Also

Replication Object Properties


PublisherDatabase Property

The PublisherDatabase property specifies the name of the publication database.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherDatabase [= value]

Part | Description
object | SQL Server CE Replication Object
value | Publication database name

Remarks

This is a required property.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_PublisherDatabase(BSTR *pVal);

HRESULT put_PublisherDatabase(BSTR newVal);

See Also

Replication Object Properties


Publication Property

The Publication property specifies the publication name.

Applies To

SQL Server CE Replication Object

Syntax

object.Publication [= value]

Part | Description
object | SQL Server CE Replication Object
value | Publication name

Remarks

This is a required property.

The Publication property must specify the name of a publication that has been enabled for anonymous merge subscriptions.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_Publication(BSTR *pVal);

HRESULT put_Publication(BSTR newVal);

See Also

Replication Object Properties


PublisherChanges Property

The PublisherChanges property specifies the total number of Publisher changes applied at the Subscriber when the Run method was last called.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherChanges [= value]

Part | Description
object | SQL Server CE Replication Object
value | Total number of Publisher rows inserted, deleted, and updated

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_PublisherChanges(long *pVal);

See Also

Replication Object Properties


PublisherConflicts Property

The PublisherConflicts property specifies the total number of conflicts that occurred at the Publisher when the Run method was last called.

Applies To

SQL Server CE Replication Object

Syntax

object.PublisherConflicts [= value]

Part | Description
object | SQL Server CE Replication Object
value | Number of conflicts that occurred

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_PublisherConflicts(long *pVal);

See Also

Replication Object Properties


QueryTimeout Property

The QueryTimeout property specifies the number of seconds allowed for internal queries to complete.

Applies To

SQL Server CE Replication Object

Syntax

object.QueryTimeout [= value]

Part | Description
object | SQL Server CE Replication Object.
value | Number of seconds allowed for internal queries to be returned. (Default is 30 seconds.)

Remarks

The default value is 30 seconds.

A value of 0 means queries can wait indefinitely.

Data Type

Integer

Modifiable

Read/write

Prototype eVC++

HRESULT get_QueryTimeout(short *pVal);

HRESULT put_QueryTimeout(short newVal);

See Also

Replication Object Properties


Subscriber Property

The Subscriber property specifies the name of the Subscriber.

Applies To

SQL Server CE Replication Object

Syntax

object.Subscriber [= value]

Part | Description
object | Expression that evaluates to an object in the Applies To list
value | Subscriber name

Remarks

This is a required property.

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_Subscriber(BSTR *pVal);

HRESULT put_Subscriber(BSTR newVal);

See Also

Replication Object Properties


SubscriberConnectionString Property

The SubscriberConnectionString property specifies the OLE DB connection string for the SQL Server CE database on the Windows CE device.

Applies To

SQL Server CE Replication Object

Syntax

object.SubscriberConnectionString [= value]

Part | Description
object | SQL Server CE Replication Object
value | OLE DB connection string for the SQL Server CE database

Remarks

The following connection properties are supported. All other connection properties are ignored.

Property | Required or Optional | Description
Provider | Optional | Indicates the name of the data source provider. If the provider is not specified, Microsoft.sqlserver.oledb.ce.1.0 is assumed.
Data Source | Required | Indicates the name of the database. By convention, you should give your SQL Server CE databases the file extension .sdf.
Locale Identifier | Optional | Indicates the database locale, which specifies the collating order for string comparisons in the database. This property is only meaningful when calling AddSubscription(CREATE_DATABASE). The default database locale is Latin1_General (0x00000409). For other supported value, see the list of Locale Identifiers below.
SSCE:Database Password | Optional | Indicates the database password. This property must be specified if the database was created with a password. To create a database with a password, set this property and call AddSubscription(CREATE_DATABASE).
SSCE:Encrypt Database | Optional | Indicates whether a newly created database should be encrypted. This property is only meaningful when calling AddSubscription(CREATE_DATABASE). The created database is encrypted when this Boolean property is TRUE and a Database Password is specified.

Locale Identifier values are supported when creating a new database using the AddSubscription method. Use the Unique LCID for the value of Locale Identifier. See Collate to find a list of Unique LCID values. You must ensure that the locale is supported on the device where the database is being created.

Example

Object.SubscriberConnectionString = "Data Source=\NorthwindRepl.sdf; Locale Identifier=0x00000409; SSCE:Database Password=mypassword; SSCE:Encrypt Database=TRUE"

Data Type

String

Modifiable

Read/write

Prototype eVC++

HRESULT get_SubscriberConnectionString(BSTR *pVal);

HRESULT put_SubscriberConnectionString(BSTR newVal);

See Also

Replication Object Properties


SubscriberChanges Property

The SubscriberChanges property specifies the total number of Subscriber changes applied at the Publisher when the Run method was last called.

Applies To

SQL Server CE Replication Object

Syntax

object.SubscriberChanges [= value]

Part | Description
object | SQL Server CE Replication Object
value | Total number of rows inserted, deleted, and updated

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_SubscriberChanges(long *pVal);

See Also

Replication Object Properties


SubscriberConflicts Property

The SubscriberConflicts property specifies the total number of conflicts that occurred when applying the changes from the SQL Server CE subscriber to the SQL Server Publisher.

Applies To

SQL Server CE Replication Object

Syntax

object.SubscriberConflicts [= value]

Part | Description
object | SQL Server CE Replication Object.
value | The SubscriberConflicts property is always 0 since all conflicts are detected and logged on the SQL Server Publisher.

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_SubscriberConflicts(long *pVal);

See Also

Replication Object Properties


Validate Property

The Validate property controls whether SQL Server CE replication performs data validation while performing synchronization.

Applies To

SQL Server CE Replication Object

Syntax

object.Validate [= value]

Part | Description
object | SQL Server CE Replication Object
value | VALIDATE_TYPE constant that specifies the type of data validation to perform

Remarks

SQL Server CE does not support ROWCOUNT_AND_CHECKSUM, FAST_ROWCOUNT_ONLY, or FAST_ROWCOUNT_AND_CHECKSUM validation.

Data Type

The VALIDATE_TYPE specifies the security type.

Constant | Value | Description
NO_VALIDATION | 0 | Do no validation (default).
ROWCOUNT_ONLY | 1 | Do a row count comparison on the published data.

Modifiable

Read/write

Prototype eVC++

HRESULT get_Validate(VALIDATE_TYPE newVal);

HRESULT put_Validate(VALIDATE_TYPE pVal);

See Also

Replication Object Properties


Maintaining Your Database

With use, the internal structure of a database can become fragmented, leading to wasted disk space and poor performance if the fragmentation is excessive. Maintaining your database in a manageable, usable structure involves compacting.

Compacting a database has these benefits:

  • Reorganizes a table's pages so they reside in adjacent database pages. This improves performance because the table is no longer fragmented across the database.

  • Reclaims unused space created by object and record deletions. When objects or records are deleted from the database, the space they occupied is marked as available for new additions to the database. However, the size of the database never shrinks unless the database is compacted. For databases in which objects and records are frequently added, deleted, and updated, you should compact frequently.

  • Resets incrementing identity columns so the next value allocated will be one more than the highest value in the remaining records. For example, if all records in the database have been deleted, after compacting the database, the value in the identity column will be 1 when the next record is added. If the highest remaining identity value in the database is 50, after compacting, the value will be 51 when the next record is added. Note that this is true even if records containing values higher than fifty were added previously but were deleted prior to compacting.

  • Regenerates the table statistics used in the query optimization process. These statistics can become out-of-date over time, typically if transactions were rolled back, or if the database was not properly closed due to power loss or failure to completely exit the program before turning the computer off.

Before you can compact a database the following conditions must be met:

  • Sufficient disk space must exist for both the original and compacted versions of the database.

  • The database must not be open.

You should compact a corrupted database in order to repair it.

See Also

CompactDatabase Method


Programmer's Guide to Engine Object

Applications use the Engine Object to control SQL Server CE Engine-specific features, such as compacting a SQL Server CE database. They can only be accessed by using the SQL Server CE ActiveX Control Engine Object.

The Engine Object exposes one method, CompactDatabase Method, and one property, ErrorRecords Property.


CompactDatabase Method

The CompactDatabase method compacts and reclaims wasted space. It can also be used to change the SQL Server CE database's collating order, encryption, and/or password.

Syntax

object.CompactDatabase(SourceConnection, DestConnection)

Part | Description
object | Expression that evaluates to a SQL Server CE Engine Object.
SourceConnection | A string value specifying a connection to the source database to be compacted. An error will occur if the database specified by SourceConnection is already open.
DestConnection | A string value specifying a connection to the destination database to be created by the compaction. An error will occur if the database specified by DestConnection already exists or another file with that name already exists.

Remarks

The SourceConnection and DestConnection parameters specify the properties of the source and destination databases. The following table lists the connection properties that you can specify for each parameter. All other connection properties are ignored.

Property | Source | Destination | Description
Provider | Optional | Optional | Indicates the name of the provider to use to connect to the data source. If this property is not specified, the Microsoft.sqlserver.oledb.ce.1.0 provider is assumed. An error occurs if the name of the provider in the source string is different from the name of the provider in the destination string.
Data Source | Required | Required | Indicates the name of the database. This property is required for both the source and destination connection information.
Locale Identifier | N/A | Optional | Indicates the locale ID for the new database. If this is omitted, the destination database will have the same locale ID as the source database. Locale specifies the collating order for string comparisons in the database. For destination database values, see the table below.
SSCE:Database Password | Required/Optional | Optional | Indicates the password if the database is secured by a password. The source database password must be supplied if the source database contains a password. If this parameter is omitted, the new database will have the same database password as the source database. If the desire is to remove the password from the destination database, database password must be set to an empty string. The database password can be up to 40 characters.
SSCE:Encrypt Database | N/A | Optional | Indicates whether to encrypt the new database. If this parameter is omitted, the new database will have the same encryption as the source database. This is a Boolean value and should be set to TRUE for encryption and FALSE if encryption is not desired.

It is not possible to compact a database "in place"; the source database path and destination database path must be different. The source database must be closed when CompactDatabase is called.

The destination database must not exist when CompactDatabase is called. An error will occur if the database specified by destDatabasePath already exists or another file with that name already exists

If SQL Server CE is terminated when writing data (as a result of power failure or full disk), the data can become corrupted.

Locale Identifier values are supported. Use the Unique LCID for the value of Locale Identifier. See Collate to find a list of Unique LCID values. You must ensure that the locale is supported on the device where the database is being created.

See Also

ErrorRecords Property


ErrorRecords Property

The ErrorRecords property contains the SSCEErrors collection for the SQL Server CE Engine Object.

Syntax

object.ErrorRecords

Part | Description
object | SQL Server CE Engine Object

Remarks

The ErrorRecords collection is loaded when a SQL Server CE Engine Object method call fails. The error records in the collection remain available until the next SQL Server CE Engine Object method is called.

Data Type

SSCEErrors

Modifiable

Read-only

See Also

SSCEError Object

CompactDatabase Method

SSCEErrors Collection


Deploying SQL Server CE Applications

This section describes the processes you need to understand after you have completed your Microsoft® SQL Server™ CE application, so you can package it and distribute it to your customers.

Connection Methods

The method in which you deploy your application depends partially upon the way that you communicate between your Microsoft Windows® CE devices and your backend SQL Server database computer.

Serial, IR, or USB Connections

The docking stations (often called cradles) that most people get when they buy a Windows CE device usually connect to the desktop computer using a connection of this type.

Microsoft ActiveSync® manages the serial connections to the cradles, and notices when a device is inserted into or removed from the cradle. ActiveSync views the files and programs on the device, and downloads new programs to the device. The embedded tools, especially Microsoft eMbedded Visual Basic®, work closely with ActiveSync and use it to automatically download updated files during a build.

Network Connections

When you use a network card, the Windows CE device can talk directly to any computer on the network. Files can be copied easily to and from the device. The Windows CE device can connect to SQL Server installations, and can initiate update tasks to keep the two databases in synchronization. Users can also find application installation packages on the network, and can download and set up these programs on the device. Users with Internet connections can do the same using Microsoft Internet Explorer to browse the Web to find installation packages.

Wireless Phones

After a connection has been established, a wireless phone connection will tend to work more like a network connection than a serial connection. As part of making a connection, the device will either dial into a RAS server or tunnel through an ISP to a broadband connection to the office. The network packets will be handled using the operating system components that facilitate the connection.

Systems and Devices

SQL Server CE applications can use the following systems: a SQL Server system, a Microsoft Internet Information Services (IIS) system, an ActiveSync system, and a Windows CE device.

SQL Server System

This is the system on which SQL Server is running. SQL Server CE supports both remote data access (RDA) and merge replication to SQL Server.

Internet Information Services (IIS) System

This is the system on which IIS is running. SQL Server CE RDA and merge replication communicate with SQL Server through IIS. IIS and SQL Server can reside on the same system or they may reside on separate systems.

ActiveSync System

SQL Server CE includes SQL Server CE Relay, a tool that eliminates the requirement for the Windows CE devices to have a network card for connectivity to SQL Server.

SQL Server CE Relay works in parallel with ActiveSync when it is being used to talk to a Windows CE device using Serial, IR, or USB connections. SQL Server CE Relay acts as a proxy to allow TCP/IP communication from the device to be transmitted to SQL Server using ActiveSync and the desktop computer's network connection.

If you have Windows CE devices without network cards, you will need to include one or more ActiveSync systems in your setup to enable the connections between your Windows CE devices and your SQL Server database.

Windows CE Device

This is the device on which your Windows CE application is deployed.


Application Deployment Overview

To deploy an application that you have built using the SQL Server CE toolkit, you will need to install parts of the application on up to three different kinds of systems: one or more IIS systems, one or more ActiveSync systems, and multiple Windows CE devices.

In addition, you will need to configure your SQL Server system to accept RDA and/or replication requests from your SQL Server CE application.

Deployment may take one of these forms:

  • You can use the development computer to install the parts of the application directly onto the personal computer systems and Windows CE devices.

  • You can create a distribution CD, or any other distribution media, and use it to install the parts of the application onto the computer systems and Windows CE devices.

    Note This process will not require you to use any special install key checking on the media, so the same process can be used to deploy your application from a product server located in your network.

  • You can build a custom Windows CE device, and use Platform Builder to create a custom version of the Windows CE operating system that includes a SQL Server CE application.

    Note The deployment process for the IIS and ActiveSync systems will need to use one of the preceding methods, even if your Windows CE device is getting the SQL Server CE application bits using Platform Builder.

Deploying SQL Server CE Components on an IIS System

If you use either RDA or replication, you must install some SQL Server CE server components on the IIS systems. This will be required both during your application development and during your application deployment after it has been completed.

In preparation for deployment, when the SQL Server CE toolkit was installed on your development computer, the server components for replication and RDA that match your SQL Server CE database engine were copied at the same time.

To install the server tools from your development computer to your IIS system

  1. Navigate to the redist\server subdirectory on your development computer.

  2. Run server.exe and follow the directions of the setup program.

To copy the server tools to a CD image

  1. Navigate to the redist subdirectory on your development computer.

  2. Copy the server subdirectory to your CD image location.

  3. After the CD has been created and distributed, install the server tools on the IIS system by navigating to the server subdirectory on your CD and then running Server.exe.

To uninstall the server tools from the IIS computer

  1. In Control Panel, double-click Add/Remove Programs, and then select the Microsoft SQL Server CE Server Tools feature to remove.

    Note At the same time that the Server Tools were installed, the SQL Server CE setup program also installed Microsoft Data Access Components (MDAC). The MDAC components are not uninstalled automatically because other programs may be dependent upon them. Remove the MDAC components only if you are certain they are not needed for other programs.

Support for Multi-Lingual Environments

The server tools include localized MDAC bits that can affect how setup dialogs and error messages are displayed. The language of the SQL Server CE setup package will determine the language of the MDAC bits in the server tools. If you have IIS servers configured for more than one UI language, you should download the corresponding languages of SQL Server CE onto separate development machines.

If you are deploying your application via CD, then you should put the different language variants of the server tools into separate subdirectories on your CD so that the correct one can be used for each IIS machine.

Deploying on a SQL Server 2000 System

To use replication with a SQL Server 2000 system, you must run the sp_MSmakegeneration.sql script as described in Updating SQL Server System Stored Procedures.

Deploying on an ActiveSync System

If you use ActiveSync with a Serial, IR, or USB connection to communicate between your Windows CE device and your desktop computer, you must install SQL Server CE Relay on the ActiveSync system. This will be required both during your application development and during your application deployment after it has been completed.

In preparation for deployment, when the SQL Server CE toolkit was installed on your development computer, the SQL Server CE Relay component that matches your SQL Server CE database engine were copied at the same time.

To install the SQL Server CE Relay component directly from your development computer to your ActiveSync system

  1. Navigate to the redist\Relay directory on your development computer.

  2. Create the \Program files\Microsoft SQL Server CE\Relay directory on the ActiveSync computer.

  3. Copy sscerelay.exe to the \Program files\Microsoft SQL Server CE\Relay directory on the ActiveSync computer.

  4. For instructions on configuring the SQL Server CE Relay component see Running SQL Server CE Relay.

To copy the SQL Server CE Relay component to a CD image

  1. Navigate to the redist directory on your development computer.

  2. Copy the relay directory to your CD image location.

  3. After the CD has been created and distributed, you can install the SQL Server CE Relay component onto the ActiveSync system.

To install SQL Server CE Relay

  1. Navigate to the relay directory on your CD.

  2. Create the \Program files\Microsoft SQL Server CE\Relay directory on the ActiveSync computer.

  3. Copy sscerelay.exe to the \Program files\Microsoft SQL Server CE\Relay directory on the ActiveSync computer.

  4. For instructions on configuring the SQL Server CE Relay component see Running SQL Server CE Relay.

To uninstall the SQL Server CE Relay component from the ActiveSync computer

  1. Open an MS-DOS command window.

  2. Navigate to the \Program files\Microsoft SQL Server CE\Relay subdirectory on your ActiveSync machine

  3. In the command window, enter the command: sscerelay\unregister.

  4. Delete the sscerelay.exe file.
Deploying on a Windows CE Device

Installing your SQL Server CE application onto a Windows CE device can be done in a number of different ways, and the method that you choose depends upon how your application is to be used.

To install the Windows CE components directly from your development tools

If you will be using the application inside your own organization, and if you use the eMbedded Visual Basic development tools, the simplest method is to make use of the capabilities of the development tools to download your SQL Server CE application and all of the dependent components directly into a Windows CE device using an ActiveSync connection.

If you use the Microsoft eMbedded Visual C++® development tools, you will need to build an application image that can be copied manually to the Windows CE devices.

To copy the Windows CE components to a deployment CD image

If you are intending to sell the application, you may need to deploy it to your customers using a CD image, or some other similar media.

Before you can copy the SQL Server CE application components to a CD image, you will need to build an application image to copy.

The simplest application image is when you just separate out the files to copy into a device. Such an application image would always need to be copied manually into each Windows CE device, which could be important if you want to control who is using the SQL Server CE application.

An alternative method would be for you to wrap the files into an install package. This technique is useful if you prefer to put a setup image onto a location that Windows CE devices can get to using Microsoft Internet Explorer, so your customers can install and use the SQL Server CE application easily.

The installation process from the CD will depend on the application image that you build, and the location on the CD image to which you copy the files.

To include the Windows CE components in a Platform Builder image

Before you can deploy your application inside a custom Windows CE operating system, you will need to build an application image, which will be the same set of files needed for a manual installation of the image.

Next, you will need to instruct Platform Builder to include the SQL Server CE application in the Windows CE operating system image that you build. In most cases, you should include your application as part of the operating system startup process so it runs automatically whenever the device is on.

The new operating system, including the SQL Server CE application, should be downloaded into your custom devices in the same way that you download any other custom operating system.


Other Windows CE Deployment Issues

Pre-building a SQL Server CE Database

If you have a large quantity of data in your backend SQL Server database, it can be expensive to have every Windows CE device download all of the data using a replication synchronization process.

You can pre-build a SQL Server CE copy of the database, and download it into each device together with the application.

  1. Set up one Windows CE device with the application.

  2. Connect the application to the backend SQL Server database to create the SQL Server CE .sdf file on the device, and synchronize all of the data.

  3. Stop the application, and use ActiveSync to connect to the device. Use the ActiveSync Explorer function to copy the .sdf file from the Windows CE device to the development system, and store it with the rest of the application.

  4. Whenever the SQL Server CE application is copied, the .sdf file should be copied at the same time.

  5. The SQL Server CE database includes Move-Copy code that detects when a database has been moved to a new device and it automatically gets a new ID for the user. The first time that the .sdf file is used by your SQL Server CE application on a new device it will get a new ID, and will be updated with only the changes made in the backend SQL Server database after the copy was made.
Registering the SQL Server CE Application on the Device

DllRegister.exe registers the components on the device and warns you about optional components missing from the device.

  1. Select the appropriate version of DllRegister.exe based on the processor type of your device.

  2. Copy DllRegister.exe from your development system to your Windows CE device and run it.

  3. On Palm-size PCs or Pocket PCs, you can copy dllRegister.exe to the \Windows\Start menu folder and then run it from the Start menu on the device.

  4. You can find DllRegister.exe in the \Program Files\Microsoft SQL Server CE\Device\processor family\processor type folder.
Secure Connections from Windows CE devices

If you intend to use IIS encryption, you will need to make secure connections to the IIS server.

Windows CE maintains a database of trusted Certificate Authorities. When a secure connection is attempted, Windows CE extracts the root certificate from the certification chain and checks it against the Certificate Authority database.

If you issue an IIS server certificate using your own standalone Certificate Authority (CA), your root certificate will not be present in the Windows CE Certificate Authority database. As a result, Windows CE will not trust your IIS server certificate. If you install such a server certificate in IIS and attempt to use SSL encryption, SQL Server CE replication or RDA will fail with ERROR_INTERNET_INVALID_CA (12045).

If you want to use server certificates that you issue yourself, you must either certify your standalone Certificate Authority through one of the trusted certificate authorities or add the root certificate of your standalone certificate authority to the Windows CE Certificate Authority database.

To add the root certificate of your standalone certificate authority to the Windows CE Certificate Authority database

  1. Save the root certificate of the standalone certificate authority to a .cer file.

  2. Install the root certificate in the Windows CE Certificate Authority database on the Windows CE device.

For a full discussion of encryption and certificates see Configuring IIS Encryption

Upgrading from previous versions of SQL Server CE

SQL Server CE follows the upgrade strategy of the full SQL Server product. The server will work with previous client components, but not with newer client components.

When you are upgrading to a newer version you should always start from the server, and then gradually work outwards upgrading the components closer to the server before upgrading components further out. You should not upgrade client components until all other components closer to the server have already been upgraded.

For SQL Server CE, this means that you should not try to deploy newer client applications if you still have older server tools on your IIS machine. You must upgrade the server tools first. The new server tools will work with older clients, so this is still appropriate if you have a mixture of older and newer client applications.


Deploying from eMbedded Visual Basic

Using eMbedded Visual Basic to Install SQL Server CE

The eMbedded Visual Basic development environment automates many of the debugging processes that you need to use to develop a new application. Part of this process includes downloading prototype versions of the application into a Windows CE device where it can be run and debugged.

The development environment makes use of ActiveSync on the development computer to download the files into the Windows CE device.

The development environment can automatically monitor what executable files are included in the application, and what .dlls the application uses. During the download process, the development environment will download the latest version of all of these components together.

Using eMbedded Visual Basic Deployment During Application Development

If you are using eMbedded Visual Basic, you can take advantage of these capabilities during the development process:

  1. Start eMbedded Visual Basic, and then either create a new Windows CE project or open an existing project.

  2. On the Project menu, click References.

  3. In the References dialog box, select Microsoft CE SQL Server Control 1.0 and Microsoft CE ADO Control 3.1. If your application uses the ADO extensions for DDL, select Microsoft CE ADO Ext. 3.1 for DDL.

  4. Click OK, and then on the Project menu, click Properties.

  5. On the General tab, in the Update Component Frequency list, click Always.

  6. Select the Runtime Files and Project Components check boxes.

  7. On the Run menu, click Execute to invoke the eMbedded Visual Basic program. eMbedded Visual Basic downloads all SQL Server CE, ADO, OLE DB, and ADOX components you selected to your Windows CE device and registers them.

    Note In the event of installation problems, you can force eMbedded Visual Basic to re-download components by clicking Project, and then clicking Properties. Set the update components frequency to Always and select Project Components.

Your application components will be downloaded to the Windows CE device each time that you make modifications and re-build your application to re-test it.

DLLRegister.exe is not needed if you are using eMbedded Visual Basic to deploy your application. The tools handle all registration automatically.

Using eMbedded Visual Basic to Deploy Your Finished Application

After you have completed your application, you can use the download capability of the eMbedded Visual Basic tools to deploy the application to every Windows CE device.

This method of deployment is simple and will save you the trouble of creating any other setup mechanism, but it means that you must purchase a copy of the eMbedded Visual Basic tools and SQL Server CE for every computer that you want to use for installing your application onto Windows CE devices. Microsoft recommends this method only for smaller installations where it is not a problem to connect every Windows CE device to a development computer to initiate the setup.


Creating a Manual Install Image

To deploy an application that was developed using the eMbedded Visual C++ tools, you can emulate the action of the eMbedded Visual Basic tools.

First, identify the files that make up your application, as described below, and then use the file copy features of ActiveSync to copy the files manually into your Windows CE devices. You will need to copy the files to the Windows CE device each time that you make changes and rebuild your application before you can test it.

To install SQL Server CE applications manually

  1. Use the following tables to determine which files your application requires. Select the files appropriate for the processor type of your Windows CE device. Consult the documentation included with your device to determine its processor type.
    • Your application files. These .exe files are located under the project tree that you created. The Visual C tool create a separate subdirectory for each platform processor type that you ask it to build, for example; for MIPS processors it will create \projectname\MIPSRel for the release version, and \projectname\MIPSDbg for the debug version. The Visual Basic tool places your executable file directly into the project subdirectory.

    • SQL Server CE files. These files are located under \Program Files\Microsoft SQL Server CE\Device\processor family\processor type by default. Rsaenh.dll is located in \Program Files\Microsoft SQL Server CE\Encryption\Windows CE OS version\processor family\processor type by default.
      File | Requirement
      Ssce10.dll | Required. Must be registered.
      Ssceca10.dll | Required for RDA or replication. Must be registered.
      Ssceinet.dll and Sscesock.dll | Required on Windows CE version 2.11 for RDA or replication. No registration required.
      Sscecw10.dll and Rsaenh.dll | Required if your database is encrypted. Rsaenh.dll is located in the \Encryption folder. Sscecw10.dll must be registered.

    • ADO and OLE DB files. These files are located under \Windows CE Tools\dataaccess31\Windows CE OS version\processor type by default.
      File | Requirement
      Msdadc.dll and Msdaer.dll | Required. Must be registered.
      Msdaeren.dll | Required. Msdaeren.dll is the English version of the ADOCE error DLL and will work on devices of all languages. For localized ADOCE error messages, substitute the Msdaerxx.dll that corresponds to the language setting of your device.
      Adoce31.dll | Required for ADO. Must be registered.
      Adoceoledb31.dll | Required for ADO.
      Adoxce31.dll | Required for ADOX. Must be registered.

  2. Copy the files to the \Windows folder on your Windows CE device.

  3. Copy DllRegister.exe from your development system to your Windows CE device and run it. On Palm-size PCs or Pocket PCs, you can copy DllRegister.exe to the \Windows\Start menu folder and then run it from the Start menu on the device. You must select the appropriate version of DllRegister.exe based on the processor type of your device. You can find DllRegister.exe in the \Program Files\Microsoft SQL Server CE\Device\processor family\processor type folder. DllRegister.exe registers the components on the device and warns you about optional components missing from the device.

  4. The first time that you copy your SQL Server CE application to the device you may need to add the certificate to the Windows CE Certificate Authority database before secure connections can be made to IIS.

Using Manual Copying to Deploy Your Finished Application

The set of files that you need to copy to a Windows CE device for debugging your prototype application is exactly the same set of files that you will need to copy to every Windows CE device when you deploy your application; the registration operations are also the same.

The easiest way to deploy your files onto multiple Windows CE devices is to copy them into their own setup directory. This reduces the risk of you selecting an incomplete set of files for ActiveSync to copy to the Windows CE device.

You can use this same technique to deploy an application that is developed using the eMbedded Visual Basic tools if you also want to deploy the application from computers that do not have the development tools installed.

This method of deployment requires you to have ActiveSync on every computer that you wish to use for installing your application onto Windows CE devices.

Microsoft recommends doing this where it is not a problem to connect every Windows CE device to a computer running ActiveSync to initiate the setup.


Creating a Setup Image for Windows CE

In some situations it is preferable to create a setup image containing your SQL Server CE application. Packaging your application into a setup image provides the following benefits:

  1. All of application files are present.

  2. You can prevent a partial installation.

  3. You can install your application more flexibly, such as from a desktop computer or from a Web site using Internet Explorer from the Windows CE device.

The Windows CE operating system uses a Windows CE .cab file to install an application on a Windows CE-based device. A .cab file is composed of multiple files that have been packaged into one file.

Use the CAB Wizard application (Cabwiz.exe) to generate a .cab file for your application.

To create a device-specific .cab file for an application

  1. Create an .inf file with Windows CE-specific modifications.

  2. Optionally, create a Setup.dll file to provide custom control of the installation process.

  3. Use the CAB Wizard to create the .cab file, using the platform information stored in the .inf files.


Creating an .inf File for the CAB Wizard

An .inf file specifies information about an application for the CAB Wizard. Windows CE uses the Microsoft Win32® Setup .inf file format with Windows CE-specific modifications. The following table shows the sections of an .inf file.

Section | Required | Describes
Version | Yes | The creator and version of the application
CEStrings | Yes | String substitutions for application and directory names
Strings | No | String definitions for one or more strings
CEDevice | Yes | The device platform for which the application is targeted
DefaultInstall | Yes | The default installation of the application
SourceDisksNames | Yes | The name and path of the disk on which the application resides
SourceDisksFiles | Yes | The name and path of the files in which the application resides
DestinationDirs | Yes | The names and paths of the destination directories for the application on the target device
CopyFiles | Yes | Default files to copy to the target device
AddReg | Yes | Keys and values that the .cab file will add to the registry on the device
CEShortCuts | No | Shortcuts that the installation application creates on the device

CAB Wizard can create multiple .cab files by using a single .inf file and multiple application binaries. This feature allows you to create separate .cab files for each specific processor or platform type. To indicate information for a specific processor or platform, append a unique label that indicates the platform to the following section names:

  1. CEDevice

  2. DefaultInstall

  3. SourceDisksNames

  4. SourceDisksFiles

For example, to specify the name and path of the disk on which the application resides when you install the application on a platform that uses the SH4 processor, use the SourceDisksNames.SH4 section name.

Use the /cpu option when you run CAB wizard, followed by a set of platform labels, to generate .cab files for multiple platforms.


.inf Grammar Reference for the CAB Wizard

This section defines the grammar that you can use for each individual .inf file entry when you are creating the .inf file that describes your application for the CAB Wizard.


Version

The [Version] section is required and specifies the creator of the file and other relevant information.

   [Version]
   Signature = "signature_name"
   Provider = "INF_creator"
   CESignature = "$Windows CE$"

signature_name

Must be "$Windows NT$" or "$Windows 95$".

INF_creator

The name of the company that is making the application.

The following code example shows a typical [Version] section.

   [Version]
   Signature = "$Windows NT$"
   Provider = "Microsoft"
   CESignature = "$Windows CE$"


CEStrings

The [CEStrings] section is required and specifies string substitutions for the application name and the default installation directory.

   [CEStrings]
   AppName = app_name
   InstallDir = default_install_dir

app_name

The name of the application. Other instances of %AppName% in the .inf file will be replaced with this string value.

Default_install_dir

Default installation directory on the device. Other instances of %InstallDir% in the .inf file will be replaced with this string value.

The following code example shows a typical [CEStrings] section.

   [CEStrings]
   AppName="Game Pack"
   InstallDir=%CE1%\%AppName%


Strings

The [Strings] section is optional and defines one or more string keys. A string key represents a string of printable characters.

   [Strings]
   string_key = value
   [string_key = value]

value

String consisting of letters, digits, or other printable characters. Enclose value in double quotation marks ("" "") if the corresponding string key is used in an item that requires double quotation marks.

The following code example shows a typical [Strings] section.

   [Strings]
   reg_path = Software\Microsoft\My Test App


CEDevice

The [CEDevice] section is optional and describes the platform for which your application is targeted. All keys in this section are optional. If a key is nonexistent, Windows CE does not perform the checks specified for that particular key. Windows CE also does not perform any checking if a key has no data. The exception is UnsupportedPlatforms; if this key exists but there is no data, the previous value is not overridden.

   [CEDevice]
   [ProcessorType =[processor_type]]
   [UnsupportedPlatforms = platform_family_name[,platform_family_name]]
   [VersionMin = [major_version.minor_version]]
   [VersionMax = [major_version.minor_version]]

processor_type

Value that is returned by SYSTEMINFO.dwProcessorType. For example, the value for the SH3 CPU is 10003 and the MIPS CPU is 4000.

platform_family_name

A list of platform family names that are known to be unsupported.

If the platform_family_name specified in the [CEDevice.xxx] section is different from that in the [CEDevice] section, both platform_family_name values are unsupported for the microprocessor that is specified by xxx. That is, the list of specific unsupported platform family names is appended to the previous list of unsupported platform family names. Application Manager will not display the application for an unsupported platform. Also, a user will be warned during the setup process if the .cab file is copied to an unsupported device. For example:

   [CEDevice]
   UnsupportedPlatforms = pltfrm1      ; pltfrm1 is unsupported
   [CEDevice.SH3]
   UnsupportedPlatforms =              ; pltfrm1 is still unsupported

major_version and minor_version

Numeric value that is returned by OSVERSIONINFO.dwVersionMinor and OSVERSIONINFO.dwVersionMajor. The .cab file is valid for the currently connected device if the version of the currently connected device is less than or equal to VersionMax and also greater than or equal to VersionMin.

For Windows CE Japanese-language 2.0 devices, set VersionMin and VersionMax to 2.01.

If you are using ActiveSync 3.0 or greater, use the VersionMin and VersionMax keys to distinguish between black/white and color displays on a Palm-size PC. The following table describes how to declare VersionMin and VersionMax to distinguish between the different displays.

VersionMin value | VersionMax value | Palm-size PC version | Display
2.1 | 2.1 | 1.0 | Black and white
2.11 | 2.11 | 2.0 | Color
3.0 | >3.0 | 3.0 | Version 3.0 color

The following sample shows how to use one .inf file to distinguish between different Palm-size PC hardware capabilities.

   [CEDevice.PPC_1]; black&white Palm-size PC 1.0
   VersionMin = 2.1
   VersionMax = 2.1
   UnsupportedPlatforms = "HPC","HPC Pro"

   [CEDevice.PPC_2]; color Palm-size PC 2.0
   VersionMin = 2.11
   VersionMax = 2.11
   UnsupportedPlatforms = "HPC","HPC Pro"

   [CEDevice.PPC_3]; color Palm-size PC 3.0 and above
   VersionMin = 3.0
   VersionMax = 1000.0; an arbitrary high value
   UnsupportedPlatforms = "HPC","HPC Pro"

The following code example shows three [CEDevice] sections: one that gives basic information for any CPU and two that are specific to the SH3 and the MIPS microprocessors.

   [CEDevice]                           ; A "template" for all platforms
   UnsupportedPlatforms = pltfrm1       ; Does not support pltfrm1
   ; The following specifies version 2.0 devices only.
   VersionMin = 2.0
   VersionMax = 2.0

   [CEDevice.SH3]                  ; Inherits all [CEDevice] settings
   ; This will create a .cab file specific to SH3 devices.
   ProcessorType = 10003           ; The SH3 .cab file is only valid
                                   ; for the SH3 microprocessors.
   UnsupportedPlatforms =          ; pltfrm1 is still unsupported.
   ; The following overrides the version settings so no version
   ; checking is performed.
   VersionMin =
   VersionMax =

   [CEDevice.MIPS]                  ; Inherits all [CEDevice] settings
   ; This will create a .cab file specific to "MIPS" devices.
   ProcessorType = 4000             ; The MIPS .cab file is only valid
                                    ; for the MIPS microprocessor.
   UnsupportedPlatforms =pltfrm2    ; pltfrm1 and pltfrm2 are not
                                    ; supported for the "MIPs" .cab file.

Note To create the two CPU-specific .cab files for the setup .inf file in the previous example, you must run the CAB Wizard with the /cpu sh3 mips parameter.


DefaultInstall

The [DefaultInstall] section is required and describes the default installation of your application.

   [DefaultInstall]
   Copyfiles=copyfile_list_section[,copyfile_list_section]
   AddReg=add_registry_section[,add_registry_section]
   [CEShortcuts=shortcut_list_section[,shortcut_list_section]]
   [CESetupDLL=setup_DLL]
   [CESelfRegister=self_reg_DLL_filename[,self_reg_DLL_filename]

shortcut_list_section

String that identifies one more section that defines shortcuts to a file, as defined in the [CEShortcuts] section.

setup_DLL

Optional string that specifies a Setup.dll. It contains customized functions for operations during installation and removal of the application. The file must be specified in the [SourceDisksFiles] section.

self_reg_DLL_filename

String that identifies files that self-register by exporting the DllRegisterServer and DllUnregisterServer Component Object Model (COM) functions. You must specify the files in the [SourceDisksFiles] section.

During installation, if installation on the device fails to call the exported DllRegisterServer function of the file, the exported DllUnregisterServer function of the file will not be called during removal.

The following code example shows a typical [DefaultInstall] section.

   [DefaultInstall]
   CopyFiles = CopyToInstallDir,CopyToWindows
   AddReg = RegSettings
   CEShortcuts = Shortcuts


SourceDiskNames

The [SourceDisksNames] section is required and describes the name and path of the disk on which your application resides.

   [SourceDisksNames]
   disk_id= ,comment,,path
   [disk_id= ,comment,,path]

The following code example shows a typical [SourceDisksNames] section.

   [SourceDisksNames]                   ; Required section
   1 = ,"Common files",,C:\app\common   ; Using an absolute path

   [SourceDisksNames.SH3]
   2 = ,"SH3 files",,sh3                ; Using a relative path

   [SourceDisksNames.MIPS]
   2 = ,"MIPS files",,mips              ; Using a relative path


SourceDiskFiles

The [SourceDisksFiles] section is required and describes the name and path of the files in which your application resides.

   [SourceDisksFiles]
   filename=disk_id[,subdir]
   [filename=disk_id[,subdir]]

The following code example shows a typical [SourceDisksFiles] section.

   [SourceDisksFiles]         ; Required section
   begin.wav = 1
   end.wav = 1
   sample.hlp = 1

   [SourceDisksFiles.SH3]
   sample.exe = 2             ; Uses the SourceDisksNames.SH3
                              ; identification of 2.

   [SourceDisksFiles.MIPS]
   sample.exe = 2             ; Uses the SourceDisksNames.MIPS
                              ; identification of 2.


DestinationDirs

The [DestinationDirs] section is required and describes the names and paths of the destination directories for your application on the target device.

   [DestinationDirs]
   file_list_section = 0,subdir
   [file_list_section = 0,subdir]
   [DefaultDestDir=0,subdir]

Note Windows CE does not support Win32 INF directory identifiers. For more information, see Windows CE Directory Identifiers <instapps_24.htm>.

subdir

String that identifies the destination directory. Subdir can be an absolute device path, the %InstallDir% string substitution, or a %Cex% directory identifier.

The following code example shows a typical [DestinationDirs] section.

   [DestinationDirs]
   Files.Common   = 0,%CE1%\My Subdir   ;\Program Files\My Subdir
   Files.Shared   = 0,%CE2%             ;\Windows


CopyFiles

The Copyfiles key, under the [DefaultInstall] section, is required and describes the default files to copy to the target device.

   [copyfile_list_section]
   destination_filename,[source_filename],[,flags]
   [destination_filename,[source_filename],[,flags]]

The source_filename parameter is optional if it is the same as destination_filename.

flags

Numeric value that specifies an action to be done while copying files. The following table shows the values that are supported by Windows CE.

Flag | Value | Description
COPYFLG_WARN_IF_SKIP | 0x00000001 | Warn a user if an attempt is made to skip a file after an error has occurred.
COPYFLG_NOSKIP | 0x00000002 | Do not allow a user to skip copying a file.
COPYFLG_NO_OVERWRITE | 0x00000010 | Do not overwrite an existing file in the destination directory.
COPYFLG_REPLACEONLY | 0x00000400 | Copy the source file to the destination directory only if the file is already in the destination directory.
CE_COPYFLG_NO_DATE_DIALOG | 0x20000000 | Do not copy files if the target file is newer.
CE_COPYFLG_NODATECHECK | 0x40000000 | Ignore date while overwriting the target file.
CE_COPYFLG_SHARED | 0x80000000 | Create a reference when a shared DLL is counted.

The following example is a typical CopyFiles section.

   [DefaultInstall]
   CopyFiles = CopyFilesSection

   [CopyFilesSection]
   "Sample Help.htm",Help.htm,,0x00000001; rename, and warn if skipped
   "Win Game.wav",WinGame.wav,,0x80000000; rename, and mark as shared


AddReg

The AddReg key, under the [DefaultInstall] section, is required and describes the keys and values that the .cab file adds to the device registry.

   [add_registry_section]
   registry_root_string , subkey,[value_name], flags, value[,value]
   [registry_root_string, subkey,[value_name], flags, value[,value]]

registry_root_strings

String that specifies the registry root location. The following table shows the values that are supported by Windows CE.

Root string | Description
HKCR | The same as HKEY_CLASSES_ROOT
HKCU | The same as HKEY_CURRENT_USER
HKLM | The same as HKEY_LOCAL_MACHINE

value_name

Registry value name. If empty, the "(default)" registry value name is used.

flags

Numeric value that specifies information about the registry key. The following table shows the values that are supported by Window CE.

Flag | Value | Description
FLG_ADDREG_NOCLOBBER | 0x00000002 | If the registry key exists, do not overwrite it. This flag can be used in combination with any of the other flags in this table.
FLG_ADDREG_TYPE_SZ | 0x00000000 | The REG_SZ registry data type.
FLG_ADDREG_TYPE_MULTI_SZ | 0x00010000 | The REG_MULTI_SZ registry data type. The value field that follows can be a list of strings separated by commas.
FLG_ADDREG_TYPE_BINARY | 0x00000001 | The REG_BINARY registry data type. The value field that follows must be a list of numeric values separated by commas, one byte per field, and must not use the 0x hexadecimal prefix.
FLG_ADDREG_TYPE_DWORD | 0x00010001 | The REG_DWORD data type. Only the non-compatible format in the Win32 Setup .inf documentation is supported.

The following code example shows a typical AddReg section.

   [DefaultInstall]
   AddReg = RegSettings
   [Strings]
   reg_path = Software\Company\AppName

   [RegSettings]
   HKLM,%reg_path%,,0x00000000,alpha        ; <default> = "alpha"
   HKLM,%reg_path%,test,0x00010001,3        ; Test = 3
   HKLM,%reg_path%\new,another,0x00010001,6; New\another = 6


CEShortcuts

The CEShortcuts key, a Windows CE-specific key under the [DefaultInstall] section, is optional and describes the shortcuts that the installation application creates on the device.

   [shortcut_list_section]
shortcut_filename,shortcut_type_flag,target_file/path[,standard_destination_path]
[shortcut_filename,shortcut_type_flag,target_file/path[,standard_destination_path]]

shortcut_filename

String that identifies the shortcut name. It does not require the .lnk extension.

shortcut_type_flag

Numeric value. Zero or empty represents a shortcut to a file; any nonzero numeric value represents a shortcut to a folder.

target_file/path

String value that specifies the destination file or folder. For a file, use the target file name—-for example, MyApp.exe—that must be defined in a file copy list. For a path, use a file_list_section name defined in the [DestinationDirs] section—for example, DefaultDestDir—or the %InstallDir% string.

standard_destination_path

Optional string value; a standard %CEx% path or %InstallDir%. If no value is specified, the shortcut_list_section name of the current section or the DefaultDestDir value from the [DestinationDirs] section is used.

The following code example shows a typical [CEShortcuts] section.

   [DefaultInstall]
   CEShortcuts = Shortcuts

   [Shortcuts]
   Sample App,0,sample.exe              ; Uses the DestinationDirs path.
   Sample App,0,sample.exe,%InstallDir% ; The path is specified.

The following code example shows how to create a shortcut to a Help file named AppHelp.htm.

   [DefaultInstall]
   CEShortcuts = Shortcuts

   [DestinationDirs]
   Shortcuts = 0,%CE2%\Help; \Windows\Help is not localized for Pocket PCs

   [Shortcuts]
   App Help Link,0,AppHelp.htm; uses the path in DestinationDirs


Sample .inf File for the CAB Wizard

The following code example shows a typical .inf file.

   [Version]                  ; Required section
   Signature = "$Windows NT$"
   Provider = "Microsoft"
   CESignature = "$Windows CE$"

   [CEDevice.SH3]
   ProcessorType = 10003      ; SH3 microprocessor

   [CEDevice.MIPS]
   ProcessorType = 4000       ; MIPS microprocessor

   [DefaultInstall]           ; Required section
   AddReg = RegSettings.All
   CEShortcuts = Shortcuts.All

   [DefaultInstall.SH3]
   CopyFiles = Files.Common, Files.SH3

   [DefaultInstall.MIPS]
   CopyFiles = Files.Common, Files.MIPS

   [SourceDisksNames]                   ; Required section
   1 = ,"Common files",,C:\app\common   ; Using an absolute path

   [SourceDisksNames.SH3]
   2 = ,"SH3 files",,sh3      ; Using a relative path

   [SourceDisksNames.MIPS]
   2 = ,"MIPS files",,mips    ; Using a relative path

   [SourceDisksFiles]         ; Required section
   begin.wav = 1
   end.wav = 1
   sample.htm = 1

   [SourceDisksFiles.SH3]
   sample.exe = 2             ; Uses the SourceDisksNames.SH3
                              ; identification of 2.

   [SourceDisksFiles.MIPS]
   sample.exe = 2             ; Uses the SourceDisksNames.MIPS
                              ; identification of 2.

   [DestinationDirs]             ; Required section
   Shortcuts.All = 0,%CE2%\Help  ; set to \Windows\Help
   Files.Common = 0,%CE2%        ; \Windows
   Files.SH3 = 0,%InstallDir%
   Files.MIPS = 0,%InstallDir%
   DefaultDestDir = 0,%InstallDir%

   [CEStrings]                ; Required section
   AppName = My Test App
   InstallDir = %CE1%\%AppName%

   [Strings]                  ; Optional section
   reg_path = Software\Microsoft\My Test App

   [Shortcuts.All]
   Sample App,0,sample.exe, %CE17%      ; The path to the Start menu is
                                        ; explicitly specified.
   Sample App,0,sample.exe,%InstallDir% ; The path to the installation
                                        ; directory is specified.
   Sample Help,0,sample.htm             ; Uses the path specified in
                                        ; DestinationDirs, set to the Help
                                        ; directory.

   [Files.Common]
   begin.wav,,,0
   end.wav,,,0
   sample.htm,,,0

   [Files.SH3]
   sample.exe,,,0

   [Files.MIPS]
   sample.exe,,,0

   [RegSettings.All]
   HKLM,%reg_path%,,0x00000000,alpha    ; <default> = "alpha"
   HKLM,%reg_path%,test,0x00010001,3    ; test = 3
   HKLM,%reg_path%\new,another,0x00010001,6; new\another = 6


Install Functions in a Windows CE Setup.dll

Setup.dll is an optional file that you can create for your Windows CE application to enable your setup to perform custom operations during the installation and/or removal of your application on the Windows CE device. The following table shows the functions that should be exported by your Setup.dll.

Function | Description
Install_Init | Called before installation begins. Use this function to check the application version when reinstalling an application and to determine if a dependent application is present.
Install_Exit | Called after installation is complete. Use this function to handle errors that occur during application installation.
Uninstall_Init | Called before the removal process begins. Use this function to close the application, if the application is running.
Uninstall_Exit | Called after the removal process is complete. Use this function to save database information to a file and delete the database and to tell the user where the user data files are stored and how to reinstall the application.

If you need functions like these as part of your setup procedure, then the simplest way to get them is to build a Setup.dll in the standard Windows CE format because the .inf file process already has a built in mechanism to use a Setup.dll.

The Ce_setup.h header file defines the function prototypes and the return values that you should use for each function in your dll.

Note Use the CeSetupDLL key in the [DefaultInstall] section in the .inf file to point to your Setup.dll after it has been created:

   [DefaultInstall]
   [CESetupDLL=MySetup.DLL]


Using the CAB Wizard to create a .cab File

After you create the .inf file and the optional Setup.dll file, use the CAB Wizard to create the .cab file. The command-line syntax for the CAB Wizard is as follows:

   cabwiz.exe "inf_file" [/dest dest_directory] [/err error_file]
   [/cpu platform_label [platform_label]]

inf_file

Full path and filename to the CabWiz Setup .inf file.

dest_directory

Destination directory for the .cab files. If no directory is specified, the .cab files are created in the inf_file directory.

error_file

File name for a log file that contains all warnings and errors that are encountered when the .cab files are compiled. If no file name is specified, errors are displayed in message boxes. If a file name is used, the CAB Wizard runs without the user interface (UI); this is useful for automated builds.

platform_label

Creates a .cab file for each platform label that you specify. A platform label is a label that is used in the Win32 setup .inf file to differentiate between different platform and processor types. The /cpu parameter, followed by multiple platform_label values, must be the last qualifier in the command line.

The following example creates .cab files for the SH3 and MIPS microprocessors, assuming that the Win32 setup .inf file contains the SH3 and MIPS platform labels:

   cabwiz.exe  "c:\myfile.inf"  /err myfile.err  /cpu  sh3  mips

Note The following Windows CE files must be installed in the same directory on the desktop computer: Cabwiz.exe, Makecab.exe, and Cabwiz.ddf. Cabwiz.exe must be called with its full path in order to run correctly.


Troubleshooting the CAB Wizard

To identify and avoid problems that might occur when using the CAB Wizard, follow these guidelines:

  • Use %% for a percent sign (%) character when using this character in an .inf file string, as specified in the Win32 documentation. This will not work under the [Strings] section.

  • Do not use .inf or .cab files that were created for Windows CE to install applications on Windows-based desktop platforms.

  • Ensure that the Makecab.exe and Cabwiz.ddf files, included with Windows CE, are in the same directory as Cabwiz.exe.

  • Use the full path to call Cabwiz.exe.

  • Do not create a .cab file with the Makecab.exe file that is included with Windows CE. You must use Cabwiz.exe, which uses Makecab.exe to generate the .cab files for Windows CE.


Deploying SQL Server CE Applications with Platform Builder

SQL Server CE supports Platform Builder 3.0 and higher.

Platform Builder is used to create a custom Windows CE operating system if you are building a custom Windows CE device. You might be doing this if you need to build an embedded controller for a piece of equipment.

To include a SQL Server CE application into your new operating system you will need to:

  • Tell Platform Builder to include the SQL Server CE database engine files, and build an operating system to download to each device.

  • Use the Platform Builder SDK to export an SDK for your new operating system.

  • Register your new operating system with the Visual Tools.

  • If you are using eMbedded Visual Basic, then our Type Libraries will be automatically registered for you. If you are using eMbedded Visual C++, then you will need to configure the new SDK inside the tools so it can find the Header files and Library files for SQL Server CE.

  • Now you are ready to start building SQL Server CE applications for your device.

Incorporating Your Completed Application into Platform Builder

After you have completed your application, you should consider creating an updated version of your new operating system that also includes the application program file. If you intend to install the application on a large number of custom devices, having a unified setup may be simpler.

If you do combine everything into a single download, then you should consider if you want to include your application as part of the operating system startup process so it automatically runs whenever the device is on. To do this, put your application in the \Windows\Startup directory on the device.

Different version of Platform Builder may have different ways for you to add an additional application to the operating system image, so please refer to the documentation for your version of Platform Builder for instructions on how to do this.

After building your new operating system, including the SQL Server CE application, you will be able to download it into your custom devices in the same way that you download any other custom application. Please refer to the documentation for your version of Platform Builder for instructions on how to do this.

Registering Your New Platform Builder SDK with the eMbedded Tools

Platform Builder 3.0 includes the capability to create a new SDK that can be registered with the eMbedded visual tools. If you include SQL Server CE components in your new operating system, the Platform Builder SDK export registration process will automatic register those files with eMbedded Visual Basic, but if you are using eMbedded Visual C++ you need to take a few extra steps to expose the header and library files:

  1. After exporting your SDK, in the eMbedded Tools choose the Tools menu and click on Options. Select the Directories pane.

  2. Select the Include files group, and add a new entry for \Program Files\Microsoft SQL Server CE\inc

  3. Select the Library files group, and add a new entry for \Program Files\Microsoft SQL Server CE\lib

Different version of Platform Builder may export an SDK in different ways, so please refer to the documentation for your version of Platform Builder for instructions on how to include your application when building an operating system.


Sample Applications

This section describes two sample applications that ship with SQL Server CE: the RDA Sample Application and the Replication Sample Application. The sample applications are installed with the Development Tools Setup option in drive:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_RDA and drive:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_REPL.

These sample applications are based on the Northwind database that ships with Microsoft® SQL Server™ 7.0 and Microsoft® SQL Server™ 2000. Northwind database applications lend themselves to being used in a mobile environment. Existing SQL developers are familiar with the Northwind database schema and data.

These sample applications demonstrate a limited set of features and functionality since the objective is to simply highlight the two connectivity models (RDA and replication) and show some of the advanced storage engine features (referential integrity with cascading deletes, robust SQL DML support, cursoring capabilities, and other feature improvements over CEDB.

Usage

The two Northwind applications demonstrate the same functionality. One application is based on remote data access (RDA) and the other on SQL Server 2000 merge replication. The RDA application works without SQL Server being configured, whereas the replication application requires some SQL Server configuration (for example, creating a Distributor and publication).

The examples demonstrate the performance, administration, coding, functionality, and database size footprint differences between RDA and replication. They highlight the differences in coding techniques that deal with server administration (conflict resolution, ranged identity, and so forth) vs. client code administration (changing identity values and not dealing with conflict resolution).

The applications demo a scenario of a salesperson taking orders at customer locations and then, when connectivity is available, synchronizing those changes back to SQL Server. The application assumes that no new customers are being entered and only new orders are being entered. Thus, the only tables that receive new rows in the application are Orders and Orders Details.


Installing and Using the Remote Data Access Sample Application

This sample Microsoft® eMbedded Visual Basic® application helps you understand how SQL Server CE can be combined with SQL Server 7.0 or SQL Server 2000 and RDA to form a useful mobile "route sales" application. The sample application is installed with the Development Tools Setup option in drive:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_RDA.

The RDA sample application simulates a sales representative of the Northwind Trading Company using a Pocket PC to take orders from customers and push the new orders back to the SQL Server database. In a typical usage scenario, the sales representative would use RDA to pull customer and order information from a SQL Server 7.0 or SQL Server 2000 Northwind database to the Pocket PC. Customer and order data is stored on the Pocket PC in a SQL Server CE database. New order information can be entered and order history reviewed on the Pocket PC's copy of the Northwind database. When connectivity becomes available, data on the SQL Server CE database can be pushed to the SQL Server database by using the RDA Object. Since RDA uses HTTP as the transport protocol, connectivity can take the form of a network connection between the Pocket PC and SQL Server through Microsoft® Internet Information Services (IIS).

The code for the application is commented, so you can easily and freely extrapolate it for your own use. The sample application is intentionally incomplete to illustrate issues incumbent on SQL Server CE setup and development.

Important SQL Server CE databases are not case-sensitive. You cannot use this sample application with a case-sensitive SQL Server database.


Setup Instructions

Before you can run and examine the code for this SQL Server CE RDA Sample Application, you will need a number of components and tools. Following the installation and configuration of this list of items, you can view the application on any brand of Pocket PC running the Microsoft Windows CE 3.0 operating system or by employing an emulator with Microsoft eMbedded Visual Basic. The Pocket PC emulator comes with the installation of the Pocket PC Software Development Kit (SDK), which is part of Microsoft® eMbedded Visual Tools 3.0.

Install or verify the installation of the following items on your development system:

  • Microsoft eMbedded Visual Basic 3.0, included with Microsoft eMbedded Visual Tools 3.0

  • Microsoft® Windows® Platform SDK for Pocket PC (Pocket PC SDK), included with Microsoft eMbedded Visual Tools 3.0

  • Microsoft SQL Server 7.0 or Microsoft SQL Server 2000

  • Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE)

  • Microsoft Internet Information Services (IIS) 4.0 or higher

  • Configuration of SQL Server CE Server Agent ISAPI DLL (Sscesa10.dll) after IIS is installed

This sample application should not be connected to or used with your production SQL Server database without the permission of the system administrator. In fact, system administrator privileges are required for parts of this installation. The simplest back-end server configuration is to run SQL Server and IIS on the same computer.


Setup Tips for eMbedded Visual Tools

Follow the directions in Running Setup under Installing SQL Server CE to install eMbedded Visual Tools 3.0, the Pocket PC SDK, and then SQL Server CE. The Pocket PC emulator for eMbedded Visual Basic is included with the Pocket PC SDK. The emulator simulates screens and behavior of a Pocket PC.

During the setup of Microsoft eMbedded Visual Tools 3.0, select the eMbedded Visual Tools 3.0 and Microsoft Windows Platform SDK for Pocket PC options.


Setup Tips for Microsoft SQL Server CE

During the setup of SQL Server CE, you will be prompted to select Development Tools, Server Tools, or both. Select both options.

Microsoft® CE Data Access 3.1 (ADOCE) is installed with Development Tools.

Installing Server Tools makes the Server Agent ISAPI DLL, Sscesa10.dll, and MDAC 2.6 available for connectivity.


Setup Tips for IIS and the Server Agent (Sscesa10.dll)

Connectivity using RDA requires IIS to be set up properly, creation of a virtual directory, and the Server Agent (Sscesa10.dll) to be configured properly before data can be pulled from a SQL Server database to the SQL Server CE database. Preparing IIS for RDA requires these steps:

  1. Create a folder anywhere on your system to contain the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll. For this example, create a folder named C:\NwindRDA.

  2. Copy Sscesa10.dll from its default installation directory, \Program Files\Microsoft SQL Server CE\Server\Sscesa10.dll, to the folder you created in Step 1.

  3. Register the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll, by using regsvr32.

  4. Create an IIS virtual directory in the default Web site pointing to the directory you created in Step 1.

See Configuring the Server Agent ISAPI DLL for detailed configuration instructions on Windows NT 4.0 and Windows 2000.

Register the SQL Server CE Server Agent ISAPI DLL
  1. On your IIS system, click Start and then Run.

  2. Type regsvr32 followed by the path to Sscesa10.dll.

  3. Click OK to register Sscesa10.dll in the new location on your IIS system. You will see a success message.

    Note The default installation directory for Sscesa10.dll is C:\Program Files\Microsoft SQL Server CE\Server, although this directory does not initially contain the required read and write permissions on an NTFS system needed to execute RDA. See Configuring IIS Authorization for security instructions for NTFS systems.

Create an IIS Virtual Directory

The final step in setting up IIS is to set up a virtual directory under the default Web site on IIS to the directory containing the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll. Creating virtual directories can make your application more secure. If your IIS server is running on Microsoft® Windows® 2000 Professional or Microsoft® Windows® 2000 Server, use the following steps to create a virtual directory. If your IIS server is running on Microsoft® Windows NT® 4.0, see Configuring the Server Agent ISAPI DLL on Windows NT 4.0.

To set up a virtual directory on Windows 2000 Professional or Windows 2000 Server:

  1. Start the Internet Information Services snap-in by clicking Start, Settings, and then Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager. If Internet Services Manager is not present in Administrative Tools, you must install IIS as described in Configuring the Server Agent ISAPI DLL on Windows 2000.

  2. In the left pane, expand the computer containing your site. Right-click the Default Web site and select New, and then Virtual Directory to start the Virtual Directory Creation Wizard.

  3. In the Welcome to the Virtual Directory Creation Wizard, click Next.

  4. On the Virtual Directory Alias sheet, enter the name you want to assign to your virtual directory, for example, Nwind. Click Next.

  5. On the Web Site Content Directory sheet, enter the full path for the directory you copied and registered your Sscesa10.dll in Step 1 of Setup Tips for IIS and the Server Agent (Sscesa10.dll), for example, C:\NwindRDA. Click Next.

  6. On the Access Permissions sheet, enter the access permissions for the virtual directory. It is recommended that you be as restrictive as possible to make your Web site more secure. You must select Execute permissions. This permits Sscesa10.dll to run. You can disable Read, Run scripts, Write, and Browse permissions. Click Next.

  7. Click Finish to complete the Virtual Directory Creation Wizard.

You are finished with setup and ready to download and run the sample application.


Using the RDA Sample Application

You can run the RDA Sample Application by using the emulator or directly on a Pocket PC if it is connected to your development system.

Using the Emulator

The RDA Sample Application is installed by default in C:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_RDA. To run the sample application, in eMbedded Visual Basic, double-click the project file named NWindRDA.ebp.

Notice that Pocket PC Emulation has been chosen as the run modality for this sample by default. Begin the sample application by clicking Start Debugger on the Run menu. After a few moments, you will see a Pocket PC emulator screen.

Using the Pocket PC

If you have an Ethernet connection between your Pocket PC and your development system, setup and functionality is nearly identical to using the emulator. Simply select Pocket PC (Default Device) rather than Pocket PC Emulation in the drop-down list in the toolbar in eMbedded Visual Basic and run the Project file.

Initializing the Application

To initialize the application for your system:

  1. Enter the name of your SQL Server (typically the name of the machine) in the SQLServer box.

  2. Enter the sa password to your SQL Server, or change the User ID and supply the appropriate password.

    Note The sample application defaults to SQL Server Authentication. It is recommended that you first get this configuration working and then try Integrated Windows Authentication. See Implementing RDA to understand alternate security modes. You must delete the NorthwindRDA.sdf database file created to change the login information.

  3. Enter the path to the virtual directory you created earlier in the Internet URL box. Use the following syntax:

    http://yourserver/yourvirtualalias/sscesa10.dll

    yourserver is the name of the IIS server on which you created a virtual directory. This should be the same name as your SQL Server computer if you are following sample recommendations. yourvirtualalias is the alias of the virtual directory you created earlier (Nwind). For example, except for the server name, the following should be correct:

    http://yourserver/Nwind/sscesa10.dll

    After you have finished entering values into the SQLServer and Internet URL boxes, click the Initialize button. You will see a screen like the one shown in the following figure. If you receive an error or the processing continues for more than about a minute, see the "Resetting the Application" topic later in this section to learn how to enter text again.

Notice that the Initialize button now reads Synchronize and the Employee Info list now contains names from the Northwind Traders sample database. This is a good time to examine some of the other changes that have occurred on your system.

Successfully initializing the application created a SQL Server CE database named NorthwindRDA.sdf in the following location:

C:\Windows CE Tools\Wce300\MS Pocket PC\Emulation\Palm300

This location simulates the root directory of a Pocket PC. If you open the Northwind sample database in Enterprise Manager on your SQL Server, you will see that the SQLCERangedIdentity table has been created. SQLCERangedIdentity is used to track individual identity ranges for the OrderID column in the Order table for each Pocket PC. While you have Northwind open, make a note of the last OrderID number in the Orders table. You can enter new order information in the Pocket PC emulation and synchronize this new order data with SQL Server.

Adding a New Order

To begin adding a new order into the RDA Sample Application, identify which employee of the Northwind Trading Company you want to mimic. Select a name in the Employee Info list and click OK. As shown in the preceding figure, Steven Buchanan was selected. A screen similar to the one shown in the following figure is displayed. The first customer in the list is displayed by default in the Bill To box.

You now have access to all customers in the Northwind sample database. The emulator is demonstrating data held in tables in the NorthwindRDA.sdf database file on a Pocket PC. Tables created on the NorthwindRDA.sdf database include:

  • Employees

  • Orders

  • OrderDetails

  • Customers

  • Shippers

  • Products

To begin an order, select the customer you want to work with from the Bill To list and then click the Order tab. You will see a new order page like the one shown in the following figure. In this example, the customer Around the Horn is selected.

Add items to the order by selecting product names from the Product list. Enter a quantity for each item by using the keypad provided. Scroll right to see the extended price. Click the New Item button to drop down a row. When you have built a satisfactory order, take note of the number in the Order ID box. This will be the order number pushed back to SQL sever when you have a connection available. Since you are using emulation, as long as your development system has a network connection to the IIS/SQL Server computer, you always have a connection. Store the order in the local SQL Server CE database (NorthwindRDA.sdf) by clicking the Enter Order button.

To see this customer's order history, click the Review tab.

Click the Refresh button to view order detail information. Scroll to the bottom of the Select Order for Detail section. Click on the order number you want to see details on.

Pushing Data Back to SQL Server

Because SQL Server CE uses HTTP as the transport protocol, you can push data back to SQL Server through a modem, a wireless LAN, or the local area network. To push the changed data from a SQL Server CE database back to SQL Server, select Sync with Host from the Sync menu at the bottom of the emulator screen. You may want to verify that data was transferred to SQL Server by opening the Orders table in the Northwind sample database in Enterprise Manager.

Resetting the Application

There are a number of reasons why you may want to reset the application, for example, to configure alternate security schemes. To reset the application, locate and delete the database file NorthwindRDA.sdf in C:\Windows CE Tools\Wce300\MS Pocket PC\Emulation\Palm300.


Installing and Using the Replication Sample Application

This sample eMbedded Visual Basic application helps you understand how SQL Server CE can be combined with Microsoft SQL Server 2000 and replication to form a useful mobile "route sales" application. The sample application is installed with the Development Tools Setup option in drive:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_REPL.

The Replication Sample Application simulates a sales representative of the Northwind Trading Company using a Pocket PC to take orders from customers and synchronizing the new orders back to the SQL Server database. To fully support both the Replication and RDA Sample Applications coexisting on the server while using ranged identity management for all identity columns, the Replication Sample Application uses a duplicated Northwind database called Nwind_SQLCE. This database is created when the Setuprepl.bat file is run on the server. Even though both applications use separate back-end databases, the application data is identical. In a typical usage scenario, the sales representative would use replication to synchronize customer and order information from SQL Server 2000 Nwind_SQLCE database to the Pocket PC. Customer and order data is stored on the Pocket PC in a SQL Server CE database. New order information can be entered and order history reviewed on the Pocket PC's copy of the Nwind_SQLCE database, called the Subscriber. When connectivity becomes available, data on the SQL Server CE database can be synchronized to the SQL Server database by using the Replication Object. Since replication uses HTTP as the transport protocol, connectivity can take the form of a network connection between the Pocket PC and SQL Server through IIS.

The code for the application is commented, so you can easily and freely extrapolate it for your own use. The sample application is intentionally incomplete to illustrate issues incumbent on SQL Server CE setup and development.

Important SQL Server CE databases are not case-sensitive. You cannot use this sample application with a case-sensitive SQL Server database.


Setup Instructions

Before you can run and examine the code behind this SQL Server CE Replication Sample Application, you will need a number of components and tools. Also, SQL Server must be configured to create and publish the Nwind_SQLCE database. Following the installation and configuration of this list of items, you can view the application on any brand of Pocket PC running the Microsoft Windows CE 3.0 operating system or by employing an emulator with eMbedded Visual Basic. The Pocket PC emulator comes with the installation of the Pocket PC Software Development Kit (SDK), which is part of eMbedded Visual Tools 3.0.

Install or verify the installation of the following items on your development system:

  • Microsoft eMbedded Visual Basic 3.0, included with Microsoft eMbedded Visual Tools 3.0

  • Microsoft Windows Platform SDK for Pocket PC (Pocket PC SDK), included with Microsoft eMbedded Visual Tools 3.0

  • Microsoft SQL Server 2000

  • Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE)

  • Microsoft Internet Information Services (IIS) 4.0 or higher

  • Configuration of SQL Server CE Server Agent ISAPI DLL (Sscesa10.dll) after IIS is installed

Configure the Microsoft SQL Server 2000 system:

  • Upgrade SQL Server system stored procedures by using the sp_MSmakegeneration.sql script.

  • Run the SetupRepl.bat file included with the sample application.

This sample application should not be connected to or used with your production SQL Server database without the permission of the system administrator. In fact, system administrator privileges are required for parts of this application installation. The simplest back-end server configuration is to run SQL Server and IIS on the same computer.


Setup Tips for eMbedded Visual Tools

Follow the directions in Running Setup under Installing SQL Server CE to install Microsoft eMbedded Visual Tools 3.0, the Pocket PC SDK, and then SQL Server CE. The Pocket PC emulator for eMbedded Visual Basic is included with the Pocket PC SDK. The emulator simulates screens and behavior of a Pocket PC.

During the setup of Microsoft eMbedded Visual Tools 3.0, select the eMbedded Visual Tools 3.0 and Microsoft Windows Platform SDK for Pocket PC options.


Setup Tips for Microsoft SQL Server CE

During the setup of SQL Server CE, you will be prompted to select Development Tools, Server Tools, or both. Select both options.

Microsoft® CE Data Access 3.1 (ADOCE) is installed with Development Tools.

Installing Server Tools makes the Server Agent ISAPI DLL, Sscesa10.dll, Sscerp10.dll, and MDAC 2.6 available for connectivity.


Setup Tips for IIS and the Server Agent (Sscesa10.dll)

Connectivity using replication requires IIS to be set up properly, creation of a virtual directory, and the Server Agent (Sscesa10.dll) to be configured properly before data can be pulled from a SQL Server database to the SQL Server CE database. Preparing IIS for replication requires these steps:

  1. Create a folder anywhere on your system to contain the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll. For this example, create a folder named C:\NwindRepl.

  2. Copy Sscesa10.dll from its default installation directory, \Program Files\Microsoft SQL Server CE\Server\Sscesa10.dll, to the folder you created in Step 1.

  3. Register the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll, by using regsvr32.

  4. Create an IIS virtual directory in the default Web site pointing to the directory you created in Step 1.

See Configuring the Server Agent ISAPI DLL for detailed configuration instructions on Windows NT 4.0 and Windows 2000.

Register the SQL Server CE Server Agent ISAPI DLL
  1. On your IIS system, click Start and then Run.

  2. Type regsvr32 followed by the path to Sscesa10.dll.

  3. Click OK to register Sscesa10.dll in the new location on your IIS system. You will see a success message.

    Note The default installation directory for Sscesa10.dll is C:\Program Files\Microsoft SQL Server CE\Server, although this directory does not initially contain the required read and write permissions on an NTFS system needed to execute replication.

See Configuring IIS Authorization for security instructions for NTFS systems.

Create an IIS Virtual Directory

The final step in setting up IIS is to set up a virtual directory under the default Web site on IIS to the directory containing the SQL Server CE Server Agent ISAPI DLL, Sscesa10.dll. Creating virtual directories can make your application more secure. If your IIS server is running on Microsoft Windows 2000 Professional or Microsoft Windows 2000 Server, use the following steps to create a virtual directory. If your IIS server is running on Microsoft Windows NT 4.0, see Configuring the Server Agent ISAPI DLL on Windows NT 4.0.

To set up a virtual directory on Windows 2000 Professional or Windows 2000 Server:

  1. Start the Internet Information Services snap-in by clicking Start, Settings, and then Control Panel. In Control Panel, double-click Administrative Tools. In Administrative Tools, double-click Internet Services Manager. If Internet Services Manager is not present in Administrative Tools, you must install IIS as described in Configuring the Server Agent ISAPI DLL on Windows 2000.

  2. In the left pane, expand the computer containing your site. Right-click the Default Web site and select New, and then Virtual Directory to start the Virtual Directory Creation Wizard.

  3. In the Welcome to the Virtual Directory Creation Wizard, click Next.

  4. On the Virtual Directory Alias sheet, enter the name you want to assign to your virtual directory, for example, Nwind. Click Next.

  5. On the Web Site Content Directory sheet, enter the full path for the directory you copied and registered your Sscesa10.dll in Step 1 of "Setup Tips for IIS and the Server Agent," for example, C:\NwindRepl. Click Next.

  6. On the Access Permissions sheet, enter the access permissions for the virtual directory. It is recommended that you be as restrictive as possible to make your Web site more secure. You must select Execute permissions. This permits Sscesa10.dll to run. You can disable Read, Run scripts, Write, and Browse permissions. Click Next.

  7. Click Finish to complete the Virtual Directory Creation Wizard.

You are finished with setup and ready to download and run the sample application.


Required SQL Server 2000 Configuration

Once IIS is properly configured, SQL Server 2000 can be enabled for replication. The Replication Sample Application uses a duplicated Northwind database called Nwind_SQLCE. Running the SetupRepl.bat file on your SQL Server system creates the Nwind_SQLCE database, enables SQL Server for replication, and creates a publication named SQLCEReplDemo. See Configuring SQL Server.

To configure the SQL Server 2000 system:

  1. Create a network shared directory on the SQL Server 2000 computer that will become the Publisher. This shared directory is where the replication snapshot files will be created and read by the SQL Server CE Subscriber.

  2. Make sure that all Subscribers (IIS user specified during synchronization) have read access to the shared directory. By default the virtual directory is configured with anonymous access; therefore, grant computername\IUSR_computername read access to the shared directory created in Step 1.

  3. To use replication with SQL Server 2000, you must upgrade system stored procedures in the master database by running sp_MSmakegeneration.sql. The upgrade only affects replication with SQL Server CE.

    Important Do not perform this step with future service pack releases.

    At the command prompt, use the osql utility to run sp_MSmakegeneration.sql. The sp_MSmakegeneration.sql file is installed with the Development Tools Setup option in \Program Files\Microsoft SQL Server CE\Inc. For example:

    C:> OSQL -Usa -P sa_password -S server_name -i location\sp_MSmakegeneration.sql

  4. Run SetupRepl.bat, located with the SQL Server CE files, drive:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_REPL, according to the following usage specifications:

    Usage: SetupRepl {required parms} {optional parms}

    Required Parameters:

    {snapshot share} - A share available for the storage of snapshot files.

    All Subscribers (IIS users) must be able to read from this share.

    Optional Parameters:

    {publisher} - Publisher name. Defaults to local computer.

    {publisher login} - Defaults to sa.

    {publisher password} - Defaults to NULL.

    Example: SetupRepl ReplSnapshot

    This example creates the publication SQLCEReplDemo on your local computer, configures it, and prepares the snapshot files so that you can begin using the %sqlrepl_demo_publisher_db% SQLCE application (assume that sa has a NULL password, if not supplied).

    This step will install a Publisher with a local Distributor, create a database called Nwind_SQLCE, and populate it with initial data that matches data in the Northwind database that ships with SQL Server. It also creates a merge publication named SQLCEReplDemo from the Nwind_SQLCE database.

    The Distributor is installed using the shared directory specified when the Setuprepl.bat file is run. This shared directory will be used as the replication working directory (snapshot folder). For example, if you call Setuprepl.bat and specify ReplSnapshot as the snapshot shared directory, the working directory for all snapshot files will be \\computername\ReplSnapshot.

  5. Grant the IIS user (NT_Authentication) or the SQL Server user (DB_Authentication) access to the Publication Access List. See Securing the Publication for detailed instructions.


Using the Replication Sample Application

You can run the Replication Sample Application by using the emulator or directly on a Pocket PC if it is connected to your development system.

Using the Emulator

The Replication Sample Application is installed by default in C:\Program Files\Microsoft SQL Server CE\Samples\eVB\Northwind_Repl. To run the sample application, in eMbedded Visual Basic, double-click the project file named NWindRepl.ebp.

Notice that Pocket PC Emulation has been chosen as the run modality for this sample by default. Begin the sample application by clicking Start Debugger on the Run menu. After a few moments, you will see a Pocket PC emulator screen.

Using the Pocket PC

If you have an Ethernet connection between your Pocket PC and your development system, setup and functionality is nearly identical to using the emulator. Simply select Pocket PC (Default Device) rather than Pocket PC Emulation in the drop-down list in the toolbar in eMbedded Visual Basic and run the Project file.

Initializing the Application

To initialize the application for your system:

  1. Enter the name of your SQL Server (typically the name of the machine) in the SQLServer box.

  2. Enter the sa password to your SQL Server, or change the User ID and supply the appropriate password.

    Note The sample application defaults to SQL Server Authentication. It is recommended that you first get this configuration working and then try Integrated Windows Authentication. See Implementing Replication to understand alternate security modes. You must delete the NorthwindRepl.sdf database file created to change the login information.

  3. Enter the path to the virtual directory you created earlier in the Internet URL box. Use the following syntax:

    http://yourserver/yourvirtualalias/sscesa10.dll

    yourserver is the name of the IIS server on which you created a virtual directory. This should be the same name as your SQL Server machine if you are following sample recommendations. yourvirtualalias is the alias of the virtual directory you created earlier (Nwind). For example, except for the server name, the following should be correct.

    http://yourserver/Nwind/sscesa10.dll

    After you have finished entering values into the SQLServer and Internet URL boxes, click the Initialize button. You will see a screen like the one shown in the following figure. If you receive an error or the processing continues for more than about a minute, see the "Resetting the Application" topic later in this section to learn how to enter text again.

Notice that the Initialize button now reads Synchronize and the Employee Info list now contains names from the Nwind_SQLCE (Northwind) Traders sample database. This is a good time to examine some of the other changes that have occurred on your system.

Successfully initializing the application created a SQL Server CE database named NorthwindRepl.sdf in the following location:

C:\Windows CE Tools\Wce300\MS Pocket PC\Emulation\Palm300

This location simulates the root directory of a Pocket PC. The SQLCEReplDemo publication is configured to automatically manage all identity ranges; therefore, this management is used to track individual identity ranges for the OrderID column in the Order table for each Pocket PC. While you have Nwind_SQLCE open, make a note of the last OrderID number in the Orders table. You can enter new order information in the Pocket PC emulation and synchronize this new order data back to SQL Server.

Adding a New Order

To begin adding a new order into the Replication Sample Application, identify which employee of the Northwind Trading Company you want to mimic. Select a name in the Employee Info list and click OK. As shown in the preceding figure, Steven Buchanan was selected. A screen similar to the one shown in the following figure is displayed. The first customer in the list is displayed by default in the Bill To box.

You now have access to all customers in the Northwind sample database. The emulator is demonstrating data held in tables in the NorthwindRepl.sdf database file on a Pocket PC. Tables created on the NorthwindRepl.sdf database include:

  • Employees

  • Orders

  • OrderDetails

  • Customers

  • Shippers

  • Products

To begin an order, select the customer you want to work with from the Bill To list and then click the Order tab. You will see a new order page like the one shown in the following figure. In this example, the customer Around the Horn is selected.

Add items to the order by selecting product names from the Product list. Enter a quantity for each item by using the keypad provided. Scroll right to see the extended price. Click the New Item button to drop down a row. When you have built a satisfactory order, take note of the number in the Order ID box. This will be the order number pushed back to SQL sever when you have a connection available. Since you are using emulation, as long as your developer machine has a network connection to the IIS/SQL Server machine, you always have a connection. Store the order in the local SQL Server CE database (NorthwindRepl.sdf) by clicking the Enter Order button.

To see this customer's order history, click the Review tab.

Click the Refresh button to view order detail information. Scroll to the bottom of the Select Order for Detail section. Click on the order number you want to see details on.

Pushing Data Back to SQL Server

Because SQL Server CE uses HTTP as the transport protocol, you can push data back to SQL Server through a modem, a wireless LAN, or the local area network. To push the changed data from a SQL Server CE database back to SQL Server, select Sync with Host from the Sync menu at the bottom of the emulator screen. You may want to verify that data was transferred to SQL Server by opening the Orders table in the Nwind_SQLCE sample database in Enterprise Manager.

Resetting the Application

There are a number of reasons why you may want to reset the application, for example, to configure alternate security schemes. To reset the application, locate and delete the database file NorthwindRepl.sdf in C:\Windows CE Tools\Wce300\MS Pocket PC\Emulation\Palm300.


Error Handling

This chapter contains information about the following types of errors:

  • Microsoft® eMbedded Visual Basic® application errors.

  • Microsoft® eMbedded Visual C++® application errors.

  • Replication, remote data access (RDA), and Engine Object errors (SQL Server CE ActiveX® control collections SSCEErrors and SSCEParams).

  • Microsoft® SQL Server™ CE errors.


Error Handling in eMbedded Visual Basic

Your application should explicitly trap and handle errors. If it does not trap errors, the eMbedded Visual Basic runtime will capture the highest-level error and display a generic message describing the error. By trapping and handing errors in your application, you can perform more sophisticated error recovery and display more meaningful error messages. Check for errors by placing On Error Resume Next at the beginning of any code segment that may generate an error, and then examine the appropriate error object after the statement is executed.

Your application can retrieve errors by using the following error objects:

  • eMbedded Visual Basic Err Object

    The eMbedded Visual Basic Err Object captures the application's most recent error. However, the most recent error is not always the most informative error. It is recommended that the ADOCE Error Object or SSCEError Object be used instead. The Visual Basic Err object does not return extended information, such as the native error number or error parameters, from SQL Server CE.

  • ADOCE Error Object

    When accessing a SQL Server CE database through Microsoft® CE Data Access 3.1 (ADOCE), use the ADOCE Error Object to retrieve the exhaustive list of errors.

  • SQL Server CE ActiveX Control SSCEError Object

    When accessing a SQL Server CE database through the replication, RDA, or Engine Objects, use the SQL Server CE ActiveX Control SSCEError Object to retrieve the exhaustive list of errors.


eMbedded Visual Basic Err Object

The eMbedded Visual Basic Err object contains information about the most recent runtime error. The application must specify On Error Resume Next to indicate that it explicitly handles errors. It must then examine the Err object each time it performs an operation that might generate an error to determine whether any error has occurred.

See Microsoft eMbedded Visual Basic 3.0 Books Online for more information about the eMbedded Visual Basic Err object.


ADOCE Error Object

When a data-related error occurs, the data source provider captures information about the error and stores it in the Error collection. The application must specify On Error Resume Next to indicate that it explicitly handles errors. It must then examine the Error collection each time is performs an ADOCE operation that might generate an error.

For more information about the objects, methods, and properties that are supported by the ADOCE control, see Microsoft ADO for Windows CE Books Online

Working with ADOCE Error Objects

The following example displays ADOCE errors:

Dim ceErr As Object
Dim strErr As String
Dim k

strErr = ""

' Connection Error handling routine
Sub ConnErrRoutine(ConnectionType As Object)
  For Each ceErr In ConnectionType.Errors
    strErr = strErr & "Source: " & ceErr.Source & vbCrLf
    strErr = strErr & "Number: " & Hex(ceErr.Number) & vbCrLf
    strErr = strErr & "NativeError: " & ceErr.NativeError & vbCrLf
    strErr = strErr & "Description: " & ceErr.Description & vbCrLf
    for k = 0 to ceErr.ErrorParameters.Count
      strErr = strErr & "Error Param " & k & ":" & ceErr.ErrorParameters(k)& vbCrLf
    next k
    strErr = strErr & vbCrLf
  Next ceErr
  MsgBox strErr, vbCritical
  Err.Number = 0 ' This resets the VB error
End Sub


SQL Server CE ActiveX Control SSCEError Object

The following eMbedded Visual Basic example displays replication, RDA, and Engine Object errors:

Sub ShowErrors(ErrColl As SSCEErrors)

  'Initialize error variables to view error collection
  Dim ErrRec As Object  'SSCE.ErrorRecords
  Dim param As Object
  Dim strErr As String

  strErr = ""

  For Each ErrRec In ErrColl
     strErr = strErr & "Source: " & ErrRec.Source & vbCrLf
     strErr = strErr & "Number: " & Hex(ErrRec.Number) & vbCrLf
     strErr = strErr & "NativeError: " & ErrRec.NativeError & vbCrLf
     strErr = strErr & "Description: " & ErrRec.Description & vbCrLf
     For Each param In ErrRec.Params
      strErr = strErr & "Param" & " = " & param.Param & vbCrLf
     Next param
     strErr = strErr & vbCrLf
  Next ErrRec

  MsgBox strErr, vbOKOnly

Set ErrRec = Nothing
Set param = Nothing
End Sub


Error Handling in eMbedded Visual C++

eMbedded Visual C++ applications can receive much more detailed information from SQL Server CE than HRESULTs. How you retrieve this extended error information depends on which of the following methods your application uses to interact with SQL Server CE:

  • OLE DB/CE

    OLE DB defines a mechanism to allow providers to return rich error messages to consumers, extending the standard error objects defined in COM. The OLE DB Error objects store multiple layers of errors and provide additional information beyond standard errors.

  • ADOCE

    When using ADOCE through eMbedded Visual C++, you can access the ADOCE Error Object and error collection to retrieve detailed error information.

  • SQL Server CE ActiveX Control SSCEError Object

    The Replication, RDA, and Engine Objects expose error collections and parameters that can be accessed through eMbedded Visual C++.


ADOCE Error Object

The ADOCE Error Object and error collection are exposed through the ADOCE Connection Object. The following sample illustrates ADOCE error handling through eMbedded Visual C++:

#include <wceatl.h>
#include ".\inc\ADOCE31.h"
#include ".\inc\ADOCE31_i.c"
#include ".\inc\ADOXCE31.h"
#include ".\inc\ADOXCE31_i.c"
#include ".\inc\ADOCEc31.h"
#include ".\inc\ADOCEc31_i.c"
#define CHECK(a,b) if(FAILED(a)) goto b;

void ShowADOErrors(IADOCEConnection* pIADOCEConnection)
  {
  IADOCEErrors    * pIADOCEErrors = NULL;
  IADOCEError     * pIADOCEError  = NULL;
  ErrorParameters * pIADOCEParams = NULL;
  IUnknown        * pIUnknown     = NULL;

  LONG  cbBuf        = 0;
  LONG  i            = 0;
  LONG  lErrorCount  = 0;
  LONG  lErrorIndex  = 0;
  LONG  lParamCount  = 0;
  LONG  lParamIndex  = 0;

  VARIANT  var;
  VARIANT  varParam;

  WCHAR    wszBuff[4096];
  WCHAR    * pwszBuffPos = &wszBuff[0];
  BSTR     bstr;
  BOOL     fSuccess      = FALSE;
  HRESULT  hr            = S_OK;

  // Initialize variants
  VariantInit(&var);
  VariantInit(&varParam);

  // Get the Errors collection from the connection object
  //
  hr = pIADOCEConnection->get_Errors(&pIADOCEErrors);
  CHECK(hr,ErrorExit);

  // Get count of errors
  //
  hr = pIADOCEErrors->get_Count(&lErrorCount);
  CHECK(hr,ErrorExit);
  if (lErrorCount <= 0)
    {
    MessageBox(NULL, L"No extended error information.",L"ShowErrors", MB_OK);
    fSuccess = TRUE;
    goto ErrorExit;
    }

  // Display errors, one at a time
  for (lErrorIndex = 0; lErrorIndex < lErrorCount; lErrorIndex++)
    {
    cbBuf = swprintf(pwszBuffPos, L"E R R O R   %d  of  %d\r\n", lErrorIndex+1, lErrorCount);
    pwszBuffPos += cbBuf;

    // Get next error record
    var.vt = VT_I4;
    var.lVal = lErrorIndex;
    hr = pIADOCEErrors->get_Item(var, (IADOCEError**) &pIUnknown);
    CHECK(hr,ErrorExit);

    hr = pIUnknown->QueryInterface(IID_IADOCEError,(void**)&pIADOCEError);
    CHECK(hr,ErrorExit);

    // Error Description
    hr = pIADOCEError->get_Description(&bstr);
    CHECK(hr,ErrorExit);

    cbBuf = swprintf(pwszBuffPos, L"DESCRIPTION: '%s'\r\n", bstr);
    SysFreeString(bstr);
    bstr = NULL;
    pwszBuffPos += cbBuf;

    // Error Number
    hr = pIADOCEError->get_Number(&i);
    CHECK(hr,ErrorExit);
    cbBuf = swprintf(pwszBuffPos, L"NUMBER: %8.8X\r\n", i);
    pwszBuffPos += cbBuf;

    // Native Error
    hr = pIADOCEError->get_NativeError(&i);
    CHECK(hr,ErrorExit);
    cbBuf = swprintf(pwszBuffPos, L"NATIVE_ERROR: %d\r\n", i);
    pwszBuffPos += cbBuf;

    // Error Source
    hr = pIADOCEError->get_Source(&bstr);
    CHECK(hr,ErrorExit);
    cbBuf = swprintf(pwszBuffPos, L"SOURCE: '%s'\r\n", bstr);
    SysFreeString(bstr);
    bstr = NULL;
    pwszBuffPos += cbBuf;

    // Retrieve the Error Parameters
    hr = pIADOCEError->get_ErrorParameters(&pIADOCEParams);
    CHECK(hr,ErrorExit);

    // Get the number of Error Parameters
    hr = pIADOCEParams->get_Count(&lParamCount);
    CHECK(hr,ErrorExit);

    // Display the Value of Each Parameter
    for (lParamIndex = 0; lParamIndex < lParamCount; lParamIndex++)
      {

      // Get the parameter object
      var.vt = VT_I4;
      var.lVal = lParamIndex;
      hr = pIADOCEParams->get_Item(var, &varParam);
      CHECK(hr,ErrorExit);

      if (VT_I4 == varParam.vt || VT_UI4 == varParam.vt)
        {
        cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.lVal);
        }
      else if (VT_I2 == varParam.vt || VT_UI2 == varParam.vt)
        {
        cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.iVal);
        }
      else if (VT_BSTR == varParam.vt)
        {
        cbBuf = swprintf(pwszBuffPos, L"P%d: '%s'\r\n", lParamIndex, varParam.bstrVal);
        }
      pwszBuffPos += cbBuf;

      }
    cbBuf = swprintf(pwszBuffPos, L"\r\n");
    pwszBuffPos += cbBuf;

    }

  // Display error information
  MessageBox(NULL, wszBuff,L"E R R O R", MB_OK);
  fSuccess = TRUE;

ErrorExit:

  // Release the Errors collection
  //
  if(pIADOCEErrors)
    {
    pIADOCEErrors->Release();
    pIADOCEErrors = NULL;
    }

  // Release the parameters object
  //
  if (pIADOCEParams)
    {
    pIADOCEParams->Release();
    pIADOCEParams = NULL;
    }

  // Release the error object
  //
  if (pIADOCEError)
    {
    pIADOCEError->Release();
    pIADOCEError = NULL;
    }

  // Release the unknown pointer
  //
  if(pIUnknown)
    {
    pIUnknown->Release();
    }

  // Release the bstr
  //
  if (bstr)
    {
    SysFreeString(bstr);
    bstr = NULL;
    }

  VariantClear(&var);
  VariantClear(&varParam);

  // Errors object is released in calling routine
  //
  if (!fSuccess)
    {
    MessageBox(NULL, L"Error while processing errors!",L"ShowErrors", MB_OK);
    }
  return;
  }


OLE DB/CE Error Handling

The OLE DB Error objects store multiple layers of errors and provide additional information beyond standard errors. The following example illustrates how to retrieve the provider-specific error numbers when using the OLE DB Provider for SQL Server CE.

Note The general mechanism for an OLE DB client to retrieve error information is described in the Microsoft OLE DB Programmer's Reference. This section describes what is returned by the OLE DB Provider for SQL Server CE once an error occurs.

Errordecode example:

/* This code sample demonstrates a routine that can handle and display errors from the OLE DB Provider for SQL Server CE. pIUnknown is the interface returning the error, and riid is the REFIID of that interface*/

   // QueryInterface for the ISupportErrorInfo interface
   hr = pIUnknown->QueryInterface(IID_ISupportErrorInfo, (void**)&pISupportErrorInfo);
   if(FAILED(hr) || NULL == pISupportErrorInfo)
      return;

   // Determine if the interface even supports errors. If it does, then ISupportErrorInfo
   // will return S_OK for that interface
   hr = pISupportErrorInfo->InterfaceSupportsErrorInfo(riid);
   pISupportErrorInfo->Release();      // release unneeded interface

   if(S_OK == hr)
      {
      // This interface supports returning error information

      // Get the error object from the system for this thread
      hr = GetErrorInfo(0, &pIErrorInfo);
      if(FAILED(hr) || NULL == pIErrorInfo)
         {
         return;
         }

      hr = pIErrorInfo->QueryInterface(IID_IErrorRecords, (void **) &pIErrorRecords);

      pIErrorInfo->Release();  // Release unneeded interface

      // Determine the number of records in this error object
      hr = pIErrorRecords->GetRecordCount(&ulNumErrorRecs);

// Loop over each error record in the error object to display information
      // about each error.  Errors are returned
      for (dwErrorIndex = 0; dwErrorIndex < ulNumErrorRecs; dwErrorIndex++)
         {

         // Attempt to retrieve basic error information for this error.
         hr = pIErrorRecords->GetBasicErrorInfo(dwErrorIndex, &ErrorInfo);

         // Retrieve standard error information for this error
         hr = pIErrorRecords->GetErrorInfo(dwErrorIndex, NULL, &pIErrorInfoRecord);

         // Get error description
         hr = pIErrorInfoRecord->GetDescription(&bstrDescriptionOfError);

         // Get error source
         hr = pIErrorInfoRecord->GetSource(&bstrSourceOfError);

         if(NULL != pIErrorInfoRecord)
            {
            pIErrorInfoRecord->Release(); // Release unneeded interface
            }

// Print the native error number for this error - these
// are documented in the Error Handling section
//
wprintf(L"Native Error Code: %l\n", ErrorInfo.dwMinor);
         }

      pIErrorRecords->Release();  // Release unneeded interface
      }
   }

Note The OLE DB Provider for SQL Server CE returns errors for each interface supported by the provider.


SQL Server CE ActiveX Control SSCEError Object

The following eMbedded Visual C++ example displays replication, RDA, and Engine Object errors:

#define       INC_OLE2
#define      INITGUID
#include    <windows.h>
#include    <ole2.h>
#include      <stdio.h>
#include    "ca_mergex.h"

void   ShowErrors(ISSCEErrors* pISSCEErrors)
   {
   HRESULT         hr;
   LONG            cbBuf;
   LONG            i;
   LONG            lErrorCount;
   LONG            lErrorIndex;
   LONG            lParamCount;
   LONG            lParamIndex;
   VARIANT         var;
   VARIANT         varParam;
   WCHAR            wszBuff[4096];
   WCHAR*         pwszBuffPos = &wszBuff[0];
   BSTR            bstr;
   ISSCEError*      pISSCEError = NULL;
   ISSCEParams*   pISSCEParams = NULL;
   ISSCEParam*      pISSCEParam = NULL;
   BOOL            fSuccess = FALSE;

   // Initialize variants
   VariantInit(&var);
   VariantInit(&varParam);

   // Get count of errors
   if(FAILED(hr = pISSCEErrors->get_Count(&lErrorCount))) goto Exit;
   if (lErrorCount <= 0)
      {
      MessageBox(NULL, L"No extended error information.",L"ShowErrors", MB_OK);
      fSuccess = TRUE;
      goto Exit;
      }

   // Display errors, one at a time
   for (lErrorIndex = 0; lErrorIndex < lErrorCount; lErrorIndex++)
      {
      cbBuf = swprintf(pwszBuffPos, L"E R R O R  %d of %d\r\n", lErrorIndex+1, lErrorCount);
      pwszBuffPos += cbBuf;

      // Get next error record
      var.vt = VT_I4;
      var.lVal = lErrorIndex;
      if(FAILED(hr = pISSCEErrors->get_Item(var, &pISSCEError))) goto Exit;

      // Error Description
      if (FAILED(hr = pISSCEError->get_Description(&bstr))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"DESCRIPTION: '%s'\r\n", bstr);
      pwszBuffPos += cbBuf;
      SysFreeString(bstr);

      // Error Number
      if (FAILED(hr = pISSCEError->get_Number(&i))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"NUMBER: %8.8X\r\n", i);
      pwszBuffPos += cbBuf;

      // Native Error
      if (FAILED(hr = pISSCEError->get_NativeError(&i))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"NATIVE_ERROR: %d\r\n", i);
      pwszBuffPos += cbBuf;

      // Error Source
      if (FAILED(hr = pISSCEError->get_Source(&bstr))) goto Exit;
      cbBuf = swprintf(pwszBuffPos, L"SOURCE: '%s'\r\n", bstr);
      pwszBuffPos += cbBuf;
      SysFreeString(bstr);

      // Retrieve the Error Parameters
      if (FAILED(hr = pISSCEError->get_Params(&pISSCEParams))) goto Exit;

      // Get the number of Error Parameters
      if (FAILED(hr = pISSCEParams->get_Count(&lParamCount))) goto Exit;

      // Display the Value of Each Parameter
      for (lParamIndex = 0; lParamIndex < lParamCount; lParamIndex++)
         {

         // Get the parameter object
         var.vt = VT_I4;
         var.lVal = lParamIndex;
         if (FAILED(hr = pISSCEParams->get_Item(var, &pISSCEParam))) goto Exit;

         // Get and display the parameter value
         if (FAILED(hr = pISSCEParam->get_Param(&varParam))) goto Exit;
         if (VT_I4 == varParam.vt || VT_UI4 == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.lVal);
            }
         else if (VT_I2 == varParam.vt || VT_UI2 == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: %d\r\n", lParamIndex, (LONG) varParam.iVal);
            }
         else if (VT_BSTR == varParam.vt)
            {
            cbBuf = swprintf(pwszBuffPos, L"P%d: '%s'\r\n", lParamIndex, varParam.bstrVal);
            }
         pwszBuffPos += cbBuf;

         // Clear variant
         VariantClear(&varParam);

         // Release the parameter object
         pISSCEParam->Release();
         pISSCEParam = NULL;
         }
      cbBuf = swprintf(pwszBuffPos, L"\r\n");
      pwszBuffPos += cbBuf;

      }

   // Display error information

   MessageBox(NULL, wszBuff,L"Error", MB_OK);
   fSuccess = TRUE;

Exit:
   // Release the parameter object
   if (pISSCEParam)
      {
      pISSCEParam->Release();
      pISSCEParam = NULL;
      }

   // Release the parameters object
   if (pISSCEParams)
      {
      pISSCEParams->Release();
      pISSCEParams = NULL;
      }

   // Release the error object
   if (pISSCEError)
      {
      pISSCEError->Release();
      pISSCEError = NULL;
      }

   // Errors object is released in calling routine
   if (!fSuccess)
      {
      MessageBox(NULL, L"Error while processing errors!",L"ShowErrors", MB_OK);
      }
   return;
   }


Replication, RDA, and Engine Object Errors

Applications use the following SQL Server CE ActiveX Control collections to retrieve error information on replication, RDA, and engine object errors:

  • SSCEErrors Collection

  • SSCEParams Collection


SSCEErrors Collection

Applications use the SSCEErrors collection to retrieve information regarding errors. The SSCEErrors collection contains a set of SSCEError objects. The collection is created when a SQL Server CE Replication, RemoteDataAccess, or Engine object method call fails. The Error collection is retained until the next SQL Server CE Replication, RemoteDataAccess, or Engine object method is called.

An eMbedded Visual Basic program references SSCEErrors by using Ssceca10.dll. An eMbedded Visual C++ program includes Ca_mergex.h and Ca_mergex.lib.

See Also

SSCEError Object

Remote Data Access

Programmer's Guide to Engine Object

Replication


SSCEErrors Collection Properties

The SQL Server CE SSCEErrors collection supports the following property:

  • Count Property


Count Property

The Count property specifies the number of SSCEError objects in the collection.

Applies to

SSCEErrors Collection

Syntax

object.Count [=value]

Part | Description
object | SSCEErrors collection
value | Number of SSCEError objects in the collection

Remarks

The SSCEErrors collection is created when a SQL Server CE Replication, RemoteDataAccess, or Engine Object method call fails. The Error collection is retained until the next SQL Server CE Replication, RemoteDataAccess, or Engine Object method is called.

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_Count(long *plCount);


SSCEError Object

SQL Server CE uses SSCEError objects to report errors to SQL Server CE applications. SSCEError is a member of the SSCEErrors collection. SQL Server CE creates an SSCEErrors collection containing one or more SSCEError objects whenever a call to a SQL Server CE Replication, RemoteDataAccess, or Engine Object method fails. The application can enumerate through the collection and examine each SSCEError object to identify the error.

Visual Basic programs reference SSCEError by using Ssceca10.dll.

Visual C++ programs include Ca_mergex.h and Ca_mergex.lib.

See Also

SSCEErrors Collection

Remote Data Access

Programmer's Guide to Engine Object

Replication


SSCEError Properties

The SSCEError object supports the following properties:

  • Description Property_errors_description_property

  • NativeError Property_errors_nativeerror_property

  • NativeParams Property_errors_nativeparams_property

  • ErrorNumber Property_errors_errornumber_property

  • Source Property_errors_source_property


Description Property

The Description property provides a descriptive error message.

Applies to

SSCEError Object

Syntax

object.Description [=value]

Part | Description
object | SSCEError object
value | Description of the error

Remarks

The Description property provides a descriptive error message that is suitable for displaying to the user. Error messages can originate from SQL Server, SQL Server CE Replication, SQL Server CE RDA, SQL Server CE OLE DB, or SQL Server CE Query Processor. Only errors originating from SQL Server 2000 currently generate error strings.

Data Type

String

Modifiable

Read-only

Prototype eVC++

HRESULT get_Description(BSTR *pVal);

See Also

SSCEError Properties

SSCEError Object


NativeError Property

The NativeError property reports native error numbers.

Applies to

SSCEError Object

Syntax

object. NativeError [=value]

Part | Description
object | SSCEError object
value | Native error number

Remarks

The NativeError property provides the native error number reported by the error source.

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_NativeError(long *pVal);

See Also

SSCEError Properties

SSCEError Object


NativeParams Property

The NativeParams collection provides the parameters from the native error.

Applies to

SSCEError Object

Syntax

object. NativeParams [=value]

Part | Description
object | SSCEError object
value | Collection of parameters returned from the native error

Remarks

The NativeParams collection is created when a SQL Server CE Replication, RemoteDataAccess, or Engine Object method call fails, and the NativeError contains parameters on the error. The Error collection is retained until the next SQL Server CE Replication, RemoteDataAccess, or Engine Object method is called.

Data Type

Variant

Modifiable

Read-only

Prototype eVC++

HRESULT get_NativeParams(variant *pVal);

See Also

SSCEError Properties

SSCEError Object


ErrorNumber Property

The ErrorNumber property provides the OLE HRESULT.

Applies to

SSCEError Object

Syntax

object.ErrorNumber [=value]

Part | Description
object | SSCEError object
value | OLE HRESULT error number

Remarks

The ErrorNumber property provides the OLE HRESULT error number reported by the error source.

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_ErrorNumber(long *pVal);

See Also

SSCEError Properties

SSCEError Object


Source Property

The Source property names the source of the native error.

Applies to

SSCEError Object

Syntax

object.Source [=value]

Part | Description
object | SSCEError object
value | Name of the source where the error occurred

Remarks

The Source property is a string expression providing the name of the object or application that originally generated the native error. The value of this property is provider-defined.

Data Type

String

Modifiable

Read-only

Prototype eVC++

HRESULT get_Source(BSTR *pVal);

See Also

SSCEError Properties

SSCEError Object


SSCEParams Collection

Applications use the SSCEParams collection to retrieve detailed information regarding a specific error. The SSCEParams collection contains a set of six SSCEParam objects. The collection is created when a SQL Server CE Replication, RemoteDataAccess, or Engine object method call fails. The Error collection is retained until the next SQL Server CE Replication, RemoteDataAccess, or Engine object method is called.

A Visual Basic program references SSCEParams by using Ssceca10.dll. A Visual C++ program includes Ca_mergex.h and Ca_mergex.lib.

See Also

Remote Data Access

Programmer's Guide to Engine Object

Replication


SSCEParams Collection Properties

The SQL Server CE SSCEParams collection supports the following property:

  • Count Property


Count Property

The Count property specifies the number of SSCEParams objects in the collection. Always expect six objects in the collection even if all six are not used.

Applies to

SSCEParams Collection Properties

Syntax

object.Count [=value]

Part | Description
object | SSCEError collection
value | Number of SSCEError objects in the collection

Remarks

The SSCEErrors collection is created when a SQL Server CE Replication, RemoteDataAccess, or Engine Object method call fails. The Error collection is retained until the next SQL Server CE Replication, RemoteDataAccess, or Engine Object method is called.

Data Type

Long

Modifiable

Read-only

Prototype eVC++

HRESULT get_Count(long *plCount);

See Also

SSCEParams Collection Properties


SSCEParam Object

SQL Server CE uses SSCEParam objects to report detailed errors to SQL Server CE applications. SSCEParam objects are members of the SSCEParams collection. SQL Server CE creates an SSCEParams collection containing six SSCEParam objects whenever a call to a Replication, RemoteDataAccess, or Engine object method fails. The application can enumerate through the collection and examine each Error object to identify the error.

Visual Basic programs reference SSCEParam by using Ssceca10.dll.

Visual C++ programs include Ca_mergex.h and Ca_mergex.lib.

See Also

SSCEParams Collection

Remote Data Access

Programmer's Guide to Engine Object

Replication


SSCEParam Properties

The SSCEParam object supports the following property:

  • Param Property


Param Property

The Param property provides a descriptive element of an error.

Applies to

SSCEParam Object

Syntax

object.Param [=value]

Part | Description
object | SSCEParam object
value | Descriptive element of the error

Remarks

The Param property provides a descriptive element of an error message. There are always six SSCEParam objects in an SSCEParams collection. The first three are integers and the last three are strings. Some of SSCEParam object may not be used. Unused integer SSCEParam objects contain the value 0 and unused string SSCEParam objects contain an empty string. Error messages can originate from SQL Server, SQL Server CE Replication, SQL Server CE RDA, SQL Server CE OLE DB, or SQL Server CE Query Processor. Only errors originating from SQL Server 2000 currently generate error strings.

Data Type

Variant

Modifiable

Read-only

Prototype eVC++

HRESULT get_Param(BSTR *pVal);

See Also

SSCEParam Object


SQL Server CE Errors

The following categories of errors can be generated from SQL Server for SQL Server CE. When SQL Server CE returns an error, use the native number of the error to look up an error description in the following tables. Parameters are also listed in these tables. The first three parameters of an error (P0,P1,P2) are integers, while the last three parameters (P3,P4,P5) are strings.

Category | Range
Engine errors | 25000-27999
Replication transport errors | 28000-28499
Client agent errors | 28500-28799
Client agent warnings | 28800-28999
Server agent errors | 29000-29499
Message protocol errors | 29500-29999
SQL Server CE Relay errors | 30000-30499
Miscellaneous | 39500-39999

Note If you are looking for other HRESULTs, see oledberr.h in ADOCE, or winerr.h and wininet.h in the Microsoft® Windows® CE Platform SDK.


Engine Errors

Value | Description | Parameters | Error
25001 | Either not on a row or walked off the end of the row |  | SSCE_M_NOCURRENTRECORD
25002 | Invalid buffer size specified |  | SSCE_M_INVALIDBUFFERSIZE
25003 | Specified length is too large for the column type |  | SSCE_M_COLUMNLENGTHTOOBIG
25004 | Column is not allowed to be modified |  | SSCE_M_COLUMNNOTUPDATEABLE
25005 | NULL not allowed for this column |  | SSCE_M_NULLINVALID
25006 | Attempt to perform operation not valid for this object |  | SSCE_M_INVALIDOPERATION
25007 | Operation not valid when in a transaction |  | SSCE_M_INTRANSACTION
25008 | Invalid parameter passed to the storage engine |  | SSCE_M_INVALIDPARAMETER
25009 | Invalid path name specified | P3: Path | SSCE_M_INVALIDPATH
25010 | Invalid file name specified |  | SSCE_M_INVALIDFILENAME
25011 | File examined was not recognized as a valid database format | P3: DatabaseName | SSCE_M_INVALIDDATABASE
25012 | Update was attempted before the PrepUpdate was called |  | SSCE_M_UPDATENOTPREPARED
25013 | Operation is only supported on tables that are locked exclusively |  | SSCE_M_TABLENOTLOCKED
25014 | Access to system column denied |  | SSCE_M_SYSCOLACCESSDENIED
25015 | Could not allocate a page |  | SSCE_M_CANTALLOCATEPAGE
25016 | Illegal attempt with a duplicate key |  | SSCE_M_KEYDUPLICATE
25017 | Nondatabase file or database file corrupted | P3: DatabaseName | SSCE_M_DATABASECORRUPTED
25018 | Write lock failed due to outstanding write lock |  | SSCE_M_WRITECONFLICT
25019 | Commit lock failed due to outstanding read lock |  | SSCE_M_READCONFLICT
25020 | Read lock failed due to outstanding commit lock |  | SSCE_M_COMMITCONFLICT
25021 | Another session has a private version of the page |  | SSCE_M_SESSIONWRITECONFLICT
25022 | Null keys are not allowed on index |  | SSCE_M_NULLKEYDISALLOWED
25023 | Unknown object version |  | SSCE_M_UNKNOWNVERSION
25024 | Passive connection control prevented database open |  | SSCE_M_CONNECTIONCONTROL
25025 | References to key exist | P3: ForeignConstraintName | SSCE_M_INTEGRITYVIOLATION_MSTR
25026 | No referenced key exists | P3: PrimaryConstraintName | SSCE_M_INTEGRITYVIOLATION_SLV
25027 | Record too big |  | SSCE_M_RECORDTOOBIG
25028 | Invalid password |  | SSCE_M_INVALIDPASSWORD
25029 | Attempt to update field in a record twice |  | SSCE_M_RI_UPDATETWICE
25030 | Duplicate key as a result of referential integrity action | P3: ForeignTableName | SSCE_M_RI_DUPLICATEKEY
25031 | Null value as a result of referential integrity action not allowed | P3: ForeignTableName | SSCE_M_RI_KEYNULLDISALLOWED
25032 | Session write conflict due to cascading | P3: ForeignTableName | SSCE_M_RI_SESSIONWRITECONFLICT
25033 | Invalid sort sequence |  | SSCE_M_ILLEGALCOLLATINGSEQ
25034 | File locking violation |  | SSCE_M_FILELOCKVIOLATION
25035 | File sharing violation |  | SSCE_M_FILESHAREVIOLATION
25036 | File locking unavailable |  | SSCE_M_FILELOCKINGUNAVAILABLE
25037 | No space left on disk |  | SSCE_M_DISKFULL
25038 | No space left on disk |  | SSCE_M_TEMPDISKFULL
25039 | Access to the database file is not allowed | P3: FileName | SSCE_M_FILEACCESSDENIED
25040 | Invalid application signature |  | SSCE_M_INVALIDAPPSIGNATURE
25042 | Invalid sort DLL |  | SSCE_M_INVALIDSORTDLL
25043 | Too many active users |  | SSCE_M_TOOMANYACTIVEUSERS
25044 | Too many open files |  | SSCE_M_TOOMANYOPENFILES
25045 | Obsolete database format |  | SSCE_M_OBSOLETEDATABASEFORMAT
25046 | File not found | P3: FileName | SSCE_M_FILENOTFOUND
25047 | Read verification error |  | SSCE_M_READVERIFYERROR
25048 | No more file handles |  | SSCE_M_NOMOREFILEHANDLES
25049 | Disk not ready |  | SSCE_M_DISKNOTREADY
25050 | Sharing buffer exceeded |  | SSCE_M_SHARINGBUFFEREXCEEDED
25051 | Disk I/O error |  | SSCE_M_DISKIO
25052 | Operating system doesn't support threads |  | SSCE_M_THREADSNOTSUPPORTED
25053 | No call to MakeKey |  | SSCE_M_KEYNOTMADE
25054 | Too many columns in index |  | SSCE_M_TOOMANYKEYS
25055 | Illegal attempt to delete a container that still had items |  | SSCE_M_CONTAINERNOTEMPTY
25056 | Size of the UNICODE text column is not even |  | SSCE_M_COLUMNWIDTHNOTEVEN
25057 | Cannot append long value |  | SSCE_M_LV_INVALIDAPPEND
25058 | Invalid operation without a current index |  | SSCE_M_NOCURRENTINDEX
25059 | Column's type cannot be indexed |  | SSCE_M_ILLEGALINDEXCOLUMN
25060 | No such reference |  | SSCE_M_REFERENCENOTFOUND
25061 | Internal error |  | SSCE_M_INTERNAL_INVALIDDBID
25062 | Object is not replicable |  | SSCE_M_OBJECTNOTREPLICABLE
25064 | Illegal attempt to create a second row GUID, Autoinc, or version on column |  | SSCE_M_ONLYONESPECIALCOLUMN
25065 | Too many indexes | P3: TableName | SSCE_M_TOOMANYINDEXES
25066 | Too many columns |  | SSCE_M_TOOMANYCOLUMNS
25067 | Transaction nested too deeply |  | SSCE_M_TRANSTOODEEP
25068 | Referencing or referenced index is the same |  | SSCE_M_SELFREFERENCE
25069 | No primary index on referenced table |  | SSCE_M_NOPRIMARYINDEX
25070 | Different number of columns in relationship |  | SSCE_M_DIFFNUMRELCOLUMNS
25071 | Reference conflicts with existing reference | P3: IndexName | SSCE_M_CONFLICTINGREFERENCE
25072 | Primary keys must be created on non-NULL columns |  | SSCE_M_PRIMARYKEYNULLCONFLICT
25073 | Tables must have at least one column |  | SSCE_M_TABLEMUSTHAVECOLUMNS
25074 | Expression string for the default value is too long |  | SSCE_M_DEFAULTEXPRTOOLONG
25075 | Cannot create an identity on column that allows nulls |  | SSCE_M_DISALLOWIDENTITYNULL
25077 | Cannot remove constraint; it is currently referenced by another constraint |  | SSCE_M_CONSTRAINTINUSE
25078 | Cannot remove index; it is currently used to enforce a constraint |  | SSCE_M_INDEXINUSE
25079 | Encrypted databases must have a password |  | SSCE_M_ENCRYPTEDDBMUSTHAVEPWD
25080 | The CryptoAPI isn't available on this operating system |  | SSCE_M_NOOSENCRYPTIONSUPPORT
25081 | AutoInc generated was outside the min/max range specified for the column |  | SSCE_M_VIOLATEDAUTOINCRANGE
25082 | Unique indexes/constraints cannot be created over nullable columns |  | SSCE_M_UNIQUENULLCONFLICT
25083 | Reference would cause a cycle; not allowed |  | SSCE_M_CYCLEDETECTED
25084 | Columns in relationship do not match due to type |  | SSCE_M_RELCOLUMNSTYPEMISMATCH
25085 | The table already has a primary key |  | SSCE_M_PKDUPLICATE
25086 | Identity column contains invalid INCREMENT | P3: ColumnName | SSCE_M_INVALIDINCREMENT
25087 | The GUID generation function failed |  | SSCE_M_GENERATEGUIDFAILED
25200 | Column is NULL-valued |  | SSCE_WRN_COLUMNNULL
25201 | Buffer too short; data truncated |  | SSCE_WRN_BUFFERTRUNCATED
25202 | SeekLE or SeekGE did not find exact match |  | SSCE_WRN_SEEKNOTEQUAL
25203 | Some options specified were ignored |  | SSCE_WRN_OPTIONSIGNORED
25204 | Data truncated |  | SSCE_WRN_COLUMNDATATRUNCATED
25205 | Database is encrypted |  | SSCE_WRN_DATABASEENCRYPTED
25206 | Some additional records got updated due to referential integrity actions |  | SSCE_WRN_RI_RECORDSUPDATED
25207 | Some additional records got deleted due to referential integrity actions |  | SSCE_WRN_RI_RECORDSDELETED
25208 | Requested row-level locking but unable to honor request |  | SSCE_WRN_ROWLOCKCONNECTFAILED
25209 | Requested page-level locking but unable to honor request |  | SSCE_WRN_PAGELOCKCONNECTFAILED
25500 | Query optimization error; plan not created or found |  | SSCE_M_QP_BADOPT
25501 | Error parsing query | P0: Token line number P1: Token line offset P3: Token in error | SSCE_M_QP_BADPARSE
25502 | Count of column names does not match count of source expressions |  | SSCE_M_QP_SETLISTCOUNT
25503 | Bad column name specified | P3: NodeName (if any) P4: ColumnName | SSCE_M_QP_BAD_COLNAME
25504 | Integrity violation; not an identity column or does not have the nullability property | P3: Name of column in error | SSCE_M_QP_INSERTMISSINGCOL
25505 | Bad constraint specified |  | SSCE_M_QP_BADCNSTS
25506 | Out of memory |  | SSCE_M_QP_NOMEMORY
25507 | Process premature EOF |  | SSCE_M_QP_UNCLOSEDCOMMENT
25508 | Token specified too long | P0: Maximum size of token (if known) P3: Token (if known) | SSCE_M_QP_TOKTOOLONG
25509 | Function overflow; ATOF |  | SSCE_M_QP_ATOF_OVERFLOW
25510 | Numeric value overflow during parsing |  | SSCE_M_QP_NUME_OUTOFRANGE
25511 | Found end-of-query before end-quote |  | SSCE_M_QP_UNCLOSEDQUOTE
25512 | Bad money value specified |  | SSCE_M_QP_BADMONEY
25513 | Invalid identifier; NULLs specified |  | SSCE_M_QP_IDENTWITHNULL
25514 | Invalid identifier; empty string specified |  | SSCE_M_QP_NAME_EMPTY
25515 | For aggregates or grouping, the SELECT clause can only contain aggregates or expressions composed of grouping terms |  | SSCE_M_QP_NO_SCALAR_IN_SELECT
25516 | Aggregates cannot be nested within other aggregates |  | SSCE_M_QP_NO_AGG_IN_AGG
25517 | For aggregates or grouping, the HAVING clause can only contain aggregates or expressions composed of grouping terms |  | SSCE_M_QP_NO_SCALAR_IN_HAVING
25518 | For aggregates or grouping, the ORDER BY clause can only contain aggregates or expressions composed of grouping terms |  | SSCE_M_QP_NO_SCALAR_IN_AGGRORDERBY
25519 | No aggregates in expressions in the GROUP BY list |  | SSCE_M_QP_NO_AGG_IN_GROUPBY
25520 | No aggregates in expressions in the ORDER BY list |  | SSCE_M_QP_NO_AGG_IN_ORDERBY
25521 | Duplicate expression specified in ORDER BY list |  | SSCE_M_QP_NO_DUPEXPR_IN_ORDERBY
25522 | Not all table aliases in the query are distinct | P3: Name of duplicate alias | SSCE_M_QP_DUP_TABLE_ALIAS
25523 | Not all column aliases are unique | P3: Name of duplicate alias | SSCE_M_QP_DUP_COLUMN_ALIAS
25524 | Cannot have a HAVING clause without a GROUP BY (implicit or explicit) |  | SSCE_M_QP_HAVING_WITHOUT_GROUPBY
25525 | The WHERE clause cannot reference aggregates |  | SSCE_M_QP_NO_AGG_IN_WHERE
25526 | Duplicate constraint specified |  | SSCE_M_QP_DUP_CNST
25527 | A method in the array that matches this method already exists; ambiguous call | P3: Name of function | SSCE_M_QP_AMBIGUOUS_FUNC
25529 | Cannot instantiate the OLE DB provider |  | SSCE_M_QP_CANT_COCREATE
25530 | Column name has already been specified | P3: Name of duplicate column | SSCE_M_QP_SETLIST_DUPCOLNAME
25531 | Ambiguity in resolution of column name | P3: Name of ambiguous column | SSCE_M_QP_AMBIGUOUS_COLNAME
25532 | Bad float precision specified |  | SSCE_M_QP_BAD_FLOAT_PRECISION
25533 | Identifier specified is too long | P3: Name of column (if known) | SSCE_M_QP_LONGIDNAME
25534 | Order by operators do not allow large objects (i.e., ntext/image) |  | SSCE_M_QP_LOB_IN_ORDERBY
25536 | Invalid meta data for large object |  | SSCE_M_QP_INVALIDMETA_FOR_LOB
25537 | Subquery column mismatch |  | SSCE_M_QP_SUBQUERY_COLUMN_MISMATCH
25538 | Encryption specified but no database password specified |  | SSCE_M_QP_ENCRYPTION_NO_DBPASSWORD
25539 | Invalid escape character for LIKE predicate |  | SSCE_M_QP_BADLIKEESCCHAR
25540 | Bad date option specified | P3: Portion of data in error | SSCE_M_QP_BADDATEOPTION
25541 | Invalid identifier specified |  | SSCE_M_QP_INVALID_IDENTIFIER
25542 | Attempt to insert into a read-only table | P3: Name of read-only table | SSCE_M_QP_READONLYINSERT
25543 | Attempt to update a read-only table | P3: Name of read-only table | SSCE_M_QP_READONLYUPDATE
25544 | Attempt to delete from a read-only table | P3: Name of read-only table | SSCE_M_QP_READONLYDELETE
25545 | No values provided for INSERT statement into table <table_name> | P3: Name of table | SSCE_M_QP_NOINSERTCOLUMNS
25546 | Attempt to modify a non-writeable column <column_name> | P3: Name of column | SSCE_M_QP_MODIFYPROTECTEDCOL
25547 | ORDER BY <column number> not supported |  | SSCE_M_QP_SCALARORDERBYNOTSUPPORTED
25548 | Distinct operator does not work with large objects (i.e., ntext/image) |  | SSCE_M_QP_LOB_IN_DISTINCT
25549 | Group by operator does not work with large objects (i.e., ntext/image) |  | SSCE_M_QP_LOB_IN_GROUPBY
25550 | Multiple identity columns specified for table; only one identity column per table is allowed |  | SSCE_M_QP_MULTI_IDENTITY_COLUMNS
25551 | Identity column must be of data type int, and constrained to be nonnullable. |  | SSCE_M_QP_BAD_IDENTITY_TYPE
25552 | Elements in the GROUP BY clause must reference columns in the SELECT list |  | SSCE_M_QP_GROUPBY_MUST_REFERENCE_COLS
25553 | Can't have foreign key cascade RI on self-table keys |  | SSCE_M_QP_CASCADEONSELFREFFK
25554 | Defaults cannot be created on columns with an IDENTITY attribute. | P3: Name of table P5: Name of column | SSCE_M_QP_NODEFAULTONIDENTITYCOL
25555 | Subquery columns cannot be BLOB/CLOB |  | SSCE_M_QP_SUBQUERY_NOLOBCOLUMNS
25556 | Names cannot begin with a number sign (#) | P3: invalid name | SSCE_M_QP_INVALID_CHARACTER_IN_IDENTIFIER
25900 | Internal error in expression service |  | SSCE_M_QP_BADEXPR
25901 | Expression overflow |  | SSCE_M_QP_OVFLO
25902 | Type mismatch in IN expression |  | SSCE_M_QP_EXPRTYPECHECK
25903 | Error in part of date format |  | SSCE_M_QP_DATEPART
25904 | Error in date format |  | SSCE_M_QP_DATEABORT
25905 | Syntax error occurred |  | SSCE_M_QP_SYNTAX
25906 | Syntax error in conversion logic |  | SSCE_M_QP_CONVSYNTAX
25907 | Overflow of money data type in string to money conversion |  | SSCE_M_QP_MONEYOVERFLOW
25909 | Column references in default values not supported |  | SSCE_M_QP_NOCOLUMNREFINDEFAULT
25910 | Aggregate functions in default values not supported |  | SSCE_M_QP_NOAGGRINDEFAULT
25911 | Cannot put large objects (blob/ntext) in aggregates |  | SSCE_M_QP_NOAGGRONLOB
25912 | Cannot convert due to truncation of original data |  | SSCE_M_QP_NOCONVDUETOTRUNC
25913 | Arithmetic operator not supported; first parameter indices operator |  | SSCE_M_QP_ARITHOPNOTSUPPORTED
25914 | Modulo is not supported on real, float, money, and numeric types | P3: Name of type | SSCE_M_QP_NOMODULOSUPPORT
25916 | Invalid operator against result type for subquery expression, (>,<,etc.) |  | SSCE_M_QP_SUBQUERYINVALIDOP
25917 | Bit operators (&,|,^,~) are not supported on real, float, money, and numeric types | P3: Name of type | SSCE_M_QP_NOBITOPSUPPORT
25918 | Trying to do arithmetic operation with invalid type |  | SSCE_M_QP_BADARITHTYPE
25919 | Arithmetic operator is not recognized by SQL Server CE |  | SSCE_M_QP_BADARITHOP
25920 | Data truncation error |  | SSCE_M_QP_TRUNCATION
25921 | Not a recognized function name | P3: Name of function P5: Data type | SSCE_M_QP_INVALIDFUNCTIONNAME
25922 | Bad arguments to function <func_name> | P3: Name of function (if known) | SSCE_M_QP_INVALIDFUNCTIONARGS
25923 | Data types ntext and image cannot be used in WHERE, HAVING, GROUP BY, ON, or IN clause except with the LIKE or IS NULL predicates |  | SSCE_M_QP_NOSUPPORTFORLOB
25924 | Could not convert binary to datetime due to possible overflow |  | SSCE_M_QP_BINDTSYNTAX
25925 | Numeric value overflowed datetime value during conversion |  | SSCE_M_QP_NUMDTSYNTAX
25926 | Money value overflowed datetime value during conversion |  | SSCE_M_QP_MONDTSYNTAX
25927 | Bigint value overflowed datetime value during conversion |  | SSCE_M_QP_BIGINTDTSYNTAX
25928 | Too many arguments supplied to the function |  | SSCE_M_QP_TOOMANYARGS
25929 | Cannot perform a unary minus on types other than tinyint, smallint, int, bigint, money, numeric |  | SSCE_M_QP_UMINUSNUMONLY
25930 | Cannot perform operation due to numeric precision mismatch |  | SSCE_M_QP_PRECISIONMISMATCH
25931 | Cannot perform operation due to scale mismatch |  | SSCE_M_QP_SCALEMISMATCH
25932 | Cannot perform an implicit conversion from one type to another |  | SSCE_M_QP_NOIMPLICITCONVALLOWED
25933 | Conversion of string to datetime caused an overflow |  | SSCE_M_QP_DATETIMEOVFLO
25934 | Error thrown when hitting a code path that requires type specific logic that is missing |  | SSCE_M_QP_MISSINGTYPELOGIC
25935 | Divide by zero attempt |  | SSCE_M_QP_DIVBYZERO
25937 | Syntax error converting datetime from character string. No TIME part was specified in the string. |  | SSCE_M_QP_NOTIMEPARTSPECIFIED
25938 | Syntax error converting datetime from character string. Invalid HOUR specified in TIME part. |  | SSCE_M_QP_INVALIDHOURTIMEPARTSPECIFIED
25939 | Syntax error converting datetime from character string. Invalid MINUTE specified in TIME part. |  | SSCE_M_QP_INVALIDMINUTETIMEPARTSPECIFIED
25940 | Syntax error converting datetime from character string. Invalid SECOND specified in TIME part. |  | SSCE_M_QP_INVALIDSECONDIMEPARTSPECIFIED
25941 | Syntax error converting datetime from character string. Invalid MILLISECOND specified in TIME part. |  | SSCE_M_QP_INVALIDMSEDCONDIMEPARTSPECIFIED
25942 | Syntax error converting datetime from character string. Invalid syntax in DATE or TIME part specified in the string. |  | SSCE_M_QP_SYNTAXERRORINDATETIMESTRING
25943 | Format error converting datetime from character string. Invalid format of DATE or TIME part specified in the string. |  | SSCE_M_QP_FORMATERRORINDATETIMESTRING
25944 | Format error converting datetime from character string. Invalid order within the DATE or TIME part specified in the string. |  | SSCE_M_QP_INVALIDORDERINDATETIMESTRING
25945 | Invalid escape sequence in LIKE predicate |  | SSCE_M_QP_INVALID_ESCAPE_SEQUENCE
26100 | Invalid table name | P3: Name of table | SSCE_M_QP_BADTABLE
26101 | Error accessing schema rowset |  | SSCE_M_QP_BADSCHEMAROWSET
26102 | Error accessing tables schema rowset |  | SSCE_M_QP_TBLSCHEMAROWSET
26300 | Error returned from OLE DB call |  | SSCE_M_QP_OLEDBERR
26301 | Cannot cast from the specified type |  | SSCE_M_QP_BADADT
26302 | Bad type specified |  | SSCE_M_QP_BADTYPE
26303 | Internal query processor error occurred |  | SSCE_M_QP_INTERNAL
26304 | No error |  | SSCE_M_QP_ALLWELL
26305 | Bad meta information |  | SSCE_M_QP_BADADTMETAINFO
26306 | Failed data conversion | P0: OLE DB status value | SSCE_M_QP_COERSIONERROR
26308 | SQL Server CE does not support zero length binary constants |  | SSCE_M_QP_ZEROLENGTHBINARYCONST
27000 | Too many outstanding sessions |  | SSCE_M_TOOMANYSESSIONSOUTSTANDING
27001 | Cannot set COLUMN property PRIMARY KEY when adding a column. Create a table level constraint instead. |  | SSCE_M_PRIMARYKEYPROPERTYNOTSETTABLE
27002 | Cannot set COLUMN property UNIQUE when adding a column. Create a table level constraint instead. |  | SSCE_M_UNIQUEKEYPROPERTYNOTSETTABLE
27003 | Cannot change a column's nullability after it has been created |  | SSCE_M_COLUMNNULLABILITYNOTALTERABLE
27004 | Cannot add the IDENTITY attribute to column after it has been created |  | SSCE_M_CANTMODIFYIDENTITYATTRIBUTE
27005 | Attempt to set invalid column property |  | SSCE_M_INVALIDCOLUMNPROPERTY
27500 | Decimal data overflow error |  | SSCE_M_DECIMALOVERFLOW
27501 | Decimal data truncation error |  | SSCE_M_DECIMALTRUNCATED
27502 | Invalid parameter was passed to Common |  | SSCE_M_CMN_INVALIDPARAMETER
27700 | Decimal data truncated warning |  | SSC_WRN_DECIMALTRUNCATED


Replication Transport Errors

Value | Description | Parameters | Error
28000 | SQL Server CE Transport Open called without closing previous open |  | SSCE_M_OPENTWICE
28001 | InternetRead returned an incorrect number of bytes |  | SSCE_M_INTERNETREADERROR
28002 | InternetWrite wrote an incorrect number of bytes |  | SSCE_M_INTERNETWRITEERROR
28003 | Either the server is out of memory or an incorrect RSCBID was sent in a request |  | SSCE_M_INVALIDRSCBID
28004 | There are too many requests pending at the server; no further requests can be queued |  | SSCE_M_TOOMANYPENDINGREQUESTS
28005 | Failed trying to start a thread to host the reconciler |  | SSCE_M_COULDNTSTARTRECTHREAD
28006 | Failed trying to load the reconciler resource DLL |  | SSCE_M_CANTLOADRECRESOURCEDLL
28007 | Invalid parameter to Reconciler |  | SSCE_M_INVALIDRECONCILERPARAM
28008 | Invalid transport command |  | SSCE_M_INVALIDTRNSPTCOMMAND
28009 | Unable to cocreate an instance of the Reconciler |  | SSCE_M_CANTCOCREATERECONCILER
28010 | Unable to cocreate an instance of the Reconciler's errors object |  | SSCE_M_CANTCOCREATERECONERROR
28011 | Authentication failed on server |  | SSCE_M_HTTPSTATUSDENIED
28012 | Authentication failed on proxy server |  | SSCE_M_HTTPSTATUSPROXYAUTHREQ
28013 | Bad request sent to server |  | SSCE_M_HTTPSTATUSBADREQUEST
28014 | Payment required to access this site |  | SSCE_M_HTTPSTATUSPAYMENTREQ
28015 | Forbidden from accessing this site without SSL (HTTPS) |  | SSCE_M_HTTPSTATUSFORBIDDEN
28016 | URL not found |  | SSCE_M_HTTPSTATUSNOTFOUND
28017 | Bad method invoked |  | SSCE_M_HTTPSTATUSBADMETHOD
28018 | Server returned 'none acceptable' |  | SSCE_M_HTTPSTATUSNONEACCEPT
28019 | Request timed out on server |  | SSCE_M_HTTPSTATUSREQTIMEOUT
28020 | Server returned status 'Conflict' |  | SSCE_M_HTTPSTATUSCONFLICT
28021 | Server returned status 'Gone' |  | SSCE_M_HTTPSTATUSGONE
28022 | Server error |  | SSCE_M_HTTPSTATUSSERVERERROR
28023 | Server returned status 'not supported' |  | SSCE_M_HTTPSTATUSNOTSUPPORTED
28024 | Bad gateway |  | SSCE_M_HTTPSTATUSBADGATEWAY
28025 | Service unavailable |  | SSCE_M_HTTPSTATUSSVCUNAVAIL
28026 | Gateway timeout |  | SSCE_M_HTTPSTATUSGATTIMEOUT
28027 | HTTPS not supported on this operating system |  | SSCE_M_HTTPSNOTSUPPORTED
28028 | Replication is prohibited for this server agent |  | SSCE_M_REPLPROHIBITED
28029 | RDA is prohibited for this server agent |  | SSCE_M_RDAPROHIBITED
28030 | Compression failed |  | SSCE_M_COMPRESSIONFAILED
28031 | Decompression failed |  | SSCE_M_DECOMPRESSIONFAILED
28032 | Failure initializing Internet functionality |  | SSCE_M_FAILUREINITIALIZINGINTERNET
28033 | Invalid URL syntax |  | SSCE_M_INVALIDURLSYNTAX
28034 | Internet connect failure |  | SSCE_M_INTERNETCONNECTFAILURE
28035 | Failure when querying header |  | SSCE_M_FAILUREQUERYINGHEADER
28036 | Failure when closing an Internet handle |  | SSCE_M_CLOSEINTERNETHANDLEFAILED
28037 | HttpSendRequest failed; HRESULT has more detail |  | SSCE_M_HTTPSENDREQUESTFAILED
28038 | Maximum number of RSCBs exceeded; connection refused by server; try again later |  | SSCE_M_MAXIMUMRSCBSEXCEEDED
28039 | Request was superseded by a subsequent request |  | SSCE_M_REQUESTSUPERSEDED
28040 | Command had already completed; resend ignored |  | M_RESENTCOMMANDIGNORED
28041 | Error used to force a resend of a command |  | M_RESENDREQUEST


Client Agent Errors

Value | Description | Parameters | Error
28500 | Unable to cocreate an instance of the SQL Server CE Errors collection object |  | SSCE_M_CANTCOCREATESSCEERRORS
28501 | Subscriber database path is missing |  | SSCE_M_SUBSCRIBERDATABASEPATHMISSING
28502 | Internet URL property is missing |  | SSCE_M_INTERNETURLPROPERTYMISSING
28503 | Publisher property is missing |  | SSCE_M_PUBLISHERPROPERTYMISSING
28504 | Publisher database property is missing |  | SSCE_M_PUBLISHERDATABASEPROPERTYMISSING
28505 | Publication property is missing |  | SSCE_M_PUBLICATIONPROPERTYMISSING
28506 | Subscriber property is missing |  | SSCE_M_SUBSCRIBERPROPERTYMISSING
28507 | Some Distributor properties are missing |  | SSCE_M_MISSINGDISTRIBUTORPROPERTIES
28508 | Missing Distributor address |  | SSCE_M_MISSINGDISTRIBUTORADDRESS
28509 | Missing Publisher address |  | SSCE_M_MISSINGPUBLISHERADDRESS
28510 | Invalid Publisher security mode |  | SSCE_M_INVALIDPUBLISHERSECURITYMODE
28511 | Invalid Distributor security mode |  | SSCE_M_INVALIDDISTRIBUTORSECURITYMODE
28512 | Invalid query timeout value |  | SSCE_M_INVALIDQUERYTIMEOUTVALUE
28513 | Invalid login timeout value |  | SSCE_M_INVALIDLOGINTIMEOUTVALUE
28514 | Invalid Distributor network |  | SSCE_M_INVALIDDISTRIBUTORNETWORK
28515 | Invalid exchange type |  | SSCE_M_INVALIDEXCHANGETYPE
28516 | Invalid validation type |  | SSCE_M_INVALIDVALIDATIONTYPE
28517 | Initialize failed |  | SSCE_M_INITIALIZEFAILED
28518 | Add Subscription failed |  | SSCE_M_ADDSUBSCRIPTIONFAILED
28519 | Unsupported Database Drop option |  | SSCE_M_UNSUPPORTEDDBDROPOPTION
28520 | Drop Subscription failed |  | SSCE_M_DROPSUBSCRIPTIONFAILED
28521 | Database is already replicable |  | SSCE_M_DBALREADYREPLICABLE
28522 | Run failed |  | SSCE_M_RUNFAILED
28523 | Internal object initialization failed |  | SSCE_M_INITIALIZATIONFAILED
28524 | Terminate failed |  | SSCE_M_TERMINATEFAILED
28525 | Reinitialize subscription failed |  | SSCE_M_REINITIALIZESUBSCRIPTIONFAILED
28526 | Unexpected ROC encountered in message |  | SSCE_M_UNEXPECTEDROCENCOUNTERED
28527 | Column ordinal not found |  | SSCE_M_COLUMNORDINALNOTFOUND
28528 | Failed to generate a nickname |  | SSCE_M_NICKNAMEGENERATIONFAILED
28529 | Database is not replicable |  | SSCE_M_DBNOTREPLICABLE
28530 | Failure trying to read registry |  | SSCE_M_FAILUREREADINGREGISTRY
28531 | Failure trying to write to the registry |  | SSCE_M_FAILUREWRITINGREGISTRY
28532 | Read from transport returned no data |  | SSCE_M_TRANSPORTREADRETURNEDNODATA
28533 | Cannot cocreate instance of SQLSERVERCE |  | SSCE_M_CANTCOCREATESQLSERVERCE
28534 | RDA Pull failed |  | SSCE_M_RDAPULLFAILED
28535 | RDA Push failed |  | SSCE_M_RDAPUSHFAILED
28536 | RDA SubmitSQL failed |  | SSCE_M_RDASUBMITSQLFAILED
28537 | Failure establishing Identity Range |  | SSCE_M_IDENTITYRANGE
28538 | An article in the message is invalid |  | SSCE_M_INVALIDARTICLE
28539 | The object is already initialized |  | SSCE_M_OBJECTALREADYINITIALIZED
28540 | The object is not initialized |  | SSCE_M_OBJECTNOTINITIALIZED
28541 | Local table name missing on Push call |  | SSCE_M_LOCALTABLENAMEMISSING
28542 | Not all the parameters were set for the Pull operation |  | SSCE_M_NOTALLPARAMSSETFORPULL
28543 | The table is not an RDA tracked table |  | SSCE_M_TABLENOTTRACKED
28544 | One or more error rows returned from RDA PUSH; see associated _err table |  | SSCE_M_RDAERRORROWSRETURNED
28545 | You must supply a valid OLE DB connection string |  | SSCE_M_SUBSCRIBERCONNECTIONSTRINGMISSING
28546 | The connection string cannot be parsed |  | SSCE_M_INVALIDCONNECTIONSTRING
28547 | Cannot compact a database that is open |  | SSCE_M_DATABASEALREADYOPEN
28548 | A parameter specified is too large |  | SSCE_M_PARAMETERTOOLARGE
28549 | Unable to apply retries |  | SSCE_M_FAILEDRETRIES
28550 | Unable to compact database |  | SSCE_M_COMPACTFAILED
28551 | Missing connection string for either Pull or Push |  | SSCE_M_MISSINGCONNECTSTRING
28552 | No ROWGUID column for this table |  | SSCE_M_ROW_RUID
28553 | NO ROWGUID or Identity range |  | SSCE_M_SPECIAL_COLUMN
28554 | The number of rows for the table does not match SQL Server | P0: SQL Server Count P1: SSCE Count | SSCE_M_VALIDATEFAILED
28555 | Failed making database replicable/unreplicable;reinitialize is now required |  | SSCE_M_FAILEDMAKEDBREP
28556 | A table name is required for the Pull command |  | SSCE_M_TABLENAMEMISSING
28557 | The database is in an unusable state. Delete it and recreate it. |  | SSCE_M_UNUSABLEDATABASE
28558 | Problems attempting to create the database |  | SSCE_M_CREATEDATABASE
28559 | Problems attempting to open the database |  | SSCE_M_OPENDATABASE
28560 | OLE DB Execute Method failed; bad or invalid SQL statement |  | SSCE_M_EXECUTEFAILED
28561 | Failed to ROLLBACK changes |  | SSCE_M_ROLLBACKFAILED
28562 | Failed to create the Delete message to send to the server |  | SSCE_M_PROCESSDELETEFAILED
28563 | Insufficient memory on the device |  | SSCE_M_CLIENTAGENT_NOMEMORY
28564 | Failed to DELETE a row |  | SSCE_M_DELETEFAILED
28565 | Failed to INSERT a row |  | SSCE_M_INSERTFAILED
28566 | Failed to UPDATE a row |  | SSCE_M_UPDATEFAILED
28567 | Failed to OPEN a table |  | SSCE_M_OPENTABLEFAILED
28568 | Failed to CLOSE a table |  | SSCE_M_CLOSETABLEFAILED
28569 | Failed to Set the Index for seeking on the Row Guid column |  | SSCE_M_INVALIDINDEX
28570 | Failed to Get the row data |  | SSCE_M_ERRORFETCHINGDATA
28571 | Failed to Get the column data for a row |  | SSCE_M_ERRORFETCHINGCOLUMNDATA
28572 | Failed to Set the row data |  | SSCE_M_ERRORSETTINGDATA
28573 | Local Table Already Exists |  | SSCE_M_TABLEALREADYEXISTS


Client Agent Warnings

Value | Description | Parameters | Error
28800 | One or more error rows returned from RDA Push; see associated _err table |  | SSCE_WRN_RDAERRORROWSRETURNED
28801 | A data error occurred and was fixed; a subsequent run is required for data convergence |  | SSCE_WRN_SUBWINSERRORSFIXED


Server Agent Errors

Value | Description | Parameters | Error
29000 | Unexpected state when reading generation info |  | SSCE_M_UNEXPECTEDSTATEREADINGGENINFO
29001 | Expected inserts only |  | SSCE_M_EXPECTEDINSERTSONLY
29002 | Identity seed or range is too large |  | SSCE_M_IDENTITYSEEDORRANGETOOLARGE
29003 | Unexpected state when processing tombstones |  | SSCE_M_UNEXPECTEDSTATEPROCESSINGTOMBSTONES
29004 | Can't cocreate instance MSDAInitialize |  | SSCE_M_CANTCOCREATEMSDAINITIALIZE
29005 | RSCB with same ExchangeID already exists |  | SSCE_M_RSCBWITHSAMEEXCHANGEID
29006 | SQL Server Reconciler failed |  | SSCE_M_SQLRECONCILERFAILED
29007 | Query cannot be tracked |  | SSCE_M_QUERYCANNOTBETRACKED
29008 | PrepareUpdate command failed |  | SSCE_M_PREPAREUPDATECMDFAILED
29009 | Cannot process expression or literal without alias |  | SSCE_M_EXPRESSIONWITHOUTALIAS
29010 | Table does not have a primary key |  | SSCE_M_NOPRIMARYKEY
29011 | Table contains a timestamp or other row versioning column |  | SSCE_M_ROWVERCOLUMN
29012 | Thrown when internal error during Push operation in server agent |  | SSCE_M_INVALIDPUSHSEQUENCE
29013 | Attempt to set a new param value on top of an existing param value in Push operation |  | SSCE_M_PUSHPARAMSETONVALUE
29014 | Not all parameters were set for Push operation |  | SSCE_M_NOTALLPARAMSETFORPUSH
29015 | Mismatch in column count between key data supplied and what was expected |  | SSCE_M_PUSHPKCOLCOUNTMISMATCH
29016 | Verifying schema cannot match up a client-side column to a server-side column for RDA table |  | SSCE_M_VF_MISSINGSERVERCOLUMN
29017 | Mismatched OLE DB type information between client columns and server columns for RDA table |  | SSCE_M_VF_MISMATCHEDTYPES
29018 | No columns found; missing tablename or invalid permissions on server |  | SSCE_M_VF_MISSINGTABLE
29020 | A row could not be updated/deleted on the server using RDA |  | SSCE_M_NOROWSAFFECTED
29021 | More than one row was affected by the update/delete on the server using RDA |  | SSCE_M_TOOMANYROWSAFFECTED
29022 | Incorrect version of SQL Server OLE DB provider |  | SSCE_M_INCORRECTPROVIDERVERSION
29023 | Incorrect provider |  | SSCE_M_INCORRECTPROVIDER
29024 | Push operation could not match client-side pk column order to server-side pk column order |  | SSCE_M_VF_PRIMARYKEYCHANGE
29025 | Push operation: expected primary key column missing on server side |  | SSCE_M_VF_MISSINGSERVERPKCOLUMN
29026 | Push operation: found extra server side primary key column |  | SSCE_M_VF_EXTRASERVERPKCOLUMN
29027 | DBSCHEMA_COLUMNS supported by server database provider does not have COLUMN_NAME, DATA_LENGTH, CHARACTER_MAXIMUM_LENGTH, or COLUMN_FLAGS support |  | SSCE_M_MISSINGCOLUMNSCHEMACOLS
29028 | Server code encountered an unsupported OLE DB type reported by server database provider |  | SSCE_M_UNSUPPORTEDOLEDBTYPE
29029 | Encountered DBTYPE_IUNKNOWN binding but DBCOLUMNFLAGS_ISLONG flag was not set in Push verify schema |  | SSCE_M_VF_NONLOBIUNKNOWN
29030 | Query cannot be tracked; not all columns in the primary key are included |  | SSCE_M_NOTRACKPKCOLMISSING
29031 | Query cannot be tracked; attempting to pull a computed column. |  | SSCE_M_NOTRACKCOMPUTEDCOLUMN
29032 | Query cannot be tracked; it is a multitable query. |  | SSCE_M_NOTRACKMULTITABLE
29033 | Server or override code page is invalid or not installed on IIS server |  | SSCE_M_INVALIDCODEPAGE
29034 | Client and server components have mismatched versions |  | SSCE_M_MISMATCHEDCOMPONENTS
29042 | RSCB was inactive for longer than the cleanup interval |  | SSCE_M_RSCBTIMEDOUT
29043 | Version of operating system on Windows CE device does not support authenticated proxy servers |  | SSCE_M_NOPROXYSERVERSUPPORT
29044 | Rename of .IN file to .OUT for retry transport failed |  | SSCE_M_FILERENAMEFAILED
29045 | Initialization of reconciler failed |  | SSCE_M_INITIALIZERECONCILERFAILED


Message Protocol Errors

Value | Description | Parameters | Error
29500 | Transport read returned incorrect data length |  | SSCE_M_TRANSPORTREADWRONGSIZE
29501 | Unexpected state when writing message |  | SSCE_M_UNEXPECTEDSTATEWRITINGMESSAGE
29502 | Invalid column number |  | SSCE_M_INVALIDCOLUMNNUMBER
29503 | Cannot find a column by its name |  | SSCE_M_CANTFINDCOLUMNBYNAME
29504 | Names buffer is too small |  | SSCE_M_NAMESBUFFERTOOSMALL
29505 | Incorrect number of columns processed |  | SSCE_M_INCORRECTNUMBEROFCOLUMNSPROCESSED
29506 | Unexpected state when getting columns |  | SSCE_M_UNEXPECTEDSTATEGETTINGCOLUMNS
29507 | Unexpected state when getting column length |  | SSCE_M_UNEXPECTEDSTATEGETCOLLENGTH
29508 | Unexpected state when getting column data |  | SSCE_M_UNEXPECTEDSTATEGETCOLDATA
29509 | Unexpected state when setting a column |  | SSCE_M_UNEXPECTEDSTATESETCOLUMN
29510 | Stream was not exhausted |  | SSCE_M_STREAMNOTEXHAUSTED
29511 | Message received from server cannot be decoded |  | SSCE_M_GARBLEDMESSAGEFROMSERVER
29512 | Message received from client cannot be decoded |  | SSCE_M_GARBLEDMESSAGEFROMCLIENT


SQL Server CE Relay Errors

Value | Description | Parameters | Error
30000 | WSANOTINITIALISED error on initialization or uninitialization of socket |  | SSCE_M_WSANOTINITIALISED
30001 | WSAENETDOWN error on initialization or uninitialization of socket |  | SSCE_M_WSAENETDOWN
30002 | WSAEINPROGRESS error on initialization or uninitialization of socket |  | SSCE_M_WSAEINPROGRESS
30003 | WSASYSNOTREADY error on initialization of socket |  | SSCE_M_WSASYSNOTREADY
30004 | WSAVERNOTSUPPORTED error on initialization of socket |  | SSCE_M_WSAVERNOTSUPPORTED
30005 | WSAEPROCLIM error on initialization of socket |  | SSCE_M_WSAEPROCLIM
30006 | WSAEFAULT error on initialization of socket |  | SSCE_M_WSAEFAULT
30007 | Create Event failed, hr is the system error |  | SSCE_M_CREATEEVENTFAILED
30008 | Set Event failed, hr is the system error |  | SSCE_M_SETEVENTFAILED
30009 | Wait for event failed, hr is the system error |  | SSCE_M_WAITFAILED
30010 | Invalid client port specified |  | SSCE_M_INVALIDCLIENTPORT
30011 | Conversion of server name to unicode failed |  | SSCE_M_CONVERSIONTOUNICODEFAILED
30012 | Invalid server port specified |  | SSCE_M_INVALIDSERVERPORT
30013 | Failure accessing system menu |  | SSCE_M_FAILUREACCESSINGSYSTEMMENU
30014 | Failure setting or creating registry keys |  | SSCE_M_FAILURESETTINGREGISTRY
30015 | Invalid parameter passed to sscerelay |  | SSCE_M_INVALIDARGUMENT
30016 | An invalid combination of arguments was supplied |  | SSCE_M_INVALIDARGUMENTS
30017 | A client or server port number is invalid or the server name is missing |  | SSCE_M_MISSINGPORTORSERVER
30018 | Socket call failed |  | SSCE_M_SOCKETCALLFAILED
30019 | Socket port is already in use on this machine |  | SSCE_M_PORTALREADYINUSE
30020 | Bind failed |  | SSCE_M_BINDFAILED
30021 | Cannot resolve server address |  | SSCE_M_CANTRESOLVESERVERADDRESS
30022 | Listen failed on a socket |  | SSCE_M_LISTENFAILED
30023 | Accept failed on a socket |  | SSCE_M_ACCEPTFAILED
30024 | Connect failed on a socket |  | SSCE_M_CONNECTFAILED
30025 | Cannot create a thread |  | SSCE_M_CANTCREATETHREAD
30026 | Set socket option for keepalive failed |  | SSCE_M_SETKEEPALIVEFAILED
30027 | Set socket option for Nagle algorithm failed |  | SSCE_M_SETNAGLEFAILED
30028 | Receive failed on a socket |  | SSCE_M_RECEIVEFAILED
30029 | Send failed on a socket |  | SSCE_M_SENDFAILED
30030 | Initialization of arguments failed |  | SSCE_M_INITARGSFAILED
30031 | WSAStartup failed |  | SSCE_M_WSASTARTUPFAILED
30032 | WSACleanup failed |  | SSCE_M_WSACLEANUPFAILED
30033 | Invalid or missing Server Name |  | SSCE_M_INVALIDSERVERNAME
30034 | Socket connection was reset |  | SSCE_M_CONNECTIONRESET


Miscellaneous

Value | Description | Parameters | Error
39999 | Evaluation copy has expired |  | SSCE_M_EVALUATIONCOPYEXPIRED


Troubleshooting

This section contains troubleshooting information for remote data access (RDA) and replication. It includes troubleshooting flowcharts for SQL Server security, Windows security, and Internet Information Services security.


Remote Data Access and Replication

You can use the following tools and techniques for troubleshooting SQL Server CE remote data access (RDA) and replication.


SQL Server Security Flowchart

Assumption:

Verify that you have entered the correct password.


 SQL Server CE Books Online

Windows Security Flowchart


Internet Information Services Security Flowchart

Assumptions:

  • Verify that you have entered the correct password.

  • You are not using a proxy server. If you are using a proxy server, see the RDA or Replication Object properties.

  • If you are using Anonymous Authentication, SQL Server and IIS are on the same computer. If not, see Anonymous Authentication on Windows 2000 or Anonymous Authentication on Windows NT 4.0.


Enabling Server Agent Logging

The Server Agent is capable of logging errors, warnings, and informational messages to a log file on the Microsoft® Internet Information Services (IIS) server. By default, logging is disabled. When logging is enabled, the Sscerepl.log file is written to the SQL Server CE IIS virtual directory. The information recorded in the log can be useful when you are trying to diagnose RDA or replication problems.

To enable Server Agent logging

  1. If it does not already exist, create the following registry key:

    HKLM\Software\Microsoft\MSSQLSERVERCE\Transport

  2. Under the HKLM\Software\Microsoft\MSSQLSERVERCE\Transport key, create a DWORD key value. The name of the key value must begin with the local path associated with your SQL Server CE IIS virtual directory. For example, if your Sscesa10.dll is located in the NTFS file directory C:\Inetpub\sqlce\NorthWind, you must name the registry value C:\Inetpub\sqlce\NorthWind\LOGGING_LEVEL. The data value of the DWORD key must be a value between 0 and 3. The following table describes the data values that may be assigned to the registry key value.

  3. After creating the registry entry, you must restart IIS. This is essential because the SQL Server CE Server Agent only reads the registry key when the Server Agent DLL is first loaded by IIS. You can restart IIS 5.0 on Microsoft® Windows® 2000 through Internet Service Manager by right-clicking the server name and selecting Restart IIS. If you are using IIS 4.0 on Windows NT 4, you must restart the computer.

  4. Ensure that IIS is active and that your Web site is started.

The data value contained in the registry entry controls the level of logging that the SQL Server CE Server Agent performs.

LOGGING_LEVEL Value | Meaning
0 | Logging is disabled.
1 | Log errors.
2 | Log errors and warnings.
3 | Log errors, warnings, and informational messages. Note The Server Agent generates very large log files when you specify LOGGING_LEVEL 3. You should not use this logging level under normal circumstances; however, it is useful when you are attempting to diagnose a problem.

For example, if your Sscesa10.dll is located in the NTFS file directory C:\Inetpub\SSCE\NorthWind, create the following registry key value. In this example, the key value "3" causes errors, warning, and informational message to be logged.

HKLM\Software\Microsoft\MSSQLSERVERCE\Transport
C:\Inetpub\sqlce\NorthWind\LOGGING_LEVEL   3


Using Internet Explorer to Check Your IIS Configuration

You can use Internet Explorer to verify that you have configured the Server Agent ISAPI DLL correctly. To do this, run Internet Explorer and enter the URL for your Server Agent, for example, http://myserver/sqlce/sscesa10.dll. If the Server Agent ISAPI DLL is configured correctly, Internet Explorer will display the string "Body".

You can also use Internet Explorer to verify that IIS security is working as you intended. If you configured IIS to require Basic Authentication, Internet Explorer should prompt you for your user name and password before displaying a response. If you configured IIS to use SSL encryption, your URL must specify HTTPS rather than HTTP, for example, https://myserver/sqlce/sscesa10.dll. When you use Internet Explorer to verify IIS security, you must stop and restart Internet Explorer each time you change any IIS security setting. This ensures that Internet Explorer establishes a new connection to IIS rather than reusing an existing connection that may already have been authenticated. You must use the Internet Explorer Refresh button each time you display the URL. This ensures that Internet Explorer sends the HTTP request to IIS rather than servicing the request out of its local cache. You will get misleading results unless you do both of these things each time you change any IIS security setting.


Replication Security Problems

Verify Your Security Settings

If you encounter problems with replication security, review the security settings for your system.

  1. Review the security setting for IIS.
    • Use the Internet Services Manager to verify the Client Authentication settings for the SQL Server CE replication virtual directory.

    • Use the Internet Services Manager to verify the Secured Sockets Layer (SSL) encryption setting for the SQL Server CE replication virtual directory.
  2. Review the security setting for the NTFS file system.
    • Verify that the client's Windows user account has read and execute permission on the Server Agent DLL (Sscesa10.dll).

    • Verify that the client's Microsoft® Windows® user account has read and write permissions to the NTFS file system directory you specified when you configured the IIS virtual directory.
  3. Review the security setting for Microsoft® SQL Server™.
    • Verify that the client's Windows user account has read permission to the NTFS file system SQL Server default Snapshot directory.

    • Verify whether SQL Server is configured to use Windows Integrated Authentication or SQL Authentication. If Windows Integrated Authentication is being used, verify that the client's Windows user account has been granted access to SQL Server. If SQL Authentication is being used, verify that the client is passing a valid SQL Server user name and password and the user has been granted access to SQL Server.
Check your IIS Configuration

See Using Internet Explorer to Check Your IIS Configuration, for more information.

Snapshot Folder

If the IIS user trying to access the snapshot file does not have read permission to the directory where the snapshot file is located, you will receive the following error:

The process could not deliver the snapshot to the Subscriber.