Microsoft SQL Server 2000 Windows CE Edition 2.0

 SQL Server CE Books Online

Portal page art

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 CE Product Web Site

Microsoft SQL Server Product Web Site

Samples


Getting Started with SQL Server CE Books Online

The following topics in this section provide information about using SQL Server CE Books Online, how to obtain additional resources about Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE), and using the accessibility features:

  • Documentation Conventions
  • Using SQL Server CE Books Online
  • Additional Resources
  • Accessibility for People with Disabilities


Documentation Conventions

The following table shows the conventions that 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 SQL Server CE Books Online

SQL Server CE Books Online is the online documentation provided with Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE). The Contents tab contains the topics in SQL Server CE Books Online. The topics are organized 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.


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.

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 or later, 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 SQL Server CE 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 this Microsoft Web site.

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 Contents tab, and then click Open All. | Opens all books or folders. This command only works if the Contents tab is displayed.
Right-click in the Contents tab, 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.
Right-click in the Contents tab, and then click Jump to URL. | Displays a window in which you can enter a URL to jump to.

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

The following table lists additional resources you can access on the Internet for information about Microsoft® SQL Server™ and related products and technologies.

Resource | Address
Microsoft Technical Support Web site | http://support.microsoft.com
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/
Microsoft SQL Server CE Web site | http://www.microsoft.com/sql/ce
Microsoft SQL Server Web site | http://www.microsoft.com/sql
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™ 2000 Windows CE Edition 2.0 (SQL Server CE) more accessible for people with disabilities:

  • SQL Server CE Accessibility Features
  • Accessibility in Microsoft Windows
  • Adjusting Microsoft Products for People with Accessibility Needs
  • Assistive Technology Products for Windows
  • Microsoft Documentation in Alternative Formats
  • Customer Services for People Who Are Deaf or Hard-of-Hearing
  • Getting More Accessibility Information

    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. For more information available in the following eight languages: English, French, Portuguese, Spanish, Chinese, Japanese, Swedish, and Italian, see http://www.microsoft.com/enable/.

SQL Server CE Accessibility Features

In addition to the Windows accessibility features and utilities described in the next section, the Help Viewer makes 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. The tool 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 SQL Server CE Books Online.

Accessibility in Microsoft Windows

Many accessibility features have been built into the Microsoft Windows operating system, starting with the introduction of Windows 95. These features are useful for individuals who have difficulty typing or using a mouse, are blind or have low vision, or who are deaf or hard-of-hearing. The features can be installed during setup. The following sections provide more information about the various accessibility features of Windows XP Professional and Home, Windows 2000, Windows Millennium, Windows 98, and Windows 95.

Windows XP Professional and Home

Accessibility enhancements and improvements in Microsoft Windows XP Professional and Home Editions provide better integration with assistive technology products and richer communications. Accessibility improvements and other Windows XP Professional features make it easier for people with accessibility needs to work more efficiently. For more information about accessibility enhancements and features in Windows XP, visit http://www.microsoft.com/windowsxp/accessibility/.

Windows 2000

Microsoft Windows 2000 includes several accessibility tools to help people with disabilities configure and use business computers quickly, without additional software and hardware. Accessibility features from earlier versions of the Windows operating system are still included, and with the increased integration of Microsoft Active Accessibility®, many assistive technology products simply work better. For more information about accessibility in Microsoft Windows 2000, visit http://www.microsoft.com/enable/products/.

Windows Me

Accessibility tools and features in Microsoft Windows Me offer people with disabilities greater immediate access and ease-of-use than ever before. Accessibility highlights include an expanded Accessibility menu and an enhanced Accessibility Wizard. For more information about accessibility in Windows Me, visit http://www.microsoft.com/enable/products/.

Windows 98

Microsoft Windows 98 offers enhanced hardware support, home networking capabilities, improved online experience, and new accessibility features. For more information about accessibility Microsoft Windows 98, visit http://www.microsoft.com/enable/products/.

Windows 95 and Windows NT Workstation 4.0

Microsoft Windows 95 and Windows NT Workstation 4.0 have several built-in accessibility features to help people with disabilities use computers more easily and effectively. For more information about accessibility in these operating systems, visit http://www.microsoft.com/enable/products/.

Adjusting Microsoft Products for People with Accessibility Needs

Accessibility options and features are built into many Microsoft products, including the Windows operating system. Accessibility options and features are useful for individuals who have difficulty typing or using a mouse, are blind or have low vision, or who are deaf or hard-of-hearing.

Free Step-by-Step Tutorials

Microsoft offers a series of step-by-step tutorials to help you learn how to adjust the accessibility options and settings on your computer. The tutorials provide detailed procedures on how to adjust options, features, and settings to meet the needs of people with disabilities and accessibility needs. This information is presented in a side-by-side format so that you can see at a glance how to use the mouse, the keyboard, or a combination of both. Step-by-Step Tutorials for the following products are available at http://www.microsoft.com/enable/training/.

  • Microsoft Windows XP Professional and Home
  • Microsoft Windows 2000
  • Microsoft Windows Me
  • Microsoft Windows 98
  • Microsoft Internet Explorer 6
  • Microsoft Internet Explorer 5
  • Microsoft Outlook 2002 (part of the Office XP suite)
  • Microsoft Outlook 2000
  • Microsoft Word 2002 (part of the Office XP suite)
  • Microsoft Word 2000
Assistive Technology Products for Windows

A wide variety of assistive technology products are available to make computers easier to use for people with disabilities.

Microsoft provides a searchable catalog of assistive technology products that run on Microsoft Windows operating systems at http://www.microsoft.com/enable/at/.

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 that provide 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 people 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.
Upgrading

If you use an assistive technology product, be sure to contact your assistive technology vendor to check compatibility with products on your computer before upgrading. Your assistive technology vendor can also help you learn how to adjust your settings to optimize compatibility with your version of Windows or other Microsoft products.

Microsoft Documentation in Alternative Formats

Microsoft product documentation is available in alternative formats to help our customers with accessibility needs.

Obtaining Documentation for SQL Server CE

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

Obtaining Documentation for Additional Microsoft Products

You can obtain accessible documentation for Microsoft products from the Microsoft Accessibility Web site at http://www.microsoft.com/enable/products/docs/.

Recording for the Blind & Dyslexic, Inc.

In addition, you can obtain additional Microsoft publications from Recording for the Blind & Dyslexic, Inc. These documents are distributed to registered, eligible members of the distribution service on audiocassettes or floppy disks. The collection contains more than 80,000 titles, including Microsoft product documentation and books from Microsoft Press®. For information about eligibility and availability of Microsoft product documentation and books from Microsoft Press, contact:

Recording for the Blind & Dyslexic, Inc.
20 Roszel Road
Princeton, NJ 08540
Phone from within the United States: (800) 221-4792
Phone from outside the United States and Canada: (609) 452-0606
Fax: (609) 987-8116
Web: http://www.rfbd.org/
Customer Service 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, Monday through Friday, excluding holidays.

Technical Assistance

For technical assistance in the United States, you can contact Microsoft Product Support Services on a text telephone at (800) 892-5234 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.

Getting More Accessibility Information

Information about assistive technology for improving the lives of people with disabilities is provided at the Microsoft Accessibility Web site at www.microsoft.com/enable/. The information on this site benefits people with disabilities and their friends and family members, people in outreach organizations, educators, and advocates.

A free monthly electronic newsletter is available to help you keep up to date with accessibility topics about Microsoft products. To subscribe, visit http://www.microsoft.com/enable/news/subscribe/default.asp.


Microsoft SQL Server 2000 Windows CE Edition 2.0 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-2002 Microsoft Corporation. All rights reserved.

Active Directory, ActiveSync, ActiveX, Microsoft, Microsoft Press, MSDN, MS-DOS, Visual Basic, Visual C++, Visual C#, Win32, 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.


What's New

Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE) extends the functionality of Microsoft SQL Server 2000 to the small footprint of Windows CE-based devices. This release of SQL Server CE provides enhanced database engine and query capabilities, improved connectivity solutions, and integration with the Microsoft Visual Studio® .NET development environment and the .NET Compact Framework.

SQL Server CE Books Online describes these enhancements in new sections and a redesigned content structure. In addition, the documentation has expanded to include more information and examples in the topics that cover connectivity, OLE DB, error handling, and SQL Server CE error messages.

SQL Server CE Database Engine
SQL Server CE Query Analyzer

SQL Server CE Query Analyzer now includes an easy-to-use interface that allows you to manage database objects in a graphical Objects tab. SQL Server CE Query Analyzer also provides 10 preset buttons in which you can save frequently used SQL statements for future querying.

For more information, see Using SQL Server CE Query Analyzer.

Query Processing

Additional intrinsic functions and support for the UNION operator allow you to create richer queries for accessing mobile data. For more information, see SQL Reference for SQL Server CE.

In conjunction with Microsoft ADO.NET, you also can use parameterized queries, which will result in faster querying and cleaner code. For more information, see Using Parameters in Queries.

Storage Engine

SQL Server CE now supports 249 indexes per table, the same number of indexes per table as Microsoft SQL Server 2000. For more information, see Understanding SQL Server CE Database Objects.

Database Management

A new error messages file (Ssceerror20en.dll) is available for application developers. For more information, see Installing SQL Server CE on a Windows CE-based Device.

SQL Server CE Connectivity
Connectivity Management

Two new connectivity tools allow you to configure the appropriate security and connectivity options:

  • Use the SQL Server CE Connectivity Management utility to launch the SQL Server CE Virtual Directory Creation Wizard, manage existing Microsoft Internet Information Services (IIS) virtual directories, and set up additional NTFS permissions.
  • Use the SQL Server CE Virtual Directory Creation Wizard to create new virtual directories and set up appropriate NTFS permissions.

For more information, see Using Connectivity Tools.

Replication and Remote Data Access (RDA)

The new UPLOAD replication option can significantly improve synchronization time when no changes need to be sent to the device. For more information, see ExchangeType Property (Replication).

To improve query performance, RDA now offers the ability to pull additional indexes from SQL Server. For more information, see Pull Method.

Development in Visual Studio .NET

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

.NET Compact Framework Data Providers

The System.Data.SqlServerCe namespace provides programmatic access to databases in SQL Server CE from a Visual Studio .NET application running on Windows CE .NET-based devices. For more information, see Data Provider for SQL Server CE (SqlServerCe).

The System.Data.SqlClient namespace provides the classes for developing Windows CE .NET-based applications that access databases in Microsoft SQL Server 7.0 or later. For more information, see Data Provider for SQL Server (SqlClient).

Sample Applications

The IBuySpy Delivery sample application is a robust application based upon real-world scenarios. Use this application to learn how to write replication and RDA in the .NET Framework development environment. For more information, see IBuySpy Delivery .NET Framework Application.

Performance
Query Processor

An improved query optimizer uses all available indexes in processing DML statements, complex joins, outer joins, and predicates with ORDER BY clauses.

Connectivity

SQL Server CE server-side components provide better processing of large synchronizations and reduce overall CPU utilization on the computer running Microsoft Internet Information Services (IIS).

The SQL Server CE Client Agent supports a useful connectivity retry time-out default while still maintaining recoverability from lost connections in the field. For more information, see "Supported Connectivity Solutions," in Client and Server Environments.


SQL Server CE Overview

Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE) extends Microsoft SQL Server to Microsoft Windows CE-based mobile devices, while providing developers with a consistent programming model for rapid application development. SQL Server CE delivers essential relational database functionality in a small footprint: a robust data store; an optimizing query processor; and reliable, scalable connectivity capabilities.

This section provides an overview of the SQL Server CE environment, including information about components, architecture, database engine, connectivity, and security. For complete information, see the relevant sections in this documentation.

The following table lists the main sections of SQL Server CE Books Online.

Section | Description
Installing SQL Server CE | Describes the hardware and software requirements for SQL Server CE and how to install the SQL Server CE platform.
Configuring Security for Connectivity | Describes how to configure a connection between SQL Server and Windows CE-based applications.
Managing Connectivity | Provides information about specific connectivity solutions, including remote data access (RDA) and replication.
Working with SQL Server CE Databases | Provides information about how to create and work with SQL Server CE databases, and how to access data in these databases.
Using SQL Server CE Query Analyzer | Describes the user interface of SQL Server CE Query Analyzer and how you can use these features to perform database tasks.
SQL Reference for SQL Server CE | Provides reference for the SQL grammar used to query or change data in SQL Server CE databases.
Building Applications | Provides programming reference for Microsoft .NET Compact Framework Data Providers, Microsoft ActiveX® Data Objects for Windows CE (ADOCE), replication, RDA, and error handling.
Deploying Applications | Describes how to package and distribute SQL Server CE-based applications.
Sample Applications | Provides sample applications that demonstrate the use of replication and RDA connectivity in the Microsoft Visual Studio® .NET and the Microsoft eMbedded Visual Tools development environments.
Troubleshooting | Provides troubleshooting information and error message descriptions for connectivity, Windows security, and Microsoft Internet Information Services (IIS) security.


SQL Server CE Environment

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides a compact database solution for mobile and embedded devices. By using Microsoft Visual Studio® .NET or Microsoft eMbedded Visual Tools, you can extend the enterprise data management capabilities of SQL Server to Windows CE-based devices. The following illustration shows the relationship of three typical environments in which SQL Server CE can be used.

Illustration showing the relationship of the three environments in which SQL Server CE can be used: a development, a client, and a server environment.

Development Environment

This is the computer on which Windows CE-based applications are developed. This computer must have one of the following development environments:

  • Microsoft Visual Studio .NET
  • Microsoft eMbedded Visual Tools version 3.0 installed with at least one of the following software development kits (SDKs): Handheld PC 2000 SDK, Pocket PC SDK, or the Windows Powered Pocket PC 2002 SDK.
Client Environment

This is the device on which the Windows CE-based application is deployed. When the Windows CE-based device does not contain network connectivity, Microsoft ActiveSync® can be used to connect to the server environment.

Server Environment

This is the computer(s) that runs Microsoft Internet Information Services (IIS) and an instance of Microsoft SQL Server. You can run IIS and SQL Server on the same computer or configure them over several computers. Remote data access (RDA) and merge replication communicate with SQL Server through IIS.


Client and Server Environments

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) relies on several components to exchange data from a Microsoft Windows CE-based device to an instance of SQL Server. The following illustration shows the relationship between the different components.

Illustration showing the relationship between SQL Server CE and the different components it relies on to exchange data.

SQL Server CE Database Engine

The SQL Server CE database engine manages the SQL Server data store on the Windows CE-based device. The SQL Server CE database engine can track all database records that are inserted, updated, or deleted by maintaining a small amount of change tracking information with each record. The tracking functionality is enabled when you use one of the two connectivity solutions.

SQL Server CE Client Agent

The SQL Server CE Client Agent is the primary component for connectivity on the Windows CE-based device. It implements these custom SQL Server CE objects: the Replication object, Remote Data Access (RDA) object, and Engine object. By using these objects, applications can programmatically control connections to SQL Server.

SQL Server CE Server Agent

The SQL Server CE Server Agent handles the HTTP requests made by the SQL Server CE Client Agent. When an application makes a request, the SQL Server CE Client Agent sends the request to the SQL Server CE Server Agent through HTTP. The SQL Server CE Server Agent connects to SQL Server and returns the resulting recordset to the SQL Server CE Client Agent through HTTP. Additional SQL Server connectivity components are involved in this process and are also located on the computer running Microsoft Internet Information Services (IIS), although they are not shown in the preceding illustration.

Replication and RDA handle HTTP requests differently and use different SQL Server connectivity components on the computer running IIS. For more information, see Managing Connectivity.

Supported Connectivity Solutions

SQL Server CE connectivity solutions communicate using Web protocols, HTTP or HTTPS. The SQL Server CE Client Agent, which resides on the Windows CE-based device, uses HTTP(S) to communicate with the SQL Server CE Server Agent on the Web server. The SQL Server CE Server Agent, which resides on the computer running IIS, communicates with SQL Server using either replication or remote data access.

Note SQL Server CE connectivity solutions are primarily intended for Windows CE-based devices that are occasionally connected to the network.

SQL Server CE works with the following network connectivity as long as they are configured to support HTTP(S):

  • Ethernet
  • Wireless LANs
  • Wireless WANs

By using Microsoft ActiveSync® 3.5 and a Pocket PC 2002 device connected using serial, infrared, or USB, you can directly access SQL Server through the network connection of the desktop computer. Other device and ActiveSync combinations require SQL Server CE Relay to be configured on the desktop computer.

SQL Server CE can use the Secure Sockets Layer (SSL) feature of IIS to encrypt data propagated between the device running SQL Server CE and the computer running SQL Server.

In addition, SQL Server CE connectivity solutions optimize wireless communication by compressing data to minimize the amount of data sent over the network. Data is propagated between the Windows CE-based device and the server by using a simple protocol patterned after file transfer protocols. SQL Server CE connectivity solutions recover from communication failures by restarting from the last successfully transmitted block of data, as long as the connection recovers within a time-out period of approximately two minutes. This makes synchronization possible even if the underlying transport is not reliable.


Development Environment

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports two development environments: Microsoft Visual Studio® .NET and Microsoft eMbedded Visual Tools. Both environments provide a set of data access application programming interfaces (APIs) and a subset of SQL syntax that work specifically with SQL Server CE.

Microsoft Visual Studio .NET

Microsoft Visual Studio .NET provides an application development platform for Microsoft Windows CE-based devices. Using Microsoft Visual Basic® .NET or Microsoft Visual C#™ .NET, you can develop Windows CE-based applications that communicate with databases in SQL Server and SQL Server CE.

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

The following illustration shows the relationship of the different components.

Illustration showing the relationship of the different components that interact with SQL Server CE in the Visual Studio .NET development environment.

For more information, see Development Tools.

Microsoft eMbedded Visual Tools

By using Microsoft eMbedded Visual Basic 3.0 or Microsoft eMbedded Visual C++® version 3.0 and version 4.0, you can apply your knowledge of Visual Basic or Visual C++ to develop Windows CE-based applications. You can create application code using a code editor, form editor, and property pane, which are similar to those used in Visual Basic or Visual C++. Like Visual Basic and Visual C++, eMbedded Visual Tools also provides an integrated development environment (IDE).

The following illustration shows the relationship of the different components.

Illustration showing how the different components that interact with SQL Server CE relate in the eMbedded Visual Tools development environment.

To develop applications with the eMbedded Visual Tools, the software development kit (SDK) for Handheld PC 2000, Pocket PC, or Pocket PC 2002 must be installed on the device. These SDKs include Windows CE-based device emulators, which provide the look of a physical device on the desktop computer. SQL Server CE-based applications can be created on a desktop computer and then tested on the emulator; so, no device is required.

For more information, see Development Tools.

Familiar Data Access Technologies

SQL Server CE is implemented as a set of dynamic-link libraries (DLLs) that support the following data access technologies:

  • Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE) and Microsoft ActiveX Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE)
  • ADO.NET
  • OLE DB Provider for SQL Server CE

ADOCE, ADOXCE, and ADO.NET are based on ADO, which is a high-level interface to all types of data. ADOCE provides consistent, high-performance access to data for developers using eMbedded Visual Basic to program applications for Windows CE. ADOCE is the most widely used interface for creating, accessing, and modifying SQL Server CE databases. ADOXCE extends ADOCE to expose additional objects for creating, modifying, and deleting schema objects. Schema objects are the attributes of the database, such as columns, indexes, tables, and properties. A subset of ADO.NET, which provides the same high-performance access to data for developers who are using Visual Basic .NET and C# as ADOCE, is available for Windows CE-based devices.

OLE DB is a low-level data interface technology. OLE DB for SQL Server CE can be used from eMbedded Visual C++, and it provides more granular capabilities than ADOCE or ADOXCE when used with SQL Server CE. Of all the data access APIs, OLE DB for SQL Server CE provides the fastest data manipulation and access.

For more information about programming with these objects, see Building Applications.

Familiar SQL Grammar

SQL Server CE includes SQL grammar that allows applications to query a database and insert, update, and delete data in the database. This grammar is compatible with the SQL grammar of other versions of Microsoft SQL Server. Most statements that run on SQL Server CE also run on SQL Server databases.

SQL Server CE also supports intrinsic functions that are consistent with functions provided in SQL Server.

For more information, see SQL Reference for SQL Server CE.


SQL Server CE Database Engine

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides:

  • SQL grammar compatible with SQL Server 2000.

    Using data definition language (DDL), you can create databases, alter tables, enforce and check referential integrity, and set default values. Using data manipulation language (DML), you can insert, update, and delete data. You can also use the SELECT statement, UNION, intrinsic functions, and parameterized queries.

  • Multiple-column indexes and matching index limits.
  • Transaction support.
  • Referential integrity.
  • 128-bit file-level encryption and password protection.
Compact Footprint

The SQL Server CE database engine occupies approximately 1.2 to 1.6 megabytes (MB) of disk space, depending on the processor of the target device. SQL Server CE supports databases up to 2 gigabytes (GB), with support for BLOBs of up to 1 GB.

For more information about the SQL Server CE database engine, see Working with SQL Server CE Databases.


Connectivity Solutions

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports two methods of connecting to and exchanging data with a data source:

  • Remote data access (RDA)
  • Merge replication

These connectivity solutions use the authentication, authorization, and encryption services of Microsoft Internet Information Services (IIS). The connectivity can be performed over wired and wireless LANs and WANs. You can configure Microsoft ActiveSync® 3.5 or ActiveSync 3.1 with SQL Server CE Relay, to use the network connection on a desktop computer to communicate with SQL Server. This eliminates the requirement for the Windows CE-based device to have a network card or modem.

RDA

RDA provides a simple way for a Windows CE-based application to access data located in a remote SQL Server 7.0 or SQL Server 2000 database. You can use RDA when you do not need the full functionality 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 data manipulation language (DML) statement that is forwarded to the SQL Server system for execution, or the application can supply an SQL query that returns a rowset. The resulting rowset is transmitted to the Windows CE-based device where it is stored in a table. All changes made by the application are optionally tracked, and at the request of the application, the updated rows are sent back to the server, where they are applied to the SQL Server database.

For more information, see Using Remote Data Access (RDA).

Merge Replication

Merge replication in SQL Server CE is based on the merge replication implemented in Microsoft SQL Server 2000. Merge replication is 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.

Common scenarios for merge replication include: read-only replication; data capture and upload; and replication, updating and synchronization. Most applications use a combination of these scenarios. 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 then upload them to a server.

You 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.

For more information, see Using Replication.


SQL Server CE Security

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) connectivity security relies on the security models of Microsoft Internet Information Services (IIS) and SQL Server 2000.

IIS authentication and authorization are configured to control which users can invoke the SQL Server CE Server Agent, thereby, controlling the users that can perform database synchronization using merge replication or remote data access. IIS can be configured to use Secure Sockets Layer (SSL) encryption. This safeguards the data sent between the Windows CE-based device and IIS when database synchronization or remote database access is performed.

For more information, see Configuring Security for Connectivity.

In addition, a SQL Server CE database relies on a password and 128-bit encryption for security. For more information, see Using SQL Server CE Database Security Features.


Installing SQL Server CE

The following topics in this section describe installing Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE).

Topic | Description
Before you begin
SQL Server CE Installation Overview | Describes the various systems and configuration options that can be used in a SQL Server CE environment.
Hardware and Software Requirements | Lists hardware and software requirements for each system.
Upgrading from Earlier Versions of SQL Server CE | Provides information on upgrading from SQL Server CE 1.0 and SQL Server CE 1.1.
Desktop installations
Installing SQL Server CE with Visual Studio .NET | Describes installing SQL Server CE on a computer running the Microsoft Visual Studio® .NET development environment.
Installing SQL Server CE with eMbedded Visual Tools | Describes installing SQL Server CE on a computer running the Microsoft eMbedded Visual Tools development environment.
Installing SQL Server CE with Platform Builder | Describes creating a custom Windows CE operating system that includes SQL Server CE using Platform Builder.
Device installations
Installing SQL Server CE on a Windows CE-based Device | Describes installing SQL Server CE on a Windows CE-based device.
Server installations
Installing SQL Server CE on an IIS System | Describes installing SQL Server CE on a computer running Microsoft Internet Information Services (IIS).
Installing SQL Server CE on a SQL Server System | Describes installing SQL Server CE on a computer running an instance of Microsoft SQL Server.
Other installations
Using SQL Server CE Relay with an ActiveSync System | Describes installing SQL Server CE Relay on a computer running Microsoft ActiveSync®.
Installing SQL Server CE Query Analyzer | Describes installing SQL Server CE Query Analyzer on a Windows CE-based device.


SQL Server CE Installation Overview

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) is typically installed in an enterprise environment, which requires installing and configuring up to five systems:

  • Development environment (Microsoft Visual Studio® .NET or Microsoft eMbedded Visual Tools)
  • Microsoft SQL Server system
  • Microsoft Internet Information Services (IIS) system
  • Microsoft Windows CE-based device
  • Microsoft ActiveSync® system (optional)

After choosing a server configuration, reviewing the hardware and software requirements for each system, and then installing the appropriate software, you are ready to install SQL Server CE.

Illustration showing the relationship of the client and server environments on which SQL Server CE components are installed.

Single- and Multiple-Server Environments

The servers in the SQL Server CE environment can be configured as either a single- or multiple-server environment. In a single-server environment, all systems are on one computer. In a multiple-server environment, the IIS and SQL Server systems are on different computers. As shown in the preceding illustration, a Windows CE-based device can connect directly to a single-server running IIS and SQL Server, multiple-servers (one running IIS and the other running SQL Server), or a workstation running a development environment. Application development environments for Windows CE-based mobile devices include Microsoft Visual Studio .NET and Microsoft eMbedded Visual Tools. Depending on your server configuration, you may have to install SQL Server CE Server Tools on more than one computer. For example, if you have multiple computers running IIS, each computer running IIS must have SQL Server CE Server Tools installed.

Multiple servers are typically used in production, especially in a corporate enterprise, because they provide more flexibility and can better meet complex security needs. If you are setting up SQL Server CE for the first time, consider setting up a single-server environment. This allows you to install all the necessary server software on one computer. You can further simplify setup by combining a single-server and development environment on one computer to create a complete development and test environment. After you have successfully set up a single-server environment, you can easily migrate to a multiple-server environment.

ActiveSync

ActiveSync is required in the development environment to deploy and debug applications. Microsoft Windows Powered Pocket PC 2002 can use ActiveSync 3.5 or later to synchronize SQL Server CE over a serial, infrared (IR), or USB connection. When using Pocket PC 2000 or Handheld PC 2000 mobile devices, you must use SQL Server CE Relay in conjunction with IIS to synchronize over these connections. For more information, see Using SQL Server CE Relay with an ActiveSync System.

See Also

Installing SQL Server CE

Hardware and Software Requirements

Installing SQL Server CE on a Windows CE-based Device


Hardware and Software Requirements

The tables in this topic describe the hardware and software requirements for each system that Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) interacts with. For more information, see SQL Server CE Environment.

Hardware Requirements
Platform | Requirements
Development environment | 45 MB of available disk space. The computer must have an additional 45 MB of temporary storage space for the setup files.
Microsoft Windows CE-based device (client environment) | 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 version of the Windows CE operating system. Space requirements also depend on the development environment and which SQL Server CE components you install.
Microsoft SQL Server system (server environment) | For more information, see "Installing SQL Server" in SQL Server Books Online.
Microsoft Internet Information Services (IIS) system (server environment) | 120 MB of available disk space.
Operating System Requirements
Platform | Supported operating systems
Development environment | Microsoft Windows 2000 and Windows XP. Microsoft ActiveSync® 3.1 or later is required.
SQL Server system (server environment) | For information, see "Installing SQL Server" in SQL Server Books Online.
IIS system (server environment) | Microsoft Windows 2000 and Windows XP. Windows NT 4.0 is supported only for manual configurations of the SQL Server CE Server Agent.
Windows CE-based device: | Microsoft Windows Powered Pocket PC 2002, Pocket PC 2000, and Handheld PC 2000. Microsoft Windows CE .NET version 4.1 (Platform Builder) is supported for embedded devices.
SQL Server Requirements
SQL Server | Supported SQL Server CE features
SQL Server 2000 with Service Pack 1 or higher | Merge replication and remote data access (RDA) are supported.
SQL Server version 7.0 with Service Pack 3 or higher | RDA is supported; replication is not supported.

RDA and replication require that Microsoft Data Access Components (MDAC) 2.6 or later be present on the Microsoft Internet Information Services (IIS) system. If MDAC 2.6 or later is not present on the IIS system, SQL Server CE Setup installs it when you specify the Server Tools installation option or launch the self-extracting SQL Server CE Server Tools installation file (Sqlce20sql2ksp1.exe or Sqlce20sql2ksp2.exe).

SQL Server CE RDA and replication are supported with computers running any edition of Microsoft SQL Server 2000 with Service Pack 1 or higher. SQL Server CE replication is not supported with earlier versions of SQL Server. RDA is supported on SQL Server 7.0, but only in a multiple-server environment; if IIS and SQL Server are installed on the same computer (a single-server environment) SQL Server 2000 with Service Pack 1 or higher is required.

IIS and Internet Explorer Requirements
Component | Requirements
Microsoft Internet Explorer 5.0 | Internet Explorer 5.0 or later is required on the development system to access SQL Server CE Books Online. Internet Explorer 5.0 or later is required on the IIS system.
Microsoft Internet Information Services (IIS) | IIS versions supported on Microsoft Windows NT 4.0 with SP5 or higher, Microsoft Windows 2000 and Microsoft Windows XP.
ActiveSync Requirements
Component | Requirements
ActiveSync 3.1 | Microsoft Windows 98 Second Edition, Windows Millennium Edition, Windows NT® 4.0 with Service Pack 5 or later, or Windows 2000.
ActiveSync 3.5 (Recommended) | Microsoft Windows 98 Second Edition, Windows Millennium Edition, Windows NT 4.0 with Service Pack 6 or later, Windows 2000, or Windows XP.


Upgrading from Earlier Versions of SQL Server CE

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports side-by-side installation. Versions of SQL Server CE can coexist on the same computer, enabling a simple and gradual upgrade process. SQL Server CE connectivity requires that the client components on the Windows CE-based device and the server components installed on the computer running Microsoft Internet Information Services (IIS) be the same major-release version.

Upgrading Deployed Applications

When you upgrade, install SQL Server CE Server Tools first and then client components. Do not deploy newer client applications if you still have an earlier version of SQL Server CE Server Tools on the computer running IIS. After all components are in place, redeploy the application to the devices. It is important to ensure the upgraded application is available and functioning properly before removing the previous release of your application and the SQL Server CE client components.

During the process of upgrading your application, you must change any references of SQL Server CE version 1.0 or 1.1 to SQL Server CE version 2.0. When you upgrade the computer running IIS, you must install Server Tools for SQL Server CE 2.0. You can then configure a new virtual directory for SQL Server CE 2.0 clients on this computer. As you deploy SQL Server CE 2.0 client components to your devices, you must update your application to use this new virtual directory for SQL Server CE 2.0 by updating the InternetURL property of your Replication or Remote Data Access (RDA) objects. The new InternetURL property ends with Sscesa20.dll instead of Sscesa10.dll. Updating the InternetURL property is critical because the SQL Server CE Client Agent for SQL Server CE 2.0 can communicate only with the SQL Server CE Server Agent for SQL Server CE 2.0.

Note When you update your applications, it is not necessary to re-create the database files (.sdf files). SQL Server CE versions 2.0, 1.1, and 1.0 share the same file format.

See Also

Deploying Applications


Installing SQL Server CE with Visual Studio .NET

Installing Microsoft® Visual Studio® .NET automatically configures the development environment for use with Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE). After installing Visual Studio .NET, you must still configure the computer running Microsoft Internet Information Services (IIS) and the Windows CE-based device.

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

File Locations and Descriptions

The following table lists the files, by location, that are installed on the development computer. By default, these files and folders are created in \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000.

Location | Contents
\Windows CE | A folder that contains SQL Server CE Assemblies, System.Data.SqlServerCe.dll and System.Data.Common.
\Windows CE\platform | A series of subfolders. Each folder contains dynamic-link libraries (DLLs), Ssce20.dll, Ssceca20.dll, and Sscemw20.dll for use with each of the processors supported by SQL Server CE. These folders also contain Isqlw20.exe, a program that implements the SQL Server CE Query Analyzer, and Ssceerror20en.dll, a DLL that provides error descriptions for use during development. All of these components are included in the cab files Sqlce.platform.processor.cab and Sqlce.dev.platform.processor.cab, which are also located in the subfolder for each processor.
\ | A folder that contains the SQL Server CE Books Online (Sqlce.chm), SQL Server CE Server Tools self-extracting executables (Sqlcesql2ksp1.exe and Sqlcesql2ksp2.exe), and SQL Server CE Relay extension to Microsoft ActiveSync® (SSCERelay.exe).
\Samples | A series of folders containing sample applications.


Installing SQL Server CE with eMbedded Visual Tools

This topic describes the prerequisites and steps for installing Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) on a computer running the Microsoft eMbedded Visual Tools development environment.

Note Set up the server configuration and the appropriate system software before you install SQL Server CE. For more information, see SQL Server CE Installation Overview and Hardware and Software Requirements.

Before you install SQL Server CE on the eMbedded Visual Tools development system, you must install:

  • Microsoft ActiveSync® 3.1 or later
  • Microsoft eMbedded Visual Tools 3.0
  • One of the following Windows CE Software Development Kits (SDKs): Pocket PC SDK, Handheld PC 2000 SDK, or the Microsoft Windows Powered Pocket PC 2002 SDK.

    The Pocket PC SDK is included with eMbedded Visual Tools, and the other SDKs are available at this Microsoft Web site.

To install SQL Server CE on an eMbedded Visual Tools development system

  1. From Windows Explorer, navigate to the location of the source files for SQL Server CE, and then double-click setup.exe.
  2. When prompted, click Development Tools.

    If Microsoft Internet Information Services (IIS) is running on the same computer as the development environment, select the Server Tools check box if you want to install Server Tools at this time. For more information, see Installing SQL Server CE on an IIS System.

After Setup completes, the development environment is configured to use SQL Server CE. SQL Server CE is not downloaded to the device until you begin your development project. For more information, see Installing SQL Server CE on a Windows CE-based Device.

Note If you encounter any problems during the installation of Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE), you must remove and reinstall SQL Server CE. The ADOCE components do not include a repair option under Add/Remove components in Control Panel.

File Locations and Descriptions

The following table lists the files, by location, that are installed on the development computer. By default, these files and folders are created in \Program Files\Microsoft SQL Server CE 2.0.

Location | Contents
\Device | A series of subfolders. Each folder contains dynamic-link libraries (DLLs), Ssce20.dll and Ssceca20.dll, for use with each of the processors supported by SQL Server CE. These folders also contain DllRegister.exe, a tool that registers the DLLs, Isqlw20.exe, a program that implements SQL Server CE Query Analyzer, and Ssceerror20en.dll, a DLL that provides error descriptions for use during development.
\Inc | Include files for use with Microsoft eMbedded Visual Basic® and Microsoft eMbedded Visual C++®. Ca_mergex20.h is the header for the SQL Server CE Microsoft ActiveX objects. Ssceoledb.h is the SQL SERVER CE header for OLE DB.
\Lib | A series of folders. Each folder contains the library Ca_mergex20.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_mergex20.tlb) is located in the root of this directory. It describes the SQL Server CE RDA, replication, and Engine objects.
\Relay | A folder that contains the SQL Server CE Relay extension to ActiveSync (SSCERelay.exe).
\Redist | A series of folders containing the components that you might have to include together when you deploy an application, including SQL Server CE Server Tools self-extracting executables (Sqlce20sql2ksp1.exe and Sqlce20sql2ksp2.exe) and SQL Server CE Relay.
\Samples | A series of folders containing sample applications.


Installing SQL Server CE with Platform Builder

Microsoft® Platform Builder is used to create a custom Microsoft Windows® CE operating system for use in a custom Windows CE-based device, such as an embedded controller for a piece of equipment. Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) supports Microsoft Platform Builder for Microsoft Windows CE .NET version 4.1.

Before you install SQL Server CE, you must install Microsoft ActiveSync® 3.1 or later and Microsoft Platform Builder for Microsoft Windows CE .NET version 4.1.

To install SQL Server CE on a computer with Platform Builder

  1. From Windows Explorer, navigate to the location of the source files for Microsoft SQL Server CE, and then double-click setup.exe.
  2. When prompted, click Development Tools.

After Setup completes, the platform builder environment is configured to use SQL Server CE.

File Locations and Descriptions

The following folder and files are installed on the computer running Platform Builder. By default, this folder and these files are created in \WinCE410\Others\SqlServerCE2. These files are installed in addition to the files specified in Installing SQL Server CE with eMbedded Visual Tools.

Location | Contents
\Device | A series of subfolders. Each folder contains dynamic-link libraries (DLLs), Ssce20.dll and Ssceca20.dll, for use with each of the processors supported by SQL Server CE. These folders also contain DllRegister.exe, a tool that registers the DLLs, Isqlw20.exe, a program that implements SQL Server CE Query Analyzer, and Ssceerror20en.dll, a DLL that provides error descriptions for use during development.

Important If you install eMbedded Visual Tools and one of the supported SDKs on the same computer with Platform Builder after SQL Server CE is installed, you must reinstall SQL Server CE to properly register SQL Server CE with the SDKs.


Installing SQL Server CE on a Windows CE-based Device

After you install Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) on a development system, you must install SQL Server CE on a Windows CE-based device. The process for installing SQL Server CE on the device depends upon whether you are using the Microsoft Visual Studio® .NET or the Microsoft eMbedded Visual Tools development environment. The following topics describe the installation process for each environment:

  • Installing SQL Server CE on a Device Using Visual Studio .NET
  • Installing SQL Server CE on a Device Using eMbedded Visual Tools


Installing SQL Server CE on a Device Using Visual Studio .NET

In the Microsoft® Visual Studio® .NET development system, you can use one of the following procedures to install the Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) system files to a Windows CE-based device:

  • Include SQL Server CE in your project.

    This is the most common method for installing SQL Server CE on a Windows CE device. To include SQL Server CE in your project, on the Project menu, click Add Reference, and select System.Data.SqlServerCe.

  • Manually copy and extract the .cab files.

    The Netcf.core.platform.processor.cab and Sqlce.platform.processor.cab files are installed by default in \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\platform\processor.

    The Sqlce.dev.platform.processor.cab file includes SQL Server CE Query Analyzer and the DLLs that provide error descriptions for use during development (Ssceerror20en.dll and Msdaeren.dll).


Installing SQL Server CE on a Device Using eMbedded Visual Tools

In the Microsoft® eMbedded Visual Tools development system, you can use either an automated process with Microsoft eMbedded Visual Basic® or a manual process to download Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) to the Windows CE-based device.

eMbedded Visual Basic Automated Process

Using eMbedded Visual Basic to include SQL Server CE in your project is the most common method for installing SQL Server CE on a Windows CE-based device. To include SQL Server CE in your project, on the Project menu, select References, Microsoft CE SQL Server Control 2.0, and then Microsoft CE ADO Control 3.1.

Note In the event of installation problems, you can force eMbedded Visual Basic to download components again: On the Project menu, click Properties. On the General tab, set the Update Components Frequency to Always, and select the Project Components check box.

If you are using Microsoft ActiveX® Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE), you must also include Microsoft CE ADO Ext. 3.1 for DDL. For more information, see Deploying Applications from eMbedded Visual Tools.

Manual Installation Process

You can manually install SQL Server CE and your eMbedded Visual Tools application on a Windows CE-based device by copying and registering all the required files. Use the following information to determine which files the application requires. Select the files appropriate for the processor type of the Windows CE-based device. To determine the processor type of the device, see the device documentation.

Application Files

On Pocket PCs, you can copy the application executable to the \Windows\Start Menu folder, and then run it from the Start menu on the device. The application executable file is located in the project tree that you create:

  • Microsoft eMbedded Visual Basic creates the executable file directly in the project subdirectory.
  • Microsoft eMbedded Visual C++® creates a separate subdirectory for each platform processor type that you want it to build. For example, MIPS processor application executables are created in \projectname\MIPSRel for the release version and \projectname\MIPSDbg for the debug version.
SQL Server CE Files

Copy the SQL Server CE files to the \Windows directory of the Windows CE-based device. These files are located in \Program Files\Microsoft SQL Server CE 2.0\Device\processor family\processor type by default. For more information about file locations and descriptions, see Installing SQL Server CE with eMbedded Visual Tools.

File | Requirement
Ssce20.dll | Required. Must be registered.
Ssceca20.dll | Required for replication and remote data access (RDA). Must be registered.
Ssceerror20en.dll | Optional for error messages used during development.
Isqlw20.exe | Optional for SQL Server CE Query Analyzer.
ADOCE and OLE DB Files

Copy the SQL Server CE files to the \Windows directory on the Windows CE-based device. These files are located by default in \Windows CE Tools\dataaccess31\Windows CE OS version\processor type.

File | Requirement
Msdaeren.dll | Optional for error messages. Msdaeren.dll is the English version of the Microsoft ActiveX Data Objects for Windows CE (ADOCE) error DLL and works on devices of all languages. For localized ADOCE error messages, substitute the Msdaerxx.dll that corresponds to the language setting of the device.
Adoce31.dll | Required. Must be registered.
Adoceoledb31.dll | Required.
Adoxce31.dll | Required for ADOXCE. Must be registered.
Registering the SQL Server CE Application on the Device

Use DllRegister.exe to register the DLLs that require registration. DllRegister.exe registers all the SQL Server CE, ADOCE, and OLE DB CE components on the device and warns if optional components are missing from the device. DllRegister.exe is located by default in \Program Files\Microsoft SQL Server CE 2.0\Device\processor family\processor type.

To register the SQL Server CE application

  1. Select the appropriate version of DllRegister.exe based on the processor type of the device.
  2. Copy DllRegister.exe from the development system to the Windows CE-based device, and then run the executable. On Pocket PCs, you can copy DllRegister.exe to the \Windows\Start menu folder, and then run it from the Start menu on the device.

    Alternately, you can register the DLLs individually by using Regsvrce.exe from the Windows CE SDK or by calling the DllRegisterServer function in each DLL.


Installing SQL Server CE on an IIS System

Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE) Server Tools are required for applications that use SQL Server CE connectivity. If you use replication or remote data access (RDA), you must install SQL Server CE Server Tools on the computer running Microsoft Internet Information Services (IIS). Replication requires the SQL Server CE Server Tools installer appropriate for the service pack that SQL Server is running. SQL Server CE ships with two installers: Sqlce20sql2ksp1.exe (SQL Server Service Pack 1) and Sqlce20sql2ksp2.exe (SQL Server Service Pack 2). If the instance of SQL Server is running a service pack later than Service Pack 2, download an updated SQL Server CE Server Tools installer from this Microsoft Web site.

SQL Server CE Server Tools Setup installs the SQL Server CE Server Agent (Sscesa20.dll) and the SQL Server CE Replication Provider (Sscerp20.dll) in \Program Files\Microsoft SQL Server CE 2.0\Server and additional SQL Server replication components in \Program Files\Microsoft SQL Server\80\Com.

To set up SQL Server CE on the computer running IIS if you are using Microsoft Visual Studio® .NET

  • From Windows Explorer on the computer running IIS, navigate to the source files for SQL Server CE, and then double-click sqlce20sql2ksp1.exe or sqlce20sql2ksp2.exe. These files are installed in \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000.

To set up SQL Server CE on the computer running IIS if you are using Microsoft eMbedded Visual Tools

  1. From Windows Explorer, navigate to the source files for SQL Server CE, and then double-click setup.exe.
  2. When prompted, click Server Tools. If the computer running IIS also has SQL Server Service Pack 1 or Service Pack 2 installed, the appropriate Server Tools installation file is installed. If the computer running IIS does not have SQL Server installed, the installation file that corresponds to SQL Server Service Pack 1 (Sqlce20sql2ksp1.exe) is installed.

    Note You can also obtain the Server Tools installer (Sqlce20sql2ksp1.exe and Sqlce20sql2ksp2.exe) from an existing development system. SQL Server CE Setup installs the files in \Program Files\Microsoft SQL Server CE 2.0\Redist\Server.

SQL Server CE Connectivity Management Utility

At the end of the setup process, the SQL Server CE Server Tools installer optionally launches the SQL Server CE Virtual Directory Creation Wizard, a component of the SQL Server CE Connectivity Management utility. For more information about the SQL Server CE Connectivity Management utility, see Configuring Security for Connectivity.

Support for Multilingual Environments

SQL Server CE Server Tools includes localized Microsoft Data Access Components (MDAC) files that affect how setup screens and error messages are displayed. The language of SQL Server CE Setup determines the language of the MDAC software in SQL Server CE Server Tools. For other language-related issues, see Ensuring Proper ANSI to Unicode Conversions.


Installing SQL Server CE on a SQL Server System

Using Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) in a Microsoft SQL Server environment does not require the installation of any components on the SQL Server system. However, if you are using remote data access (RDA) or replication, it is important to install (on the computer running IIS) the version of the SQL Server CE Server Tools appropriate for the version of SQL Server you are using. For more information about SQL Server CE Server Tools, see Installing SQL Server CE on an IIS System.

See Also

Hardware and Software Requirements


Using SQL Server CE Relay with an ActiveSync System

If you use Microsoft® ActiveSync® 3.1 with a serial, infrared (IR), or USB connection to communicate between a Microsoft Windows® CE-based device and an instance of Microsoft SQL Server™ using Microsoft Internet Information Services (IIS) through the network connection of a desktop computer, you must install SQL Server CE Relay on the computer running ActiveSync. This is required both during application development and during application deployment after development has been completed if the Windows CE-based devices do not have integrated network connectivity.

SQL Server CE Relay is installed automatically on the development computer when you install the development tools.

Important Microsoft Windows Powered Pocket PC 2002-based devices using ActiveSync 3.5 do not require SQL Server CE Relay, because this configuration supports Ethernet connectivity to and from the device through the desktop computer.

To set up SQL Server CE Relay on the computer running ActiveSync

  1. On the existing development computer, if you are using Microsoft eMbedded Visual Tools, navigate to the \Program Files\Microsoft SQL Server CE 2.0\Redist\Relay folder. If you are using Microsoft Visual Studio® .NET, navigate to the \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000 folder.
  2. Copy Sscerelay.exe to any directory on the computer running ActiveSync.
  3. Configure SQL Server CE Relay. For more information, see Using SQL Server CE Relay.

To remove SQL Server CE Relay from the computer running ActiveSync

SQL Server CE Relay is not installed using the setup process; therefore, you cannot use Control Panel to add or remove it. You must remove Relay using a command prompt.

  1. At the MS-DOS® command prompt, use the CD command to navigate to the location where you previously copied and configured SQL Server CE Relay on the computer running ActiveSync. For example, type:
    cd c:\Program Files\Microsoft SQL Server CE 2.0\Relay
  2. To unregister SQL Server CE Relay, type:
    Sscerelay /unregister
  3. To delete Sscerelay.exe, type:
    del sscerelay.exe


Installing SQL Server CE Query Analyzer

SQL Server CE Query Analyzer is installed automatically if you are using Microsoft® Visual Studio® .NET, but requires manual installation if you are using Microsoft eMbedded Visual Tools.

Visual Studio .NET

If you install Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) with Visual Studio .NET, SQL Server CE Query Analyzer (Isqlw20.exe) is placed on the development computer in C:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\platform\processor.

SQL Server CE Query Analyzer is automatically installed on the device the first time you deploy an application (by selecting Start from the Debug menu in Visual Studio .NET) that references the System.Data.SqlServerCe namespace. The default installation location is \Program Files\SQLCE2.0. A shortcut to SQL Server CE Query Analyzer also appears on the Start menu of the device.

You can manually copy SQL Server CE Query Analyzer to the device by copying and extracting the following cab files from C:\Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE to the root directory of the device: Netcf.cjk.platform.processor.cab, Sqlce.platform.processor.cab, and Sqlce.dev.platform.processor.cab. A shortcut to SQL Server CE Query Analyzer appears in the Start menu of the device.

eMbedded Visual Tools

If you install SQL Server CE with eMbedded Visual Tools, SQL Server CE Query Analyzer (Isqlw20.exe) is placed on the development computer in C:\Program Files\Microsoft SQL Server CE 2.0\Device\processor family\processor type.

If SQL Server CE is not installed on the device:

  1. Create a blank eMbedded Visual Basic project and include SQL Server CE in the project. On the Project menu, click References, Microsoft CE SQL Server Control 2.0, and then Microsoft CE ADO Control 3.1.
  2. Copy Ssce20.dll, Ssceca20.dll, Ssceerror20en.dll, Msdaeren.dll, Adoce31.dll, and Adoceoledb31.dll to the \Windows directory. For more information, see "Manual Installation Process" in Installing SQL Server CE on a Device Using eMbedded Visual Tools.
  3. After you have deployed an application referencing SQL Server CE or have manually installed the SQL Server CE files listed above, copy Isqlw20.exe to \Windows\Start Menu for Pocket PC devices or \Windows\Desktop for Handheld PC 2000 devices.

To start SQL Server CE Query Analyzer, either select the application from the Start menu or tap the icon on the desktop.

See Also

Using SQL Server CE Query Analyzer


Configuring Security for Connectivity

After you install the necessary systems for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), you must configure the appropriate security and connectivity options before any data can be exchanged by using replication or remote data access (RDA). The topics in this section describe the security and connectivity requirements for SQL Server CE.

Topic | Description
Planning for Security | Provides general information about security.
Configuring Connectivity Support in IIS | Provides information about configuring connectivity support for replication and remote data access, including NTFS permissions requirements and advanced security configurations.
Using SQL Server CE Relay | Provides information about installing and configuring SQL Server CE Relay when you are using Microsoft ActiveSync® 3.1.

After connectivity support for replication and remote data access are properly configured, you are ready to use these connectivity solutions by enabling the functionality in a Windows CE-based application. For more information, see Managing Connectivity and Building Applications.


Planning for Security

Connectivity between Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) and an instance of Microsoft SQL Server relies entirely upon properly configuring the security models for both Microsoft Internet Information Services (IIS) and SQL Server.

In the SQL Server CE connectivity scenario, a Windows CE-based application initiates synchronization by invoking the appropriate SQL Server CE connectivity solution: either replication or remote data access (RDA). Before accessing a SQL Server database using replication or RDA through HTTP, you must set up an IIS virtual directory that contains the SQL Server CE Server Agent and configure the appropriate NTFS permissions. Configuring IIS authentication and authorization specifies the clients that can invoke the SQL Server CE Server Agent. Implementing this layer of security controls the clients that can perform database synchronization or remote database access.

Note IIS can be configured to use Secure Sockets Layer (SSL) encryption. This safeguards the data sent between the Windows CE-based device and IIS when database synchronization or remote database access is performed. For more information, see Configuring SSL Encryption.

After the SQL Server CE Server Agent is invoked, it connects to an instance of SQL Server. SQL Server authentication and authorization can be configured to control access to SQL Server or SQL Server publications.

The following topics describe how IIS and SQL Server are configured to support security for the SQL Server CE connectivity solutions (replication and RDA):

  • IIS Security
  • SQL Server Security

For more information about SQL Server CE database security, see Using the SQL Server CE Database Security Features.


IIS Security

This topic describes how Microsoft® SQL Server® 2000 Windows® CE Edition (SQL Server CE) relies on:

  • IIS Authentication
  • IIS Authorization
  • IIS Encryption
IIS Authentication

When you configure the SQL Server CE Server Agent, you specify whether clients must perform Microsoft Internet Information Services (IIS) authentication when they connect to the SQL Server CE Server Agent. There are three forms of IIS authentication:

  • Anonymous Access
  • Basic Authentication
  • Integrated Windows Authentication

It is expected that most Internet applications will use Basic authentication and Secure Sockets Layer (SSL) encryption.

Anonymous Access

With Anonymous access, IIS does not perform client authentication. All work that the SQL Server CE Server Agent performs on behalf of the client is performed under the identity of the Internet Guest Account. By default, the Internet Guest Account is IUSR_computername, but you can designate some other Windows user account as the Internet Guest Account.

Basic Authentication

With Basic authentication, the SQL Server CE client must supply a valid Windows account user name and password. IIS attempts to log in by using the client-supplied user name and password. If the login attempt succeeds, all work that the SQL Server CE Server Agent performs is performed under the identity of the specified Windows user account. If the login attempt fails, the request from the client is rejected. Basic authentication can be used for both Internet and intranet applications. Basic authentication requires that each client have a valid Windows account with a corresponding user name and password.

Important 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. To safeguard the user password, Secure Sockets Layer (SSL) encryption should always be used whenever Basic authentication is used. For more information, see Configuring SSL Encryption.

Integrated Windows Authentication

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 performed under the identity of the Windows user account. If the login attempt fails, the client synchronization request is rejected. Integrated Windows authentication 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 authentication 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.

Note Because Microsoft Windows CE 3.0 does not support Digest Authentication, Kerberos Authentication, and Client Certificate Authentication, SQL Server CE connectivity solutions do not support these forms of authentication.

IIS Authorization

After the IIS client is authenticated, IIS authorization determines whether the client can invoke the SQL Server CE Server Agent. You control who can perform SQL Server CE connectivity by controlling the clients that 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 that are configured. You can configure the Web server to prevent specific computers, groups of computers, or entire networks from accessing the SQL Server CE Server Agent. When a client initially tries to access the 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, the synchronization request from the client is rejected with the message: "403 Access Forbidden".
  • If IIS is configured to require authentication, IIS checks whether the client has a valid Windows user account as described in IIS Authentication. If the user account is not valid, the client's synchronization request is rejected with the message: "403 Access Forbidden".
  • IIS next checks the Web permissions. This IIS security check is not relevant for SQL Server CE connectivity solutions.
  • IIS then checks NTFS permissions for the SQL Server CE Server Agent to ensure the connecting user has appropriate permissions. For information about configuring the NTFS permissions required for SQL Server CE applications using replication or RDA, see Configuring Connectivity Support in IIS and Configuring IIS and NTFS Permissions Manually.

    Note Although IIS can also be used with a File Allocation Table (FAT) file system, it is strongly recommended that you use NTFS. NTFS allows use of access control lists (ACLs) for granting or denying access to the SQL Server CE Server Agent and the input and output message files on the IIS system.

IIS Encryption

When you configure the SQL Server CE Server Agent, 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. For more information, see Configuring SSL Encryption.

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 RDA only: If the application specifies an OLEDBConnectionString parameter that contains 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.

  • For replication only: If either the SQL Server Publisher or Distributor relies on SQL Server authentication.

    The Distributor is using SQL Server authentication if the DistributorSecurityMode property specifies DB_AUTHENTICATION. The 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.

See Also

Configuring IP Address and Domain Name Restrictions


SQL Server Security

This topic describes how Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) works with:

  • SQL Server Authentication
  • SQL Server Authorization
SQL Server Authentication

SQL Server supports two forms of authentication:

  • Windows Authentication
  • SQL Server Authentication
Windows Authentication

When Windows authentication is used to connect to SQL Server, Microsoft 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 remote data access (RDA), the SQL Server CE Server Agent acts as the database client, running under the identity of a Windows user account:

  • When IIS is configured to use Anonymous access, the SQL Server CE Server Agent runs under the identity of the Internet Guest Account, by default IUSR_computername. If you configure another Windows user account as the IIS anonymous user account, the SQL Server CE Server Agent runs under the identity of that account.
  • When IIS is configured to use Basic authentication, the SQL Server CE Server Agent 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 Integrated Windows authentication, the SQL Server CE Server Agent runs 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-based application must supply the appropriate SQL Server login and password when connecting to SQL Server using replication or remote data access. The SQL Server CE Client Agent conveys the login and password to the SQL Server CE Server Agent. The SQL Server CE Server Agent invokes SQL Server using the login and password specified by the client.

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 that it wants to access. The user account is used to control access to the tables, views, stored procedures, and so on, in that database. The activities that a client can perform are controlled by the permissions applied to the user account through which the client gained access to the database.

For RDA only: You can precisely control the database operations that RDA clients can perform by 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 Configuring the Publication Access List.

When you create a publication, the location of the snapshot folder is specified. The snapshot folder is used when a subscription is initially created or reinitialized. If the computer running SQL Server is located on a NTFS system, the appropriate NTFS permissions must be specified. For more information, see Configuring the Snapshot Folder.

When you create a publication, you can use the Check Permissions option to provide an enhanced level of security to the 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 Configuring the Check Permissions Option.


Configuring Connectivity Support in IIS

Before you can access a database in Microsoft® SQL Server™ by using replication or remote data access (RDA) through HTTP, you must set up a virtual directory and configure the appropriate NTFS permissions. Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) provides the SQL Server CE Connectivity Management utility to create and manage virtual directories and NTFS permissions.

The following topics in this section describe using the SQL Server CE Connectivity Management utility for connectivity support and setting advanced configuration options:

  • Using Connectivity Tools
  • Advanced Security Configurations


Using Connectivity Tools

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides the SQL Server CE Connectivity Management utility to configure Microsoft Internet Information Services (IIS) and setup appropriate NTFS permissions. The SQL Server CE Connectivity Management utility contains the SQL Server CE Virtual Directory Creation Wizard for creating new virtual directories and a management console for managing existing virtual directories. The SQL Server CE Connectivity Management utility is a standard Microsoft Management Console (MMC) snap-in.

The SQL Server CE Connectivity Management utility and the SQL Server CE Virtual Directory Creation Wizard are installed automatically either by selecting the Server Tools option during SQL Server CE setup or by running the Server Tools self-extracting executable on the computer running IIS. For more information about installing Server Tools, see Installing SQL Server CE on an IIS System.

Note At the end of the SQL Server CE setup process, you can choose to launch the SQL Server CE Virtual Directory Creation Wizard immediately.

To start the SQL Server CE Connectivity Management utility on the computer running IIS

  • On the Start menu, point to Programs, Microsoft SQL Server CE, and then click Configure Connectivity Support in IIS.

Or

  • Right-click the My Computer icon, and then click Manage. In the Computer Management window, expand Services and Applications, and then click Microsoft SQL Server CE.

To start the SQL Server CE Virtual Directory Creation Wizard

If you are configuring connectivity for the first time and did not run the SQL Server CE Virtual Directory Creation Wizard at the end of setup, you can start the wizard from the SQL Server CE Connectivity Management utility.

  • In the right pane of the utility, double-click Create a Virtual Directory. For more information, see Creating a New Virtual Directory.

Important IIS must be installed and running to start the SQL Server CE Connectivity Management utility or the SQL Server CE Virtual Directory Creation Wizard.

For information about using the SQL Server CE Connectivity Management utility to manage existing virtual directories, see Modifying an Existing Virtual Directory.

See Also

Planning for Security

Managing Connectivity


Creating a New Virtual Directory

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) relies on Microsoft Internet Information Services (IIS) virtual directories to access data from a database in Microsoft SQL Server. To create a virtual directory, SQL Server CE provides the SQL Server CE Virtual Directory Creation Wizard, which contains the following pages to guide you through the process:

  • Virtual Directory Alias and Content Folder
  • Virtual Directory Authentication
  • NTFS Permissions: User
  • NTFS Permissions: Computer Running SQL Server
  • NTFS Permissions: Snapshot Folder

See Also

Planning for Security

Managing Connectivity


Virtual Directory Alias and Content Folder

This page of the SQL Server CE Virtual Directory Creation Wizard allows you to create an alias and content folder for the virtual directory.

Virtual Directory Alias

For quick reference, you can create an alias for the virtual directory. It is recommended that you use the same naming conventions that you use for a folder.

The name of the server running Microsoft® Internet Information Services (IIS), the virtual directory, and the SQL Server CE Server Agent (Sscesa20.dll) must be specified as part of the InternetURL property for connectivity. For example, the following URL accesses a SQL Server CE Server Agent for replication or remote data access (RDA): http://www.northwindtraders.com/sqlce/sscesa20.dll.

Virtual Directory Content Folder

A content folder is required for a virtual directory. By default, the wizard points to the location in which the SQL Server CE Server Agent is installed. You can specify an alternate location on disk for better disk space management, although a copy of the SQL Server CE Server Agent must be located in that location. If you do specify an alternate location, the wizard can copy and register the SQL Server CE Server Agent to the new location. All temporary files for data transfer to and from the instance of Microsoft SQL Server™ will reside in this location.

After the wizard successfully completes, HTTP Execute permissions on the content folder will be added.

See Also

Virtual Directory Recommendations and Default Settings


Virtual Directory Authentication

After you specify the virtual directory alias, create the virtual directory content folder and set the appropriate HTTP permissions. You must set access rights (authentication) to that folder. The SQL Server CE Virtual Directory Creation Wizard provides three authentication options:

  • Anonymous access
  • Basic authentication
  • Integrated Windows authentication

For more information about these options, see IIS Security.

Additional Authentication Guidelines
  • If you specify Anonymous access and the instances of Microsoft® Internet Information Services (IIS) and Microsoft SQL Server™ are located on different computers, 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 local account for a computer.

    Note When Anonymous access is selected, the anonymous user (by default computername\IUSR_computername) is automatically provided the appropriate NTFS permission rights to the computer running IIS. Read and Write access permissions are set on the content folder and Read & Execute access permission is set on the SQL Server CE Server Agent (Sscesa20.dll).

  • If you specify Basic authentication, you should also use IIS to specify Secure Sockets Layer (SSL) encryption to avoid transmitting the password of the user across the network in unencrypted form.

    Important To safeguard the user password, SSL encryption should always be used whenever Basic authentication is used. For more information, see Configuring SSL Encryption.

  • If you specify Integrated Windows authentication, you 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.

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions: User

After Microsoft® Internet Information Services (IIS) authenticates the client, IIS checks whether the client is authorized to begin replication or remote data access (RDA). You control which clients can invoke replication or RDA by setting NTFS permissions on the SQL Server CE Server Agent and content folder. Proper configuration of permissions is crucial to prevent unauthorized access to Microsoft SQL Server™ by using replication or RDA.

You must add NTFS permissions if either or both of the following states exist:

  • The computer running IIS uses NTFS.
  • The SQL Server CE-based application uses replication; and the snapshot folder, usually located on the computer running SQL Server, exists on an NTFS drive partition.

When you create a new virtual directory, the SQL Server CE Virtual Directory Creation Wizard helps you configure NTFS permissions. In addition, to edit an existing directory, you can use the NTFS Permissions tab of the SQL Server CE Connectivity Management utility to add or modify NTFS permissions.

Note When using the SQL Server CE Virtual Directory Creation Wizard, after you specify the user, the appropriate NTFS permissions are set automatically for the computer running IIS.

Additional Permissions Guidelines
  • When Basic or Integrated Windows authentication is selected, you must specify the name of the user that requires NTFS permissions.
  • When Anonymous access is selected, the Internet Guest Account (by default computername\IUSR_computername) is used automatically.

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions: Computer Running SQL Server

If your application uses replication, you must set NTFS Read permission on the actual snapshot folder and the share. Most commonly, the snapshot folder is located on the computer running Microsoft® SQL Server™.

Select the check box on this screen of the SQL Server CE Virtual Directory Creation Wizard or the NTFS Permissions Wizard, if either of these states exists:

  • A snapshot share has already been created and specified during the configuration of the SQL Server Distributor.
  • The snapshot share has been created and will be specified when the SQL Server Distributor is configured.

    Note A folder or share cannot be created using the SQL Server CE Connectivity Management utility or the SQL Server CE Virtual Directory Creation Wizard.

The configuration step to give the appropriate user Read permission to the snapshot folder and share can be completed at a later time by using the NTFS Permissions Wizard. To start the NTFS Permissions Wizard, on the NTFS Permissions tab of the SQL Server CE Connectivity Management utility, click Add/Modify NTFS Permissions for User, or use Microsoft Windows® Explorer.

For more information about snapshot folders, see Configuring the Snapshot Folder.

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions: Snapshot Folder

The snapshot share must be specified as a Universal Naming Convention (UNC) path. Depending on the Virtual Directory Authentication that has been selected, the appropriate Microsoft® Windows® user account requires Read permission on the snapshot share and underlined folder. For more information, see NTFS Permissions: User. The SQL Server CE Virtual Directory Creation Wizard and the SQL Server CE Connectivity Management utility can configure only one user at a time. If you want to configure multiple users at the same time, use Windows Explorer.

Note When using the SQL Server CE Virtual Directory Creation Wizard, after you specify the snapshot folder share and click Finish, the appropriate NTFS permission are automatically set for the snapshot folder.

For more information about snapshot folders, see Configuring the Snapshot Folder.

See Also

Virtual Directory Recommendations and Default Settings


Modifying an Existing Virtual Directory

You can use the SQL Server CE Connectivity Management utility to modify an existing virtual directory. To modify an existing configuration, select the appropriate virtual directory from the list in the left pane of the SQL Server CE Connectivity Management utility, and then modify the settings shown in the right pane by using the following tabs:

  • Virtual Directory Content Folder (HTTP Content Folder Tab)
  • Virtual Directory Authentication (HTTP Authentication Tab)
  • NTFS Permissions (NTFS Permissions Tab)

See Also

Virtual Directory Recommendations and Default Settings

Advanced Security Configurations


Virtual Directory Content Folder (HTTP Content Folder Tab)

Use this tab of the SQL Server CE Connectivity Management utility to modify the content folder associated with an existing virtual directory and/or to alter the HTTP permissions to the folder. Enter the full path to the content folder associated with the virtual directory (for example, C:\Program Files\Microsoft SQL Server CE 2.0\Server) or click Browse to find the folder on the local computer. Specify the HTTP permissions to the folder. Execute permission is required by SQL Server CE. It is not advised to add Write permission to this location.

If the content folder is changed, you must run the NTFS Permissions Wizard to set NTFS permissions on the new location. To start the NTFS Permission Wizard, on the NTFS Permissions tab of the SQL Server CE Connectivity Management utility, click Add/Modify NTFS Permissions for User.

For more information, see Virtual Directory Alias and Content Folder.

See Also

Virtual Directory Recommendations and Default Settings


Virtual Directory Authentication (HTTP Authentication Tab)

Use this tab of the SQL Server CE Connectivity Management utility to modify HTTP authentication of an existing virtual directory. If the HTTP authentication is changed, you must run the NTFS Permissions Wizard to set NTFS permissions for the new user. To start the NTFS Permissions Wizard, on the NTFS Permissions tab of the SQL Server CE Connectivity Management utility, click Add/Modify NTFS Permissions for User.

The SQL Server CE Connectivity Management utility provides three authentication options:

  • Anonymous access
  • Basic authentication
  • Integrated Windows authentication

Important By default, Basic authentication passes the user name and password across the network. To safeguard the user password, Secure Sockets Layer (SSL) encryption should always be used whenever Basic authentication is used. For more information, see Configuring SSL Encryption.

For more information about these options, see Virtual Directory Authentication and IIS Security.

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions (NTFS Permissions Tab)

Use this tab of the SQL Server CE Connectivity Management utility to start the NTFS Permissions Wizard. Use the NTFS Permissions Wizard to modify NTFS Permissions on the computer running Microsoft® Internet Information Services (IIS) or the computer running Microsoft SQL Server™. The NTFS Permissions Wizards contains the following pages:

  • NTFS Permissions: User

    This page in the NTFS Permissions Wizard is functionally identical to the NTFS Permissions: User page in the SQL Server CE Virtual Directory Creation Wizard.

  • NTFS Permissions: Computer Running IIS
  • NTFS Permissions: Computer Running SQL Server

    This page in the NTFS Permissions Wizard is functionally identical to the NTFS Permissions: Computer Running SQL Server page in the SQL Server CE Virtual Directory Creation Wizard.

  • NTFS Permissions: Snapshot Folder

    This page in the NTFS Permissions Wizard is functionally identical to the NTFS Permissions: Snapshot Folder page SQL Server CE Virtual Directory Creation Wizard.

  • NTFS Permissions: Snapshot Folder Access

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions: Computer Running IIS

After SQL Server CE Server Agent (Sscesa20.dll) is invoked, it attempts to create, read, write, and delete input and output replication or remote data access (RDA) message files. These message files are placed on the computer running Microsoft Internet Information Services (IIS) in the content folder that you specified when you configured the IIS virtual directory. This is the same folder that contains SQL Server CE Server Agent (Sscesa20.dll). You control access to the folder and the SQL Server CE Server Agent by assigning NTFS permissions to that directory and file.

Read and Write access permissions are required on the content folder (also known as the temporary file location for the input and output message files), and Read & Execute access permission is required on the SQL Server CE Server Agent (Sscesa20.dll).

See Also

Virtual Directory Recommendations and Default Settings


NTFS Permissions: Snapshot Folder Access

Depending on the Virtual Directory Authentication that is selected, the appropriate Microsoft® Windows® user account requires Read permission on the snapshot share specified and the underlying snapshot folder. For more information, see NTFS Permissions: User

For more information about snapshot folders, see Configuring the Snapshot Folder.

See Also

Virtual Directory Recommendations and Default Settings


Virtual Directory Recommendations and Default Settings

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) relies on Microsoft Internet Information Services (IIS) virtual directories to access data from a database in Microsoft SQL Server.

Virtual Directory Recommendations

It is recommended that you create a virtual directory for each application that requires data access, whether you are implementing replication or remote data access (RDA). Using the SQL Server CE Virtual Directory Creation Wizard, you can create individual virtual directories for each Windows CE-based application.

  • IIS authentication and authorization is controlled at the virtual directory level. By creating a virtual directory for each SQL Server CE publication or for different groups of RDA clients, you can establish the exact 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 database synchronization or RDA operations are performed. By configuring an IIS virtual directory for each publication or different groups of RDA clients, you increase the number of worker threads and, therefore, the number of replication operations or clients that can be active concurrently.

It is also recommended that you create one NTFS or FAT content folder for each IIS virtual directory. This content folder contains the SQL Server CE Server Agent (Sscesa20.dll) and the temporary input and output message files that SQL Server CE creates during synchronization and RDA operations.

Important 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 the clients that can access SQL Server CE replication or RDA.

Virtual Directory Default Settings Using Connectivity Tools

The SQL Server CE Virtual Directory Creation Wizard configures a number of default settings to ensure minimum SQL Server CE requirements. In addition, to the default settings described in the configuration topics, the following are also set on the virtual directory:

  • The application protection mode is set to Medium (Pooled).
  • Script Source Access option is not supported and, therefore, is not enabled.

If you want to change any of the default settings set by the wizard, see Modifying an Existing Virtual Directory. If you require more advanced configuration options, see Advanced Security Configurations and the IIS documentation.


Advanced Security Configurations

The following topics provide information about manually configuring connectivity support and additional security configuration options that are not configured using the SQL Server CE Connectivity Management utility or the SQL Server CE Virtual Directory Creation Wizard. These options are not required by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) but may be required for your specific work environment.

  • Configuring IIS and NTFS Permissions Manually
  • Configuring SSL Encryption
  • Configuring IP Address and Domain Name Restrictions
  • Configuring IIS Security Auditing


Configuring IIS and NTFS Permissions Manually

The connectivity support and security options for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) that are set by using the SQL Server CE Virtual Directory Creation Wizard can be configured manually. The following is a brief summary of the minimum configuration sets that are required to use replication or remote data access (RDA).

Configuring Microsoft® Internet Information Services (IIS) for either replication or RDA involves the following steps:

  1. Create a virtual directory using IIS:
    1. Specify an alias name for the virtual directory.
    2. Specify the location for the content folder for the virtual directory. A copy of the SQL Server CE Server Agent (Sscesa20.dll) must reside in this directory. By default, the SQL Server CE Server Agent is installed in C:\Program Files\Microsoft SQL Server CE 2.0\Server.

      Note The name of the computer running IIS, the virtual directory, and the SQL Server CE Server Agent (Sscesa20.dll) must be specified as part of the InternetURL property for connectivity. For example, the following URL accesses SQL Server CE Server Agent for replication or RDA: http://www.northwindtraders.com/sqlce/sscesa20.dll.

    3. Specify the Execute access permission for the virtual directory.

      For more information, see Virtual Directory Alias and Content Folder.

  2. Configure IIS authentication using IIS. Edit the properties of the virtual directory created in Step 1. SQL Server CE supports provides three authentication options:
    • Anonymous access
    • Basic authentication
    • Integrated Windows authentication

    For more information, see Virtual Directory Authentication.

  3. Configure IIS authorization using Windows Explorer.

    Note If the computer running IIS has a FAT file system, you can skip this step. SQL Server CE replication or RDA works with a FAT file system, but it is not secure. It is recommended that you use NTFS.

    1. Configure directory authorization by navigating to the content folder you specified when you configured the IIS virtual directory, and then add the following NTFS permission on the folder.
      User | Required permissions
      For Anonymous access, grant rights to the computername\IUSR_computername or the configured IIS anonymous user account. | Read and Write
      For Basic or Integrated Windows authentication, grant rights to the user or group of the client. | Read and Write
    2. Configure SQL Server CE Server Agent authorization by navigating to the content folder you specified when you configured the IIS virtual directory, and then add the following NTFS permission on Sscesa20.dll.
      User | Required permissions
      For Anonymous access, grant rights to the computername\IUSR_computername or the configured IIS anonymous user account | Read & Execute
      For Basic or Integrated Windows authentication, grant rights to the user or group of the client | Read & Execute
    3. Configure the SQL Server snapshot folder if you are using replication. For more information, see Configuring the Snapshot Folder.

See Also

Planning for Security

Using Connectivity Tools

Configuring the Snapshot Folder


Configuring SSL Encryption

Secure Sockets Layer (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 Microsoft® Windows® CE-based client and Microsoft Internet Information Services (IIS) use the session key to encrypt and decrypt the data they send to one another.

Replication and remote data access (RDA) do not require encryption; however, there are circumstances when you should use it. For more information, see Planning for Security.

Windows CE maintains a database of trusted Certificate Authorities (CA). 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 stand-alone CA, this root certificate is not present in the Windows CE Certificate Authority database. As a result, Windows CE does not trust this IIS server certificate. If you want to use server certificates that you issue yourself, you must either certify your stand-alone CA through one of the trusted certificate authorities or add your stand-alone CA root certificate to the Windows CE Certificate Authority database.

The SSL features in IIS cannot be used until you obtain and assign a server certificate to the computer running IIS.

SSL Configuration Process

Configuring SSL encryption is a multistep process that involves:

  1. Requesting a server certificate for the computer running IIS. If the IIS server already has a server certificate, you can skip to Step 4.
  2. Obtaining a server certificate from a certificate authority. For more information about obtaining server certificates, see Windows online Help.
  3. Installing the newly issued server certificate into IIS.
  4. Enabling SSL encryption.
  5. Updating the database of trusted Certificate Authority on each of the Windows CE-based devices so they recognize the server certificate as authentic.

For more information about the trusted Certificate Authorities maintained by Windows CE, see the Microsoft Knowledge Base article "List and Add Schannel Root Certificates (Q290288)" at this Microsoft Web site.


Updating the Database of Trusted Certificate Authorities on a Windows CE-based Device

After saving the root certificate of the stand-alone certificate authority to the *.cer file, you must install the root certificate in the Windows CE Certificate Authority database on the Microsoft® Windows® CE-based device.

To install the root certificate on the Windows CE-based device

  1. From the SQL Server CE installation directory (by default: Program Files\Microsoft SQL Server CE 2.0\Device\processor family\processor type), copy the root certificate utility program (Rootcert.exe) that matches the processor type of the Window CE-based device to the \Windows directory on the device.
  2. Copy your root certificate to the root directory of the Windows CE-based device.
  3. From File Explorer, run Rootcert.exe.

Rootcert.exe does the following:

  1. Opens and reads the root certificate file contained in the root directory of the Windows CE-based device.
  2. Creates the registry key HKLM\Comm\SecurityProviders\SCHANNEL\CAs if this key does not already exist in the registry on the Windows CE-based device.
  3. Creates the registry key HKLM\Comm\SecurityProviders\SCHANNEL\CAs\filename, where filename is the name of the root certificate file.
  4. 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.
  5. Displays the message: "Root certificate installed successfully."

After you update the Windows CE registry, start the application that is using SQL Server CE replication or remote data access (RDA). Windows CE uses the root certificate the next time Secure Sockets Layer (SSL) is invoked.

If you want to use server certificates that you issue yourself, the following limitations apply when requesting a server certificate:

  • Naming limitations

    This limitation exists because Windows CE 3.0 cannot accept server certificates containing Unicode character strings. For more information, see the Microsoft Knowledge Base article "How Special Characters in the Name Field Effect Certificates (Q216947)" at this Microsoft Web site.

  • Windows CE-based devices running Windows CE 3.0 do not recognize IIS server certificates signed by using either the MD4 or RSA/SHA1 signature algorithms.

    Windows CE-based devices reject such certificates with the error: "ERROR_INTERNET_SECURITY_CHANNEL_ERROR". To be acceptable to a Windows CE-based device, an IIS server certificate must be signed using either the MD2 or MD5 signature algorithm.


Configuring IP Address and Domain Name Restrictions

You can use Microsoft® Internet Information Services (IIS) IP address and domain name restrictions to grant or deny specific computers, groups of computers, or domains access to the 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. For more information, see the IIS documentation.


Configuring IIS Security Auditing

You can monitor the security of replication and remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) by using the security auditing mechanisms built into Microsoft Windows and Microsoft Internet Information Services (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. For more information, see the IIS documentation.


Using SQL Server CE Relay

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) extends enterprise data to the Windows CE-based mobile device. By using merge replication or remote data access (RDA), you can share data with users in the field even when there is no integrated network capability or when a network card cannot be used. SQL Server CE Relay allows communication to operate bidirectionally between a mobile device and the server by using the network connection on a desktop computer.

Important SQL Server CE Relay is not required for Microsoft Windows Powered Pocket PC 2002-based devices that are connected to desktop computers running Microsoft ActiveSync® 3.5. The ActiveSync 3.5 connection setting Allow network (Ethernet) and Remote Access Service (RAS) server connections with this desktop computer is set by default and supports Secure Sockets Layer (SSL) encryption and Integrated Windows authentication connections.

The benefits of using SQL Server CE Relay include:

  • Lower computing costs.

    If the Windows CE-based devices contain modem cards, you might have to pay for their dial-in connections to their servers. Being able to synchronize data in SQL Server CE while the Windows CE-based device is cradled and connected to the server can save on overall computing costs.

  • Connection capability in unfavorable wireless situations.

    If wireless coverage in an office is limited because of concrete walls in the building or some other interference, you can use any configured desktop to synchronize database data with SQL Server.

  • Connection capability when wireless network cards are not permitted because of radio transmission restrictions.


How SQL Server CE Relay Works

SQL Server CE Relay allows the USB, serial, or infrared (IR) connections through desktop computers to serve as a conduit for synchronization to an instance of Microsoft® SQL Server™ by using Microsoft Internet Information Services (IIS). The following illustration shows how a Pocket PC 2000-based device connects to a server computer through a Microsoft ActiveSync® desktop connection.

Illustration showing how Relay on a desktop computer synchronizes information traveling to and from a mobile device and an instance of SQL Server.

When the client code on the Microsoft Windows® CE-based device sets the InternetProxyServer property of the SQL Server CE ActiveX® control to ppp_peer:nn (where nn is a specified listening client port number on a desktop computer), ActiveSync recognizes the ppp_peer command, and the requests sent to the desktop computer appear on this designated client port. Relay is listening on the same client port; it accepts the request from the mobile device and sends the request to a port on a preconfigured server (either an IIS server or a proxy server). This process works identically but in reverse when the responding synchronization data comes back from the computer that is running SQL Server.


Planning for SQL Server CE Relay

When you are planning to implement SQL Server CE Relay, consider the following background information:

  • Relay works on desktop computers that are running Microsoft® Windows® 98 SE, Microsoft Windows ME, Microsoft Windows NT® 4.0 with Service Pack 6 or later, Microsoft Windows 2000, and Microsoft Windows XP.
  • Relay uses the peer point-to-point protocol (ppp_peer), a tunneling protocol that encapsulates Point-to-Point Protocol frames into IP datagrams for transmission over an IP-based network, in Microsoft operating systems. This means that the desktop computer functions as a proxy that can connect the mobile device to any server to which the desktop computer is connected. SQL Server CE Relay is not a true proxy server because it cannot encrypt data, but you still have firewall support if firewall support exists at the desktop computer.
  • SQL Server CE Relay requires Microsoft ActiveSync® 3.1 or later installed on the desktop computer. ActiveSync enables the ability to use the serial, infrared (IR), or USB connection (that is, the ppp_peer command can be interpreted as part of the serial, IR, or USB connection) between the mobile device that is running Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) and the desktop computer. The partnership can be a guest connection.
  • Relay does not support Secure Sockets Layer (SSL) encryption or Integrated Windows authentication. If you require SSL encryption, you must upgrade to Pocket PC 2002 and ActiveSync 3.5.

Before you install SQL Server CE Relay on the desktop computer, be sure that the following are installed or configured on this computer:

  • SQL Server CE Server Tools is installed.
  • The SQL Server CE Server Agent is configured correctly on the computer running IIS.
  • SQL Server is configured correctly for either remote data access (RDA) or merge replication connectivity.

    Note It is assumed that you are familiar with at least one of the two types of connectivity that is supported by SQL Server CE (merge replication or remote data access).

  • Security is set up correctly for connectivity to SQL Server.

    Note For more information about configuring IIS and SQL Server for connectivity, see Planning for Security.


Installing and Configuring SQL Server CE Relay

For information about installing SQL Server CE Relay, see Using SQL Server CE Relay with an ActiveSync System. The following topics in this section describe the configuration options and requirements:

  • Configuring the Desktop Computer to Use SQL Server CE Relay
  • Configuring the Mobile Device to Use SQL Server CE Relay
  • SQL Server CE Relay Configuration Options


Configuring the Desktop Computer to Use SQL Server CE Relay

To configure the desktop computer to use SQL Server CE Relay, you must specify the following:

  • Client port number
  • Name of the destination server
  • Server port number

The client port and server port configurations are very important for Relay to function correctly.

Client Port Number

The client port number is the port on which the desktop computer listens for requests from the Microsoft® Windows® CE-based device. Specify this port number as the value for the /clientport option.

Name of Destination Server

The server name is the key to identifying where you want information from the desktop to be relayed. If you are using a proxy server, the value of /servername is the name of the proxy server computer. If you are not using a proxy server, the value of /servername is the name of the computer running Microsoft Internet Information Services (IIS) that you are using to synchronize with Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE). The name of the computer running IIS must be the same as the name that is specified in the InternetURL property on the mobile device.

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, although this is not a recommended procedure. For the synchronization to succeed, the virtual directory names and security access must be the same on both servers. If both servers are valid IIS servers, Relay sends the data to the server that is specified in its parameters. Synchronization can fail if the virtual directory or a server agent does not exist, or if either is not correctly configured. The synchronization succeeds if both servers are set up identically and each has access to the computer running SQL Server.

Server Port Number

Specify the port number for the server that is identified by the /servername option. This is the port number for the computer on which the Internet application is configured. For example, if a virtual directory for SQL Server CE Server Agent has been created in the Default Web Site in IIS, the default server port is 80. Specify the server port number as the value for the /serverport option.

The following list shows services and their associated ports:

  • HTTP over TCP/IP

    Web servers, such as IIS: port 80

  • HTTPS over TCP/IP

    HTTP over SSL for encrypting Web traffic: port 443

  • FTP over TCP/IP: FTP

    Port 21, port 20, and ports 1024-65535

  • SMTP over TCP/IP

    Simple Mail Transfer Protocol (SMTP), which is used by applications such as Microsoft Exchange Server: port 25.

Most other ports are available; check the services running on your system before you assign port numbers.

See Also

SQL Server CE Relay Configuration Options


Configuring the Mobile Device to Use SQL Server CE Relay

To start the process of relaying the information from the Microsoft® Windows® CE-based device through the desktop to Microsoft Internet Information Services (IIS) on the Internet or an intranet, you must set the InternetProxyServer property in the Microsoft ActiveX® control in the Microsoft SQL Server™ 2000 Windows CE-based application. Set this property to ppp_peer:nn, where nn is the client port number on the desktop computer. This number must be the same as the client port number that has been specified by /clientport on the desktop computer.

See Also

SQL Server CE Relay Configuration Options


SQL Server CE Relay Configuration Options

The following table lists and describes the options that determine how SQL Server CE Relay functions. These options and their associated values must be space delimited; however, the options can be specified in any order.

Option | Description
/clientport* | The port on the desktop computer to and from which the client (the Microsoft® Windows® CE-based device) reads and writes.
/servername* The name of either the computer that is running Microsoft Internet Information Services (IIS) or the proxy server to which Relay connects through the desktop computer. Using a proxy server allows the client more flexibility because the client can go to any server that the proxy server can reach.

If an IIS server is used, this value must be the same as the value that is specified in the InternetURL property in the Windows CE-based application.

The IP address of the respective server computer can also be used for specifying the server name. UNC paths are not accepted for specifying the server name, however.

For example, the following fails during synchronization:
/servername "\\myIISserver"

The following succeeds during synchronization:
/servername myIISserver
/serverport* | The port to and from which the server reads and writes. This is usually port 80.
/register | Registers Relay with Microsoft ActiveSync® connect and disconnect features.
/unregister | Unregisters Relay with ActiveSync connect and disconnect features.
/noui | Runs Relay without the icons appearing in the Windows taskbar.
/? Calls Help at the command prompt, which lists SQL Server CE Relay parameters.
/stop | Halts all instances of Relay that are running, whether they were started manually or automatically.

*This option must be specified with a value to run Relay.


Running SQL Server CE Relay

SQL Server CE Relay appears as an icon on the Microsoft® Windows® status bar whenever Relay is running. One icon appears for each instance of Relay. Different icons appear according to the function Relay is performing.

Icon | Description
Taskbar icon showing that information is traveling from the device running SQL Server CE to the desktop computer. | Information is traveling from the device that is running Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) to the desktop computer.
Taskbar icon showing that information is traveling from the desktop computer to the device running SQL Server CE. | Information is traveling from the desktop computer to the device that is running SQL Server CE.
Taskbar icon showing that information is traveling in both directions between the desktop computer and the device running SQL Server CE. | Information is traveling both ways between the desktop computer and the device that is running SQL Server CE.
Taskbar icon showing that Relay is active but no information is traveling between the desktop computer and the device running SQL Server CE. | Although SQL Server CE Relay is running, no information is traveling between the desktop computer and the device that is running SQL Server CE.

SQL Server CE Relay can be run in either of the following configurations:

  • Automatic
  • Manual

    In manual configuration, you can elect to run a single instance or multiple instances of Relay.

If SQL Server CE Relay is not configured correctly, an error is written to the errors text file (Sscerelay.log) on the desktop computer. This file is in the same folder from which Sscerelay.exe is run.


Registering SQL Server CE Relay with ActiveSync to Run Automatically

The preferred configuration for running SQL Server CE Relay is to register Relay with Microsoft® ActiveSync®. By registering Relay with ActiveSync, Relay automatically starts and stops whenever the connection between the device running Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) and ActiveSync is active. The client application can then synchronize data as necessary.

To register Relay with ActiveSync, configure Relay with the /register option. You only have to do this once, as long as the configuration parameters for the options /clientport, /servername, and /serverport do not change.

When you specify the /register option, two registry keys are created automatically within Windows CE Services:

  • One registry key is created under HKEY_LOCALMACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnConnect, with the string value name MicrosoftSSCERELAYAutoConnect. This key is set with string value data that is based on the parameters you specified when you configured Relay.
  • A second registry key is created under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows CE Services\AutoStartOnDisconnect, with the string value name MicrosoftSSCERELAYAutoDisconnect. This key is set when you specify the /Stop option.

    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.

When an ActiveSync connection is made, it starts Relay with the parameters that were specified when Relay was configured.

Important When the ActiveSync connection is broken, all instances of Relay stop.

For example, if the name of the computer running Microsoft Internet Information Services (IIS) or the name of the proxy server is CorpServer, the options to run Relay are entered at the command prompt as:

sscerelay /clientport 81 /servername CorpServer /serverport 80 /register

In the preceding example:

  • The mobile device posts requests to and listens for responses on port 81 of the desktop computer.
  • The desktop computer listens for requests from the client on port 81 and forwards them to port 80 of the server that is specified by the /servername option. The desktop computer then listens for responses from the server on port 81 and posts them to the client on port 81.
  • If the computer that is specified in the /servername option is an IIS server, its name must match the server name that is supplied in the InternetURL property of the Microsoft ActiveX® control on the mobile device. SQL Server CE Server Tools must be installed on the computer and the SQL Server CE Server Agent configured on it. If the computer that is specified in the /servername option is a proxy server, it does not require SQL Server CE Server Tools or the SQL Server CE Server Agent because it forwards requests to an appropriately configured computer running IIS (the one that is specified in the InternetURL property on the mobile device).
  • The /register option registers Relay to run every time an ActiveSync connection is made.

    Note The InternetProxyServer property must be set to ppp_peer:81 in the SQL Server CE ActiveX control on the Microsoft Windows CE-based device.

Use the /unregister option at the command prompt to unregister Relay from ActiveSync, as shown here:

sscerelay /unregister

This removes the registry keys from Windows CE Services.


Running a Single Instance of SQL Server CE Relay Manually

If SQL Server CE Relay is to be used infrequently, you can run the program from the command prompt each time it is needed, as long as the mobile device is connected to the desktop computer using Microsoft® ActiveSync®. When Relay is run from the command prompt without specifying the /register option, it starts immediately. For example, if the name of the computer running Microsoft Internet Information Services (IIS) or the name of the proxy server is CorpServer, the options to run Relay manually are entered at the command prompt as:

sscerelay /clientport 81 /servername CorpServer /serverport 80

When Relay is run manually, it also must be stopped manually. Use the /stop option at the command prompt to halt Relay, as shown here:

sscerelay /stop


Running Multiple Instances of SQL Server CE Relay Manually

When you run multiple instances of SQL Server CE Relay simultaneously, different client ports must be used. Because only one instance of Relay can be registered with Microsoft® ActiveSync®, you must configure Relay manually to run multiple instances. For example, you might have to run multiple instances of Relay if multiple server destinations are required. When two groups of applications are connecting to the same desktop computer for synchronization, one application might need to connect to ServerA, which is a computer running Microsoft Internet Information Services (IIS) on the intranet and, therefore, does not require a proxy server. The other application, on the other hand, might need to connect to ServerB, which is a computer running IIS on the Internet and, therefore, does require a proxy server. In this scenario, one client port number maps to ServerA and the other client port number maps to ServerB, which requires configuring two instances of Relay.

Note For computers running Microsoft Windows® 98 SE, the number of instances of Relay is limited to 20.

Using the /stop option at the command prompt halts all instances of Relay that are running.

Note Although you can configure multiple instances of SQL Server Relay on one computer, you can synchronize only one Microsoft Windows CE-based device at a time.


Managing Connectivity

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports two methods of connecting to and exchanging data with a Microsoft SQL Server database: remote data access (RDA) and merge replication.

Topic | Description
Using Remote Data Access | Provides background information about RDA.
Using Replication | Provides background information about replication.


Using Remote Data Access (RDA)

The following topics in this section provide information about using remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Topic | Description
Introducing RDA | Provides an overview of RDA, explains how RDA is used, and describes components of RDA.
Planning for RDA | Provides background information about RDA, including data access, limitations, and conflict resolution.
Implementing RDA | Describes how to configure Microsoft Internet Information Services (IIS) and SQL Server to support RDA.

For information about writing programs that use RDA, see Remote Data Access (RDA). For troubleshooting information, see Troubleshooting.


Introducing RDA

Remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides a simple way for a Microsoft Windows CE-based application to access (pull) data from a remote SQL Server database table and store that data in a local SQL Server CE database table. The application can then 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 application can later update (push) the changed records from the local table back to the SQL Server table.

Windows CE-based applications can also use RDA to submit SQL statements to be executed on a remote SQL Server database. For example, an application could submit SQL statements that insert, update, or delete records to a remote SQL Server table. Applications can invoke any SQL statement that does not return a recordset, including a stored procedure on the remote system. RDA is appropriate when the full functionality of SQL Server CE merge replication, such as conflict resolution, is not required.

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).

RDA 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.

See Also

Planning for RDA

Implementing RDA

Remote Data Access (RDA)


Typical Uses of RDA

An application running on a Microsoft® Windows® CE-based device can use remote data access (RDA) for:

  • Downloading data.

    An application can pull data from a database in Microsoft SQL Server™ to a database in Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE). For example, an application might download a company employee directory, product price list, or product catalog to the Windows CE-based device.

  • Capturing and uploading data.

    An application 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.

  • Downloading, updating, and uploading data.

    An application can pull data from a SQL Server database 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 can submit SQL statements to be executed on a remote SQL Server database. This is especially useful when the Windows CE-based device is always connected to the network.

An application can use these techniques in combination. For example, a sales support application might download a price list to a Windows CE-based device as well as capture and upload new orders on the device. The application could also submit SQL statements directly to the SQL Server database.

See Also

Sample Applications


RDA Architecture

Remote data access (RDA) uses the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) Database Engine, SQL Server CE Client Agent, and SQL Server CE Server Agent.

The following illustration shows how these components work together.

Illustration showing the flow of data between SQL Server CE components when remote data access (RDA) is used.

SQL Server CE Database Engine

The SQL Server CE Database Engine manages the SQL Server data store on the Windows CE-based device. For pull operations that are tracked, 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. If indexes exist on the SQL Server data, RDA also supports creating indexes on the local data.

SQL Server CE Client Agent

SQL Server CE Client Agent is the primary RDA component on the Windows CE-based device. It implements the RDA object interface. Applications call this interface to programmatically control RDA. The following table describes the action the SQL Server CE Client takes in response to a call to an RDA object method.

Method | Action
Pull | Forwards the request to SQL Server CE Server Agent through HTTP. When SQL Server CE Client Agent receives the recordset back from SQL Server, it stores the recordset in the SQL Server CE database.
Push | Extracts all inserted, updated, and deleted records from the SQL Server CE database and sends them to SQL Server CE Server Agent through HTTP.
SubmitSQL | Forwards the specified SQL request to SQL Server CE Server Agent through HTTP.
SQL Server CE Server Agent

SQL Server CE Server Agent is a component responsible for handling the HTTP requests made by SQL Server CE Client Agent.

Method | Action
Pull | Receives the request from SQL Server CE Client Agent, connects to SQL Server through the OLE DB Provider for SQL Server and invokes the client's SQL statement. SQL Server CE Server Agent returns the resulting recordset to SQL Server CE Client Agent through HTTP. For more information, see Using the Pull Method.
Push | Receives all the inserted, updated, and deleted records from SQL Server CE Client Agent, connects to SQL Server through OLE DB, and inserts, updates, or deletes the records in the SQL Server database. If errors occur, SQL Server CE Server Agent reports the errors to the SQL Server CE Client Agent through HTTP. For more information, see Using the Push Method.
SubmitSQL | Receives the specified SQL request from SQL Server CE Client Agent through HTTP, connects to SQL Server through OLE DB and invokes the client's SQL statement. If errors occur, SQL Server CE Server Agent reports the errors to SQL Server CE Client Agent through HTTP. For more information, see Using the SubmitSQL Method.

SQL Server CE Server Agent uses an internal .in and .out file to manage the exchange of data between SQL Server and SQL Server CE.

See Also

Client and Server Environments

Connectivity Solutions

RDA Programmer's Reference for eMbedded Visual Tools

.NET Compact Framework Data Providers


Planning for RDA

The following topics in this section provide background information to consider before implementing remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Information is provided about what data can be accessed through RDA, as well as information regarding general limitations with RDA.

  • Supported Data Types and Data Type Mappings
  • RDA Limitations
  • RDA Conflict Detection and Resolution


Supported Data Types and Data Type Mappings

The following tables show the data type mappings that are performed when remote data access (RDA) is used to access data in a Microsoft® SQL Server™ database.

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 the Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) binary. If the data is more than 510 bytes, RDA 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 fails.
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. If the data is more than 255 characters, RDA 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 fails.
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. If the data is more than 255 characters, RDA 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 fails.
datetime | datetime
decimal | See numeric.
double precision | double precision
float | float
image | image
integer (int 4) (synonym: int) | integer (int 4)
money | money
national character (synonyms: national character, 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. If the data is more than 255 characters, RDA 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 fails.
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. If the data is more than 255 characters, RDA 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 fails.
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 fails.
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 fails.
sql_variant | Not supported The Pull method fails 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 fails.
timestamp | Not supported The Pull method fails 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. If the data is more than 510 bytes, RDA 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 fails.
Using Data Types

When possible, choose data types that are supported by both SQL Server and SQL Server CE. As a result, RDA does not have 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 an ntext column.


RDA Limitations

Remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) has the following limitations:

  • Case sensitivity

    SQL Server CE databases are not case-sensitive.

  • ROWGUID

    When using RDA to pull data from a table in 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, for the SQLSelectString parameter in the Pull method, use SELECT CompanyName, ContactName FROM Customers instead of SELECT * FROM Customers.

  • Triggers

    SQL Server CE does not support triggers; however, triggers can reside on the SQL Server table from which RDA pulled data. For tracked tables, the SQL Server triggers can be executed when changes are pushed back to SQL Server. It might be necessary to specify SET NOCOUNT ON in the trigger logic. This indicates not to return the number of rows affected, because a response of no rows affected results in an error for the RDA push method.

  • Tables and columns

    For tracked tables, the number of columns available = 253 (255 - 2 system columns). SQL Server CE allocates two system columns: S_BinaryKey and S_Operation. These columns are protected and used for tracked RDA tables.

  • Computed columns

    Not supported. The Pull method fails if the recordset contains computed columns.

Schema Limitations

SQL Server CE is capable of tracking changes to the resulting SQL Server CE table. By specifying the appropriate tracking option, SQL Server CE tracks all inserts, updates, and deletes made to the local SQL Server CE table. The application can 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 logically partitioned and conflicts are unlikely. For example, tracked Pull and Push methods might be used in a field service application which tracks each technician who 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 DEFAULT constraints
  • 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 still processing. 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


RDA Conflict Detection and Resolution

Remote data access (RDA) in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides a limited conflict mechanism to resolve conflicts during a push operation.

Important Conflicting rows in RDA are strictly defined as insert, update, or delete operations, which fail due to an error when pushed to the SQL Server table. Changes to data by different users are not considered a conflict if they do not result in error.

Although RDA does not provide a specific resolver as replication does, SQL Server CE provides an error table that captures all conflicting rows. You can specify the error table as part of the Pull method. Using the error table, you can develop Microsoft Windows CE-based applications to manage conflict detection and resolution.

In SQL Server CE RDA, a conflict exists when a row cannot be pushed up to SQL Server. SQL Server CE supports only row-level tracking; therefore, some rows succeed and others fail depending on what options are selected in a Push method.

Nonbatch Transactions

During nonbatch transactions (BATCHINGOFF option), conflicts are detected at the row level. The conflicting row is returned to the application and stored in a specified error table. For example, if the application attempts to push a row to SQL Server that is not valid, that row is returned to the application and stored in the error table along with an error message indicating the conflict.

When a conflicting row is returned to the error table, that row is removed from the original Windows CE-based database. You must design the application to allow the user to correct the conflicting data and merge the conflicting data back into the original Windows CE-based database.

Batch Transactions

RDA also supports a batch push (BATCHINGON option) that requires all rows to succeed for the entire push to process. If one row fails, the entire push transaction fails and no data is updated. The conflicting row(s) is copied to the error table. Unlike the nonbatched push, the original Windows CE-based database is kept intact. You must design the application to allow the user to correct the conflicting data and merge it back into the original Windows CE-based database. The error table is automatically cleaned before a conflicting row is copied so only the conflicts from the last push operation exist in the table.


Implementing RDA

To implement remote data access in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), in addition to following the general installation and connectivity requirements, you must configure SQL Server with the appropriate access rights.

Configuring RDA Database Access

You must grant database access based on how Microsoft Internet Information Services (IIS) and SQL Server authentication are configured.

To configure the database access option

  1. Start SQL Server Enterprise Manager. In the left pane, expand Microsoft SQL Servers, SQL Server Group, the computer containing the publication, Security, and then click Logins.
  2. In the right pane, right-click the user ID that is requiring access to the database and click Properties. The user ID depends on how IIS and SQL Server Authentication are configured.
    IIS authentication mode | SQL Server authentication mode | Must grant database access to
    Anonymous access | 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. (This configuration is supported only if SQL Server and IIS are running on the same computer.)
    Anonymous access, Basic authentication, 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.
  3. Click the Database Access tab.
  4. Select the Permit check box for the database.
  5. To close SQL Server Login Properties, click OK, and then close SQL Server Enterprise Manager.

See Also

Installing SQL Server CE

Configuring Security for Connectivity


Using Replication

The following topics in this section provide information about using replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Topic | Description
Introducing Replication | Provides an overview of SQL Server CE replication. This topic explains how replication is used and describes the components of SQL Server CE replication.
Planning for Replication | Provides background information about SQL Server CE replication including data access, limitations, and conflict resolution.
Implementing Replication | Describes how you can configure SQL Server to support SQL Server CE replication.

For information about writing programs that use replication, see Replication. For information about problems you may encounter and ways to resolve them, see Troubleshooting.


Introducing Replication

Replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) is based on Microsoft SQL Server 2000 merge replication. Merge replication is 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 an instance of SQL Server.

In SQL Server CE, replication is message-based. SQL Server CE synchronizes with SQL Server by establishing an HTTP connection to the SQL Server Publisher through Microsoft Internet Information Services (IIS). By connecting through IIS, replication takes advantage of IIS authentication and authorization services. You can locate the Publisher behind a firewall or provide access to it using Microsoft Internet Security and Acceleration Server 2000. Replication can be performed over local area networks (LANs) and wide area networks (WANs). Using Microsoft ActiveSync®, you can communicate with SQL Server through the desktop computer's network connection, eliminating the requirement for the Windows CE-based device to have a network card or modem. For more information, see Using SQL Server CE Relay with an ActiveSync System.

The replication communication protocol is designed for wireless transports. The protocol uses compression to reduce the amount of transmitted data, and supports the use of encryption to safeguard sensitive user data during transmission. Following a communication failure, transmission resumes from the last successfully transmitted message buffer.

SQL Server CE replication offers row and column filtering, which enable you 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 may 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 can be used to eliminate large text or image columns that you may not want to publish to a Windows CE-based 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-based device. For more information, see "Filtering Published Data" in SQL Server Books Online.

See Also

Planning for Replication

Implementing Replication

Replication

Troubleshooting


Typical Uses of Replication

An application based on Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) can use replication for:

  • Downloading data.

    An application running on the Microsoft Windows CE-based 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, a product price list, or a product catalog.

  • Capturing and uploading data.

    An application running on the Windows CE-based device can subscribe to a SQL Server publication and download only schema files for the articles in the publication, rather than downloading the schema and the data. The application can capture data that originates from user-entered forms, a GPS system, a bar code reader, or something similar and 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 Publisher. From the Publisher, the data can be propagated to other Subscribers.

  • Downloading, updating, and uploading data.

    An application running on the Windows CE-based 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 publication database. Similarly, changes made at the Publisher since the initial download or most recent merge are sent to the Windows CE-based device, where they are merged into the subscription database. These periodic merge operations keep the data on the server and the Windows CE-based device synchronized.

Applications can use these techniques in combination. For example, a sales support application downloads data to publish a price list to a Windows CE-based device. The application captures new orders on the device. These orders are then sent to the Publisher on the computer running SQL Server. The application also downloads customer information to the Windows CE-based device. The customer information is updated on the device, and the resulting changes are uploaded back to the Publisher.

See Also

Sample Applications


Replication Architecture

Replication uses the following components in Microsoft® SQL Server™ 2000 Windows CE Edition (SQL Server CE):

  • SQL Server CE Database Engine
  • SQL Server CE Client Agent
  • SQL Server CE Server Agent
  • SQL Server CE Replication Provider

    Illustration showing the flow of data between SQL Server CE components when replication is used.

SQL Server CE Database Engine

The SQL Server CE Database Engine manages the local database on the Windows CE-based device. For subscription databases, the SQL Server CE 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-based device. The SQL Server CE Client Agent implements the SQL Server CE Replication object interface. Applications call this interface to programmatically control replication.

SQL Server CE Server Agent

The SQL Server CE Server Agent is the component responsible for managing the communication between an instance of SQL Server and SQL Server CE. The SQL Server CE Server Agent handles the HTTP requests made by SQL Server CE Client Agent.

SQL Server Reconciler and SQL Server CE Replication Provider

The SQL Server Reconciler invokes the SQL Server CE Replication Provider when synchronization is performed. Both the SQL Server Reconciler and SQL Server CE Replication Provider reside on the computer running IIS (on which SQL Server CE Server Tools is installed). When the SQL Server CE Server Agent starts the SQL Server Reconciler, a Merge Agent at the Publisher is associated with each subscription.


How Replication Works

This topic provides a general description about how merge replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) works. For detailed information about merge replication, see SQL Server Books Online.

SQL Server CE merge replication uses this process:

  1. Data is published.

    You create a publication containing SQL Server data that will be published to other sites, including Microsoft Windows CE-based devices running SQL Server CE. (A publication is a collection of articles. An article is a table that is enabled for replication.)

  2. Subscriptions to the publications are created.

    A Windows CE-based application subscribes to the publication by using the SQL Server CE Replication object with Microsoft eMbedded Visual Tools or the SqlCeReplication class with the .NET Compact Framework Data Provider for SQL Server CE. When the subscription is created, the initial snapshot is downloaded from the Distributor to create the subscription database on the Windows CE-based device.

  3. Data at the Subscriber is updated.

    The subscription database on the Windows CE-based device is updated by applications running on that device.

  4. Data is synchronized.

    Periodically, updates made at the Subscriber are sent to the Publisher and merged with updates made at the Publisher and updates propagated to the Publisher from other Subscribers. Similarly, changes made at the Publisher and other Subscribers since the initial download or the most recent merge are sent to the Windows CE-based device, where they are merged into the subscription database.

Publishing Data

Publications specify the data that is published. Publications are tailored to different users or groups of users. In some cases, all users 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 need different partitions of data. For example, sales representatives might need one set of data, and 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 his or her own customer accounts.

You can create a publication and specify which articles it contains. 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 only includes tables in the SQL Server CE subscription. You specify which of the table rows and columns are included in the article. For more information, see "Replication" in SQL Server Books Online.

Subscribing to Publications

After you define the publication, a Windows CE-based application can subscribe to it by calling the methods exposed by the SQL Server CE Replication object or the SqlCeReplication class on the Windows CE-based device. When the subscription is created, the initial snapshot from the Distributor is applied at the subscription database on the Subscriber.

Updating Data at the Subscriber

Windows CE-based applications can update the subscription database. Merge replication allows each subscription database to be updated autonomously. Updates can occur whether or not the Windows CE-based 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, users periodically connect the Windows CE-based device to the network. This allows the Windows CE-based application to synchronize changes made at the Subscriber with changes made at the Publisher. The Windows CE-based application initiates synchronization by calling the synchronization methods exposed by the Replication object or the SqlCeReplication class. Synchronization is a four-step process:

  1. Extract changes and create the input message file.

    The SQL Server CE Client Agent extracts all inserted, updated, and deleted records from the subscription database at the SQL Server CE Subscriber and propagates them to the SQL Server CE Server Agent through HTTP. The SQL Server CE Server Agent creates a new input message file on the computer running Microsoft Internet Information Services (IIS) and writes into that file the insert, update, and delete changes sent by the SQL Server CE Client Agent.

  2. Run the SQL Server Reconciler process and apply changes to the publication database.

    When all requests have been written to the input message file, the SQL Server CE Server Agent initiates the SQL Server Reconciler. The SQL Server Reconciler loads the SQL Server CE Replication Provider, which reads the input message file and informs the SQL Server Reconciler of changes made to the SQL Server CE subscription database that must be applied to the publication database at the Publisher. During processing, the SQL Server Reconciler detects and resolves conflicts; a conflict occurs when more than one Subscriber or Publisher updates the same record.

    Note The SQL Server Reconciler resolves conflicts with conflict resolvers. Use the conflict resolvers provided with SQL Server to implement simple forms of conflict resolution for your SQL Server CE replication applications or write conflict resolvers to implement more sophisticated solutions. For more information, see "Merge Replication Conflict Detection and Resolution" in SQL Server Books Online.

  3. Create the output message file.

    The SQL Server Reconciler informs the SQL Server CE Replication Provider of changes made at the Publisher that must be applied to the subscription database on the Windows CE-based device. The SQL Server CE Replication Provider writes these changes to an output message file it creates on the computer running IIS.

    Note The SQL Server CE Client Agent processes both the input and output message files in logical blocks as it reads from or applies changes to the subscription database on the Windows CE-based device. By processing each message file in this way, the SQL Server CE Client Agent avoids writing the entire message file on the Windows CE-based device, conserving storage space.

  4. Read the output message file and apply changes to the SQL Server CE subscription database.

    When the SQL Server Reconciler process is complete, 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 that must be applied to the subscription database on the Windows CE-based 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-based device. The SQL Server CE Client Agent applies the changes from the output message file to the SQL Server CE subscription database.

After the SQL Server CE Client Agent has incorporated all changes into the subscription database on the Windows CE-based device and conflicts (if any) have been resolved, the publication and subscription databases are synchronized and data is converged. However, before data values would be identical at the Publisher and at the Subscribers (because updates can occur continuously), you would need to stop all updates and then run several merges


Planning for Replication

The following topics in this section provide information to consider before implementing replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Typical SQL Server CE replication topologies are described. Information regarding what data can be replicated and limitations on published data is also provided.

  • Replication Topologies
  • Supported Data Types and Data Type Mappings
  • Replication Limitations
  • Schema Changes on Publication Databases
  • Replication Conflict Detection and Resolution


Replication Topologies

You can configure replication in Microsoft® SQL Server™ 2000 Windows CE Edition (SQL Server CE) in a variety of ways. You should choose a configuration based on the following factors:

  • Performance

    The performance of a system depends on the number of Microsoft Windows CE-based devices that must be supported, the frequency with which the devices must synchronize with the server, the connection bandwidth, 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 the application you develop.

Basic Configuration Rules

The following basic configuration rules govern SQL Server CE replication configuration:

  • The Subscriber is always an anonymous Subscriber.

    Individual Subscribers cannot be assigned a merge replication conflict resolution priority; the priority for Subscribers is always 0.

  • SQL Server CE cannot be a Publisher or Distributor.

    Two or more Windows CE-based devices can share a publication only by subscribing to the same SQL Server 2000 publication.

  • A 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. The more common ways to configure SQL Server CE replication are:

  • Single server
  • Two servers
  • Multiple Microsoft Internet Information Services (IIS) systems and SQL Server republishing
Single Server

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-based devices, synchronize by connecting to IIS on the Publisher. The Publisher can be located behind a firewall.

Illustration showing a replication topology in which IIS and the SQL Server Publisher/Distributor all reside on one computer.

Two Servers

You can place IIS on one server and configure the SQL Server Publisher and Distributor on another server. The server running IIS can be isolated from the Internet by a firewall. SQL Server CE clients, running on Windows CE-based devices, synchronize by connecting to IIS. Another firewall can isolate the SQL Server Publisher and Distributor from the IIS system.

Illustration showing a replication topology in which IIS resides on one computer and the SQL Server Publisher/Distributor on another computer.

Multiple IIS Systems and SQL Server Republishing

If you must support very large numbers of SQL Server CE Subscribers that synchronize at the same time, you can partition the work across multiple computers running IIS.

Illustration showing a replication topology with a single SQL Server Publisher/Distributor and multiple computers running IIS.

If further load balancing is required on the computer running SQL Server, you can create a republishing hierarchy on multiple computers. The top-level Publisher publishes data to Subscribers, which in turn republish the data, load balancing requests from the SQL Server CE clients. Load balancing is static in the sense that each SQL Server CE Subscriber is assigned to one of the republishers and always synchronizes with that republisher (SQL Server CE does not support alternate synchronization partners).

Illustration showing a replication topology with a single SQL Server Publisher/Distributor, multiple republishers, and multiple computers running IIS.

By using Microsoft ActiveSync®, a desktop system may be used to synchronize SQL Server CE to an instance of SQL Server. By using Microsoft Windows Powered Pocket PC 2002 and Microsoft ActiveSync 3.5, you can use the Pass Through functionality. If you are using ActiveSync 3.1, you must install SQL Server CE Relay. For more information, see Using SQL Server CE Relay.

Using Windows Clustering

SQL Server CE replication can be used on a Microsoft Windows 2000 cluster containing a farm of Web servers running IIS. However, the SQL Server CE Server Agent must maintain session state across client calls; therefore, you must use load-balancing hardware or software that is capable of maintaining a session state between the SQL Server CE Client Agent and the SQL Server CE Server Agent.

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.

SQL Server CE can be used with a variety of load-balancing systems for example Windows 2000 Network Load Balancing (NLB).

Windows 2000 NLB is included as part of Microsoft Windows 2000 Advanced Server and Windows 2000 Datacenter Server. NLB can be used with SQL Server CE because NLB supports client affinity, which is an option that ensures that the client is always directed to the same server running IIS within the cluster. Note, however, that if a server or network failure occurs during a client session, a new logon is required to reauthenticate the client and reestablish session state. Also, adding a new server running IIS to the cluster redirects some client traffic to the new server, which can affect existing sessions.

For more information, see "Windows Clustering Technologies" in the technical resources for Microsoft Windows 2000 at this Microsoft Web site.


Supported Data Types and Data Type Mappings

The following table shows the data type mappings that are performed when replicating between Microsoft® SQL Server™ and Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE). The table lists mappings for each SQL Server data type and describes restrictions or special behaviors.

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, 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 fails when the data is sent from the SQL Server CE Subscriber to the SQL Server Publisher.
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 fails 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 fails when the data is sent from the SQL Server CE subscription to the SQL Server publication.
datetime | datetime
decimal | See numeric.
double precision | double precision
float | float
image | image
integer (int 4) (synonym: 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 fails when the data is sent from the SQL Server CE subscription to the SQL Server publication.
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 fails when the data is sent from the SQL Server CE subscription to the SQL Server publication.
ntext | ntext
numeric (synonyms: decimal, dec) | numeric
real | real
smalldatetime | datetime If the precision of the datetime data exceeds the precision of the smalldatetime column, synchronization fails 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 fails when the data is sent from the SQL Server CE subscription to the SQL Server publication.
sql_variant | sql_variant is mapped to ntext. If binary data exists in the sql_variant column, the binary data must be an even number of bytes or a conversion error occurs.
text | ntext If the length of the text data exceeds 1,073,741,823 characters, synchronization fails when the data is sent from the SQL Server publication to the SQL Server CE subscription.
timestamp | Not supported Data stored as timestamp data 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 fails when the data is sent from the SQL Server CE subscription to the SQL Server publication.
varchar | See character varying

Choose data types that are supported by both SQL Server and SQL Server CE, so it is not necessary for replication to perform data mapping. When this is not possible, the 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 char, nchar, varchar, or nvarchar columns with lengths greater than 255. Creation of the SQL Server CE subscription fails because these column types are mapped to ntext, and a primary key cannot be created on an ntext column.

For more information about SQL Server data types, see "Data Types" in SQL Server Books Online.

See Also

Replication Limitations


Replication Limitations

Replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) has the following limitations:

  • Dynamic filters

    When you use dynamic filters, SQL Server CE requires that you use the optimize synchronization option. You can set this option by using either the Create Publication wizard or stored procedure scripts:

  • Using the Create Publication wizard

    Select Yes, minimize the amount of data to minimize the amount of data sent over the network when dynamic horizontal filters are defined. You cannot change this option for an existing publication.

  • Using the sp_addmergepublication script

    Set the @keep_partition_changes option to TRUE. The @keep_partition_changes option specifies whether synchronization optimization occurs.

    For more information, see the topics "Optimizing Synchronization" and "sp_addmergepublication" in SQL Server Books Online.

    Additionally, SQL Server CE cannot validate Subscriber information. When configuring a Publication with dynamic filters, you can request that the Subscriber information be validated; however, SQL Server CE ignores this request.

    Note The HostName property specifies the dynamic filter value for the subscription. If you want to change the dynamic filter value for the Subscriber by specifying a new HostName property, you must call the Reinitialize method before you synchronize.

  • Display of Subscriber names in SQL Server Enterprise Manager

    For SQL Server CE Subscribers listed in the SQL Server Enterprise Manager Replication Monitor, the Merge Agent subscription column is formatted as subscribername:-agentid. This guarantees uniqueness for each row in the Merge Agent if the Subscriber name supplied by the SQL Server CE application is not unique across all SQL Server CE subscriptions. The Subscriber name and the agent ID can be used to find the Subscriber ID (GUID) in the msmerge_agents system table in the distribution database.

  • Connection timeout

    SQL Server CE connectivity solutions recover from communication failures by restarting from the last successfully transmitted block of data, as long as the connection recovers within a time-out period of approximately two minutes. This makes synchronization possible even if the underlying transport is not reliable.

  • Snapshots

    SQL Server CE only supports the alternate snapshot location option, if the usual (default) snapshot location is not available.

    To specify an alternate snapshot location, you can set this option by using either the create publication stored procedure script or by using SQL Server Enterprise Manager to edit the properties of an existing publication:

  • Using the sp_addmergepublication script

    Set the @snapshot_in_defaultfolder option to FALSE and @alt_snapshot_folder= location of the alternate folder for the snapshot.

  • Editing Publication Properties of an existing publication

    On the Snapshot Location tab of the publications Properties dialog box, clear the Generate snapshots in the normal snapshot folder check box, select Generate snapshots in the following location check box, and specify the new location in Folder. You cannot change this option for an existing publication.

    Note SQL Server CE does not support FTP or compressed snapshot options for either the default or alternate locations.

  • Ranged identity columns

    SQL Server CE identity columns must have a data type of integer (int 4). 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 (int 4), the creation of that subscription fails on SQL Server CE.

    SQL Server CE allows you to modify the seed and 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 seed or increment values at the Subscriber. If you specify a seed that is above your allocated range identity, SQL Server CE returns an error when you attempt to insert a new record in the table. When you next synchronize, the Publisher corrects the problem by assigning your Subscriber a new identity range.

  • Computed columns

    Not supported. Data stored as computed columns is vertically partitioned out of all SQL Server CE subscriptions.

  • Information that is not propagated to the SQL Server CE Subscriber

    You can include the following items in a SQL Server publication, but they are not propagated to the SQL Server CE Subscriber:

    • CHECK constraints
    • DEFAULT definitions for columns
    • Extended properties
    • Stored procedures
    • Views
    • User-defined functions
    • Triggers

    Because SQL Server CE replication cannot propagate these items, you should implement equivalent logic in a SQL Server CE-based application. Doing so ensures that the SQL Server CE database remains consistent with the SQL Server database. For example, if the SQL Server database includes a CHECK constraint, the SQL Server CE-based application should implement the corresponding check in application code.

  • Case sensitivity

    SQL Server CE databases are not case-sensitive; therefore objects and data are treated differently in a SQL Server CE database from the way in which they are treated in a SQL Server database. For example, two tables, MYTABLE and mytable, are treated as different objects in a case-sensitive SQL Server database. The same table names cause a naming conflict in a SQL Server CE database. Similarly, two values, MYVALUE and myvalue, cause a primary key violation in SQL Server CE, because they are treated as the same value, whereas they do not cause a violation in 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 fails on SQL Server CE.

  • Tables and columns

    For all replication tables, the number of available columns is 252 (255 – 3 system columns). SQL Server CE allocates three system columns for tracking.

  • NOT FOR REPLICATION constraints

    SQL Server CE does not support the NOT FOR REPLICATION option. Do not create constraints using this option. If constraints in a database have the NOT FOR REPLICATION option, remove the constraint and then re-create it. If the NOT FOR REPLICATION option is specified, the constraint is still created on the SQL Server CE Subscriber, but it does not include the NOT FOR REPLICATION syntax.

See Also

IDENTITY (Property)

Supported Data Types and Data Type Mappings

ReinitializeSubscription Method


Schema Changes on Publication Databases

You can add and drop columns in a table published in a Microsoft® SQL Server™ publication without dropping and re-creating the publication. If you add or drop a column in a published SQL Server table, that schema change is published to the subscription database in Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) 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.

If a column is dropped from the SQL Server publication database, any changes made to data in that corresponding 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.

Important The SQL Server CE Subscriber must also be reinitialized if the column that is added to an existing published SQL Server table is an identity column.


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 is accepted and propagated to other sites based on a resolver specified when the publication was created. Each Subscriber merges with the Publisher, but conflicts typically occur between updates made at different Subscribers.

Microsoft® SQL Server™ 2000 Windows® CE Edition (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 row at the Publisher, and another change is made to the phone number column of the corresponding row in the same table at the Subscriber. 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.

Because SQL Server CE implements row-level tracking only, column-level tracking is ignored, even if it is configured on the Publisher. Therefore, a conflict occurs even if the columns affected in the corresponding rows are not the same.

After a conflict is detected, the Merge Agent launches the conflict resolver selected for the article. In addition to the default resolver, merge replication allows you to use a variety of custom resolvers to deal with conflict situations. 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. For more information about conflict detection and resolution, see "Merge Replication Conflict Detection and Resolution" in SQL Server Books Online.


Implementing Replication

The topics in this section describe the configuration requirements for using replication in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). The topics contain procedures for performing configuration tasks; some procedures are optional, depending on your requirements.

To implement SQL Server CE replication, you must configure SQL Server. Configuring SQL Server involves the following steps:

  1. Creating the Publication
  2. Securing the Publication
  3. Configuring the Snapshot Folder
  4. Checking the Status of the Snapshot Agent


Creating the Publication

You create publications for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) by using standard SQL Server replication tools and techniques. The easiest way to create a publication is by using the Create Publication Wizard. For more information, see "Replication Wizards" in SQL Server Books Online.

When you create a publication for SQL Server CE Subscribers by using the Create Publication Wizard, it is important to select the following options:

  • On the Select Publication Type page, select Merge publication.
  • On the Specify Subscriber Types page, select the Devices running SQL Server CE check box.

By selecting Devices running Windows CE, the following options are automatically configured for the publication:

  • Support for anonymous subscriptions
  • Character mode snapshot

If you use dynamic filters, SQL Server CE requires that you use the optimize synchronization option. Set this option by using either the Create Publication Wizard or the stored procedure sp_addmergepublication. For more information about this and other SQL Server CE replication limitations, see Replication Limitations.

If this is the first publication created for this server, the Create Publication Wizard prompts 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 files to the Windows CE-based device.

Note The snapshot folder location defaults to an administrative share (for example, C$); you should use an explicit share instead of the default because the administrative share can be accessed only by an administrator account. For more information, see Configuring an Explicit Snapshot Folder.

See Also

Securing the Publication

Configuring the Snapshot Folder

Checking the Status of the Snapshot Agent


Securing the Publication

Securing the Microsoft® SQL Server™ publication involves the following steps:

  1. Configuring Database Access
  2. Configuring the Publication Access List
  3. Configuring the Check Permissions Option

See Also

Configuring Security for Connectivity


Configuring Database Access

When you create a publication, Microsoft® SQL Server™ creates a publication access list (PAL) for the publication. The PAL is similar to an access control list (ACL). To add a user to the publication access list, you must first grant database access based on how you configured Microsoft Internet Information Services (IIS) and SQL Server authentication.

To configure the Database Access option

  1. On the computer running SQL Server, start SQL Server Enterprise Manager: On the Start menu, point to Programs, Microsoft SQL Server, and then click Enterprise Manager.
  2. In the console tree, expand Microsoft SQL Servers, SQL Server Group, the computer containing the publication, and Security; and then click Logins.
  3. In the details pane, right-click the user ID under which the Merge Agent executes, and then click Properties. The user ID of the Merge Agent depends on how you configured IIS and SQL Server authentication.
    IIS authentication mode | SQL Server authentication mode | Must grant database access to
    Anonymous access | Windows authentication | computername\IUSR_computername or the configured IIS anonymous user account.
    Basic authentication | Windows authentication | The IIS client's user or group.
    Integrated Windows authentication | Windows authentication | The IIS client's user or group. (This configuration is supported only if SQL Server and IIS are running on the same computer.)
    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, and then select the Permit check box for the database.

See Also

Configuring the Publication Access List

Configuring the Check Permissions Option

Configuring Security for Connectivity


Configuring the Publication Access List

When you create a publication, Microsoft® SQL Server™ creates a publication access list (PAL) for the publication. The PAL is similar to an access control list (ACL). It contains the list of logins that have been granted access to the publication. During synchronization, SQL Server checks the PAL for the Microsoft Internet Information Services (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. 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. On the computer running SQL Server, start SQL Server Enterprise Manager: On the Start menu, point to Programs, Microsoft SQL Server, and then click Enterprise Manager.
  2. In the console tree, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Databases, and the database you are publishing, and then click Publications.
  3. Right-click the 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. 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 access | Windows authentication | computername\IUSR_computername or the configured IIS anonymous user account.
    Basic authentication | Windows authentication | The IIS client's user or group.
    Integrated Windows authentication | Windows authentication | The IIS client's user or group. (This configuration is only supported if SQL Server and IIS are running on the same computer.)
    Anonymous, Basic, or Integrated Windows authentication | SQL Server authentication | The users specified in the DistributorLogin and PublisherLogin properties of the Replication object.

    Note If the Publisher and Distributor are on different computers, 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 Access Denied message is displayed at the Subscriber.

See Also

Configuring the Check Permissions Option

Configuring Database Access

Configuring Security for Connectivity


Configuring the Check Permissions Option

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, Microsoft® 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 are 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.

To configure the Check Permissions option

  1. On the computer running SQL Server, start SQL Server Enterprise Manager: On the Start menu, point to Programs, Microsoft SQL Server, and then click Enterprise Manager.
  2. In the console tree, expand Microsoft SQL Servers, SQL Server Group, the computer containing your publication, Databases, and the database you are publishing; and then click Publications.
  3. Right-click your publication name, click Properties, and then click the Articles tab.
  4. Click the properties button (...) for the published article you want to configure. This displays the Table Article Properties dialog box.
  5. Click the Merging Changes tab.
  6. Under 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 Microsoft Internet Information Services (IIS) and SQL Server authentication. For more information, see Configuring Security for Connectivity.

See Also

Configuring Database Access


Configuring the Snapshot Folder

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 to create the subscription on the Microsoft® Windows® CE-based device. You control access to the snapshot folder by assigning file system access permissions to it.

When you assign Read permissions to the snapshot folder and share, remember that the identity under which the SQL Server CE Replication Provider runs depends upon how Microsoft Internet Information Services (IIS) authentication is configured:

  • When IIS is configured to use Anonymous access, the SQL Server CE Replication Provider runs under the identity of the default IIS anonymous user account (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 corresponding to the login and password supplied by the Subscriber for the InternetLogin and InternetPassword properties of the Replication object.
  • When IIS is configured to use Integrated Windows authentication, the SQL Server CE Replication Provider runs under the identity of the Windows user account corresponding to the login and password supplied by the Subscriber for the InternetLogin and InternetPassword properties of the Replication object. Unlike Basic authentication, the login and password are never transmitted over the network with Integrated Windows authentication.

Whether IIS and the SQL Server Distributor are located on the same computer or different computers, it is strongly recommended that you configure the snapshot folder as described in Configuring an Explicit Snapshot Folder.

See Also

Configuring Security for Connectivity

InternetLogin Property (Replication)

InternetPassword Property (Replication)


Configuring the Default Snapshot Folder

If the snapshot folder is located on a FAT file system, configuring the folder is not necessary; proceed directly to Checking the Status of the Snapshot Agent.

Note It is recommended that you use an NTFS file system because it is more secure.

The default snapshot folder, also called the normal snapshot folder, resides on an administrative share (drive$) by default. It is recommended that you do not use the default administrative share setting but instead create an explicit share for the default (normal) snapshot folder. For more information, see Configuring an Explicit Snapshot Folder.

To secure the snapshot folder

  1. On the computer running Microsoft® SQL Server™, start Windows® Explorer by double-clicking My Computer.
  2. Locate the snapshot folder, right-click it, and then click Properties. The default location of the snapshot folder is C$\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.) 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 access, grant computername\IUSR_computername or the configured Microsoft Internet Information Services (IIS) anonymous user account read permission. If IIS and the SQL Server Distributor are located on different computers, 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 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 an Explicit Snapshot Folder

Explicitly configuring the snapshot folder and share is recommended. This is necessary because Microsoft® SQL Server™ places the snapshot folder in the C$ share by default. The C$ share is a special administrative-only share. You cannot grant rights to the C$ share, and only administrators on the computer can access it. You must create and secure a nonadministrative network share for the snapshot folder so the Server SQL Server CE Replication Provider can read it remotely.

If you have already configured the Distributor using the administrative share, you must also change the location of the default snapshot folder after the new explicit share is created.

To create and secure a nonadministrative network share

  1. On the computer running SQL Server, start Microsoft Windows® Explorer by double-clicking My Computer. Create a new NTFS file system folder to contain the snapshot files. Place the folder on any drive you want and give it any name you want.
  2. Right-click the new folder, click Properties, and then click the Sharing tab.
  3. Click Share this folder. In Share name, type any name you want. Optionally enter a comment describing the share.
  4. To display the Share Permissions tab, click Permissions. Click 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 access, 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 is a local account. | Read
    For IIS Basic or Integrated Windows authentication, grant the client's user or group read permission. | Read
  5. To close the Share Permissions tab, click OK.
  6. Click the Security tab. (If the Security tab is not displayed, you are using a FAT file system and can skip this step.) Set the same NTFS permissions as the permissions specified on the actual folder in Step 4, and then click OK to close.

To change the location of the default snapshot folder

  1. On the computer running SQL Server, start SQL Server Enterprise Manager: On the Start menu, point to Programs, Microsoft SQL Server, and then click Enterprise Manager.
  2. In the console tree, expand Microsoft SQL Servers, SQL Server Group, and select the instance of SQL Server containing the publication.
  3. With the appropriate instance of SQL Server selected, on the Tools menu, point to Replication, and then click Configuring Publishing, Subscribers, and Distribution.
  4. Select the Publisher tab, and then click the properties (...) button.
  5. Enter the new folder location where the snapshot files will be stored. This location is the new nonadministrative network share you just created.


Checking the Status of the Snapshot Agent

You can use the Replication Monitor in SQL Server 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. On the computer running Microsoft® SQL Server™, start SQL Server Enterprise Manager: On the Start menu, point to Programs, Microsoft SQL Server, and then click Enterprise Manager.
  2. In the console tree, expand Microsoft SQL Servers, SQL Server Group, the computer containing the Distributor for the publication, and Replication Monitor; and then click Agents.
  3. In the left pane, click Snapshot Agents. The status of the Snapshot Agent is displayed in the right pane.
  4. To display more information about an entry listed in the right pane, double-click the entry.

If the Snapshot Agent for the publication has not started, in the right pane, right-click the agent entry and select Start Agent.


Working with SQL Server CE Databases

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) extends a subset of the database programming functionality of Microsoft SQL Server to Microsoft Windows CE-based devices. You can create, access, and modify SQL Server databases programmatically in these devices using the SQL Server CE database engine.

The following topics in this section describe the administrative and programmatic tasks involved when you work with SQL Server CE databases.

Title | Description
Understanding SQL Server CE Database Objects | Describes the size limitations of SQL Server CE database objects.
Designing and Maintaining SQL Server CE Databases | Describes the ways to create, secure, and maintain databases in SQL Server CE.
Accessing SQL Server CE Databases | Describes how to query and modify databases in SQL Server CE.
Using SQL Server CE Query Analyzer | Describes the user interface of SQL Server CE Query Analyzer and how you can use the interface to perform database tasks.


Understanding SQL Server CE Database Objects

The following table specifies the maximum sizes and numbers for several database objects defined in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) databases. Use these specifications, while applying the same concepts about database design and programming that you use in SQL Server, when you work with SQL Server CE databases.

Category | Object | Maximum size limitations
Storage | Column name | 128 characters
Columns in a table | 255
Database password | 40 characters
Database size | 2.14 gigabytes (GB)
Database size increase | 1-page to 16-page increments, depending on table size
Identifier length | 128
Page size | 4 kilobytes (KB)
Sessions | 1
Size of BLOB (ntext and image) column | 1.07 GB
Table name | 128 characters
Table size | 2.14 GB
Queries | Characters in an SQL statement | Unlimited
Columns in a cursor | 255
Columns in a query | Unlimited
Columns in an ORDER BY clause | 255
Levels of nested subqueries | Unlimited
Named parameters | Not supported
Operands in a query | Unlimited
Tables in a join | Unlimited
Indexes

Note For every PRIMARY KEY, FOREIGN KEY, and UNIQUE constraint defined on a table, an index is created on those columns. Additionally, for every FOREIGN KEY constraint, the engine creates internally an index on the referenced table. These indexes all count against the total number of indexes allowed for a table.

 BLOB columns Cannot be indexed
Bytes in an index key | 510
Columns in an index | 10
Indexes per table | 249
Constraints | PRIMARY KEY, UNIQUE, and FOREIGN KEY | Supported


Designing and Maintaining SQL Server CE Databases

The following topics in this section describe the administrative-related tasks relating to databases in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE):

  • Creating a Database
  • Using SQL Server CE Temporary Databases
  • Using the SQL Server CE Database Security Features
  • Maintaining SQL Server CE Databases


Creating a Database

With Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), you must be connected to an existing database before you can create a new database using the SQL CREATE DATABASE syntax. For more information, see CREATE DATABASE.

You can create a new SQL Server CE database by using one of the following methods:

  • Using SQL Server CE Query Analyzer
  • Creating a Database Through ADOXCE
  • Creating a Database Through OLE DB
  • Creating a Database Through the AddSubscription Method in Replication


Creating a Database Through ADOXCE

To create a database through Microsoft® ActiveX® Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE), use the Catalog object. The Catalog object exposes the Create method, which takes an OLE DB connection string. For more information about ADOXCE, see the Microsoft ActiveX Data Objects Extensions for Windows® CE 3.1 documentation at this Microsoft Web site.

Dim cat As ADOXCE.Catalog
Set cat = CreateObject("ADOXCE.Catalog.3.1")
cat.Create "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.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.2.0; data source=\test2.sdf;Locale Identifier=1041"


Creating a Database Through OLE DB

The OLE DB Provider for SQL Server CE supports programmatically creating databases in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). For more information and an OLE DB programming example, see Creating Databases.

See Also

Programming OLE DB Applications for SQL Server CE


Creating a Database Through the AddSubscription Method in Replication

The AddSubscription method of the Replication object creates a new anonymous subscription to an existing publication. The CREATE_DATABASE option using Microsoft® eMbedded Visual Tools, or the CreateDatabase option using Microsoft Visual Studio® .NET, creates a new (empty) Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database on a Windows CE-based device. This method can be used to create SQL Server CE databases whether or not you are using merge replication to synchronize data.

For more information, see AddSubscription Method.


Using SQL Server CE Temporary Databases

During execution, Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) creates a temporary database that it uses for storing temporary data such as:

  • Pages that are part of an open transaction that no longer fits in the SQL Server CE cache buffer.
  • Interim result sets that are created during a query.
  • Interim sort tables that are created when executing an ORDER BY clause.

The temporary database is created when the SQL Server CE database engine starts, and it is removed when the database engine is shut down in a predictable manner. Abnormal termination of a SQL Server CE application leaves temporary database files that must be manually removed. Unless a new location for the temporary database has been assigned, these files can be found in the \TEMP directory and have file names that begin with SQLCE, for example, SQLCE334241234.tmp.

Growth of the Temporary Database

During execution, once its buffer cache is full, the SQL Server CE database engine dynamically allocates resources to the temporary database. Large databases can generate large amounts of temporary data during normal execution. When the temporary database grows to the point that there is insufficient storage space on the default storage device, the application fails.

The following operations cause growth in the temporary database, particularly when they are wrapped in a single transaction:

  • UPDATE and DELETE statements.
  • Explicit transactions.
  • Sort operations: Sorting is required when indexes are created and also when statements that include the ORDER BY or GROUP BY clause are executed.
Location of the Temporary Database

To prevent large database files from growing beyond the storage limits of the device, it is possible to store databases on a storage card rather than in internal RAM. Even when user databases are moved to a storage card, the temporary database is always created by default in the \TEMP directory of the device, which uses internal RAM.

For operations requiring a large temporary database, you can specify a location different from the default \TEMP directory for the temporary database. The new location for the temporary database is usually on a storage card.

Because the temporary database is created when the database engine starts, the location of the temporary database must be specified prior to the engine being started and cannot be changed when the engine is running. The location of the temporary database can be changed when the database is compacted.

You can specify the location of the temporary database in the following ways:

  • Specifying the Location of the Temporary Database in a Smart Device Application
  • Specifying the Location of the Temporary Database Using ADOCE
  • Specifying the Location of the Temporary Database Using the Replication and RDA Controls
  • Specifying the Location of the Temporary Database Using OLE DB


Specifying the Location of the Temporary Database in a Smart Device Application

Using Microsoft® .NET Compact Framework Data Provider for SQL Server CE, you can explicitly specify the location of the temporary database by adding the temp file directory property to the SqlCeConnection.ConnectionString object that is passed to SqlCeConnection as follows:

"temp file directory = temp_database_location;"

Note Property values in the connection string can be specified in any order and must be separated by semicolons.

You can also specify the temporary database location in the destConnect connection string when calling the SqlCeEngine.Compact method.

Examples

The following Microsoft C# example shows how to pass the temporary database location in the connection string of the SqlCeConnection object.

SqlCeConnection conn = new SqlCeConnection();
conn.ConnectionString = "Persist Security Info=False; Data Source =
    Northwind.sdf; temp file directory = temp_database_location;"

conn.Open();

The following Microsoft Visual Basic® example shows how to pass the temporary database location in the connection string of the SqlCeConnection object.

Dim conn As New SqlCeConnection()
conn.ConnectionString = "Persist Security Info=False; Data Source = " + _
   "Northwind.sdf; temp file directory = temp_database_location;"

conn.Open()

For more information, see the System.Data.SqlServerCe.SqlCeConnection class in the .NET Compact Framework SDK in Microsoft Visual Studio® .NET.

See Also

Using SQL Server CE Temporary Databases


Specifying the Location of the Temporary Database Using ADOCE

Using Microsoft® ActiveX® Data Objects for Windows® CE (ADOCE), you can explicitly specify the location of the temporary database by adding the following value to the connection string that is passed by the Connection.Open method:

"SSCE:Temp File Directory = temp_database_location"

Note Property values in ADOCE connection strings must be separated by semicolons, and the location of the temporary database path inside the connection string is not important.

You can also specify the temporary database location in the connection string when calling the Engine.CompactDatabase method.

Examples

The following Microsoft Visual Basic® example shows how to pass the temporary database location in the connection string using ADOCE.

Dim cn As ADOCE.Connection
Set cn = CreateObject("ADOCE.Connection.3.1")
cn.ConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0; data "
    + " source=\Northwind.sdf; SSCE:Temp File Directory = temp_database_location"
cn.Open

See Also

CompactDatabase Method

Using SQL Server CE Temporary Databases


Specifying the Location of the Temporary Database Using the Replication and RDA Controls

 SQL Server CE Books Online

Specifying the Location of the Temporary Database Using Replication and RDA Controls

You can explicitly specify the location of the temporary database by using both the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) Replication and Remote Data Access (RDA) ActiveX® control objects by adding the following value at the end of the connection string:

"SSCE:Temp File Directory = temp_database_location"

Note Property values in the connection string must be separated by semicolons, and the location of the temporary database path inside the connection string is not important.

For the Replication object, you must include the temporary database location for all methods that use a SubscriberConnectionString property. These methods are:

  • REPL_Object.Initialize
  • REPL_Object.AddSubscription
  • REPL_Object.Run
  • REPL_Object.ReinitializeSubscription
  • REPL_Object.DropSubscription

For the RDA object, you must include the temporary database location for all methods that use a LocalConnectionString property. These methods are:

  • RDA_Object.Pull
  • RDA_Object.Push
Examples
A. Using the SubscriberConnectionString property in the Replication object

The following Microsoft Visual Basic® example shows how to use the SubscriberConnectionString property in the SQL Server CE ActiveX Control Replication object.

' Declare the Replication object.
Dim ceRepl As SSCE.Replication

' Create the Replication object.
Set ceRepl = CreateObject("SSCE.Replication.2.0")

' Set Internet properties.
ceRepl.InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
ceRepl.InternetLogin = "MyInternetLogin"
ceRepl.InternetPassword = "<MyInternetPassword>"

' Set Publisher properties.
ceRepl.Publisher = "SamplePublisher"
ceRepl.PublisherDatabase = "Nwind_SQLCEReplDemo"
ceRepl.Publication = "SQLCEReplDemo"
ceRepl.PublisherSecurityMode = DB_AUTHENTICATION
ceRepl.PublisherLogin = "MySqlPublisherLogin"
ceRepl.PublisherPassword = "<MySqlPublisherPassword>"

' Set Subscriber properties.
ceRepl.SubscriberConnectionString = "data source=\NorthwindRepl.sdf;SSCE:Temp File Directory =temp_database_location"
ceRepl.Subscriber = "SQLCE Sub #1"

 ' Create the new anonymous subscription.
 ceRepl.AddSubscription CREATE_DATABASE
B. Using the LocalConnectionString property in the RDA object

The following Visual Basic example shows how to use the LocalConnectionString property in the SQL Server CE RDA ActiveX control object.

' Declare the SQL Server CE RDA ActiveX control object.
Dim ceRDA As SSCE.RemoteDataAccess

' Create the RDA object.
Set ceRDA = CreateObject("SSCE.RemoteDataAccess.2.0")

' Set RDA properties.
ceRDA .InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
ceRDA .InternetLogin = "MyInternetLogin"
ceRDA .InternetPassword = "<MyInternetPassword>"
ceRDA .LocalConnectionString = "Data Source=\NorthwindRDA.sdf;SSCE:Temp File Directory =temp_database_location"

' 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>"

See Also

CompactDatabase Method

Using SQL Server CE Temporary Databases


Using the SQL Server CE Database Security Features

The primary security systems for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) are provided by the connectivity features of the product. For more information about secure connectivity, see Planning for Security.

In addition to the connectivity security options, the SQL Server CE database engine provides two additional features for securing local databases on a Windows CE-based device. These features are the ability to password protect databases and encrypt databases. For more information, see Password Protecting SQL Server CE Databases and Encrypting SQL Server CE Databases.


Password Protecting SQL Server CE Databases

The Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database engine allows you to require that a password be supplied when accessing a local database. In SQL Server CE, one password is created for the database that is being secured. A password is not created for each user of a database. Passwords for SQL Server CE databases:

  • Can be up to 40 characters long.
  • Can contain letters, symbols, digits, or a combination.
  • Cannot be recovered.

    Note The password does not prevent the reading of any data in the database file as clear text. By using both encryption and a password, you can store the data in an encrypted format and restrict programmatic access to the database.

Creating Password-protected Databases

Password-protected databases are created by supplying a password property when the database is created. Password-protected databases can be created by the following methods:

  • Using SQL Syntax

    To create a password-protected database through SQL syntax, specify database_password in the CREATE DATABASE statement. The password must follow the DATABASEPASSWORD keyword and be enclosed in single quotation marks as in the following example:

    Create Database "secure.sdf" databasepassword '<myPassword>'
  • Using the .NET Compact Framework Data Provider for SQL Server CE

    To create a password-protected database using the SqlCeEngine.CreateDatabase method, you must specify the password property in the connection string as in the following example:

    "data source=\NorthWind.sdf; password=<myPassword>"

    For more information, see the System.Data.SqlServerCe.SqlCeEngine class in the .NET Compact Framework SDK in Microsoft Visual Studio® .NET.

  • Using Microsoft ActiveX® Data Objects for Windows CE (ADOCE), Microsoft ActiveX Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE), or the Replication object

    To create a password-protected database using the either the ADOCE or ADOXCE Catalog object, or the AddSubscription method of the SQL Server CE Replication ActiveX object, you must specify the provider-specific SSCE:Database Password connection property in the connection string. For example:

    "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0; data source=\NorthWind.sdf; SSCE:Database Password=<myPassword>"
  • Using OLE DB

    For more information, see Creating Databases.

Accessing Password-protected Databases

A password must be supplied to open a password-protected database. Password-protected databases can be accessed by the following methods:

  • Using the data provider for SQL Server CE

    To access a password-protected database using the SqlCeConnection.Open method, you must specify the password property in the connection string. For example:

    "data source=\NorthWind.sdf; password=<myPassword>"

    For more information, see the System.Data.SqlServerCe.SqlCeConnection class in the .NET Compact Framework SDK in Microsoft Visual Studio .NET.

  • Using ADOCE, ADOXCE, or the Replication object

    To access a password-protected database using either the ADOCE or ADOXCE Catalog object, or the SQL Server CE Replication ActiveX object, you must specify the provider-specific SSCE:Database Password connection property. For example:

    "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0; data source=\NorthWind.sdf; SSCE:Database Password=<myPassword>"
  • Using OLE DB

    For more information, see Accessing Password-protected Databases.

Changing the Database Password

After a password has been assigned to a database, it cannot be changed until the database is compacted. For more information, see Changing Passwords and Encryption Settings for a Database.

See Also

Connecting to a SQL Server CE Database

SubscriberConnectionString Property


Encrypting SQL Server CE Databases

The Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database engine allows you to encrypt databases. Databases that are encrypted must also be protected with a database password.

Important Because encrypted databases can only be accessed with a password, if the password for an encrypted database is lost, the data is essentially gone.

This encryption support is provided by Windows CE and is supported on all Pocket PC devices. To enable encryption on a Windows CE-based device, you must install Rsaenh.dll (a dynamic-link library that implements the security features of SQL Server CE) on the Pocket PC device. This encryption component is shipped with Handheld PC 2000 Service Pack 1 devices and is also available for download in the Microsoft High Encryption Pack, which can be found at this Microsoft Web site.

Note Database encryption is not supported in Handheld PC 2000 or in the Windows CE emulation.

Creating Encrypted Databases

Encrypted databases are created by supplying both encryption and password properties when the database is created. Encrypted databases can be created by the following methods:

  • Using SQL Syntax

    To create an encrypted database through SQL syntax, specify both database_password and the ENCRYPTION ON option. For example:

    Create Database "secure.sdf" databasepassword '<password>' encryption on
  • Using the .NET Compact Framework Data Provider for SQL Server CE

    To create a password-protected database using the SqlCeEngine.CreateDatabase method, you must specify the password property in the connection string. For example:

    "data source=\secure.sdf;password=<myPassword>;encrypt database=TRUE"

    For more information, see the System.Data.SqlServerCe.SqlCeEngine class in the .NET Compact Framework SDK in Microsoft Visual Studio® .NET.

  • Using Microsoft ActiveX® Data Objects for Windows CE (ADOCE), Microsoft ActiveX Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE), or the Replication object

    To create an encrypted database using either the ADOCE or ADOXCE Catalog object, or the AddSubscription method of the SQL Server CE Replication ActiveX object, you must specify both the provider-specific SSCE:Database Password connection property and the provider-specific SSCE:Encrypt Database connection property. SSCE:Encrypt Database is a Boolean value that must be set to TRUE for an encrypted database. For example:

    "provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;data source=\secure.sdf;SSCE:Database Password=<myPassword>;SSCE:Encrypt Database=TRUE"
  • Using OLE DB

    For more information, see Creating Databases.

Accessing Encrypted Databases

A password must be supplied to open an encrypted database. Encrypted databases can be accessed by the following methods:

  • Using the data provider for SQL Server CE

    To access a password-protected database using the SqlCeConnection.Open method, you must specify the password property in the connection string. For example:

    "data source=\NorthWind.sdf; password=<myPassword>"

    For more information, see the System.Data.SqlServerCe.SqlCeConnection class in the .NET Compact Framework SDK in Microsoft Visual Studio® .NET.

  • Using ADOCE, ADOXCE, or the Replication object

    To access a password-protected database using either the ADOCE or ADOXCE Catalog object, or the SQL Server CE Replication ActiveX object, you must specify the provider-specific SSCE:Database Password connection property in the connection string. For example:

    "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0; data source=\NorthWind.sdf; SSCE:Database Password=<myPassword>"
  • Using OLE DB

    For more information, see Accessing Password-protected Databases.

Changing the Encryption Settings and Database Password

After an encryption setting and password have been assigned to a database, they cannot be changed until the database is compacted. For more information, see Changing Passwords and Encryption Settings for a Database.

See Also

Connecting to a SQL Server CE Database

SubscriberConnectionString Property


Changing Passwords and Encryption Settings for a Database

Once the encryption or password properties on a database have been set, these properties can only be modified when the database is compacted. In addition to setting these security properties on the database, compaction is primarily used to compress unused space in a database and to search for database consistency errors. For more information, see Maintaining SQL Server CE Databases.

Compaction is exposed through the following mechanisms in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE):

  • The Compact method of the SQL Server CE Database Engine ActiveX® control.

    For more information, see CompactDatabase Method.

  • The Compact method of the System.Data.Sqlserverce.SqlCeEngine class of the .NET Compact Framework Data Provider for SQL Server CE.

    For more information, see .NET Compact Framework Data Providers.

  • Directly through the OLE DB for SQL Server CE by using the ISSCECompact interface.

    For more information, see ISSCECompact.

    Note When compacting a password protected or encrypted database, you will need to specify the password for the original database.


Maintaining SQL Server CE Databases

The internal structure of a database can become fragmented over time and, after much use, result in wasted disk space. If the fragmentation is excessive, performance can deteriorate. To avoid fragmentation and get better performance, use the compaction process to maintain the database.

Compacting a database performs the following tasks:

  • Reorganizes a table's pages so they reside in adjacent database pages. This improves performance by reducing table fragmentation across the database.
  • Reorders table rows when there is a UNIQUE or PRIMARY KEY constraint present on the table.
  • Reclaims unused space created by object and record deletions by rewriting all database data into new data pages with no gaps in the page. When objects or records are deleted from the database, the space they occupied is marked as available for new additions to the database. However, unless an entire page of data has been deleted, the page remains in a partially filled state and the size of the database does not shrink until either the final data is deleted from the page or 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, compacting the database sets the value of the identity column of the next record to 1. If the highest remaining identity value in the database is 50, compacting the database sets the value of the next record to 51. Note that this is true even if records containing values greater than 50 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 when much time has elapsed, when transactions are rolled back, and when the database was not properly closed due to power loss or failure to completely exit the program before turning the computer off.
  • Repairs a suspect database.
  • Modifies database properties.

Before compacting a database, ensure that the following conditions are met:

  • The database must not be open.
  • The source and destination database path must be different.

    The destination database must not exist when CompactDatabase is called. An error occurs if the database specified by DestConnection already exists or another file with that name already exists.

  • Sufficient storage space must exist for both the original and compacted versions of the database, as well as any cached data and data stored in the temporary database.

When a database is compacted, the following database properties can be modified:

  • Password
  • Whether or not the database is encrypted
  • Locale identifier

See Also

CompactDatabase Method

ISSCECompact

Using SQL Server CE Query Analyzer


Accessing SQL Server CE Databases

The Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database engine provides the following features for accessing SQL Server CE databases:

  • Parameterized queries

    Create queries with parameters and use these queries many times. The parameters are placeholders for values supplied at run time. For more information, see Using Parameters in Queries.

  • Intrinsic functions

    Use mathematical, string, and system functions in your queries to perform operations and return scalar values. For more information, see Functions.

  • UNION operator

    Obtain a single result set from a combination of two or more SELECT statements. For more information, see UNION.

  • SQL Server CE Query Analyzer

    Use the SQL syntax in the SQL Server CE Query Analyzer to access and modify databases. For more information, see Using SQL Server CE Query Analyzer.

For information about the SQL grammar, see SQL Reference for SQL Server CE. For more information about Transact-SQL, see SQL Server Books Online in the MSDN® Library at this Microsoft Web site.


Using Parameters in Queries

Parameters are often used when querying relational databases. Using parameters in queries allows the database client to run an SQL statement multiple times with potentially different sets of values. This allows queries with the same structure and with only differing variables to be run without having to recompile the query multiple times. This improved efficiency can be used to minimize query execution time, especially for large queries or queries that are run many times.

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), input parameters in a query are specified with parameter markers. A parameter marker is a question mark (?) placed in the location of an input expression in an SQL statement. Values for the parameters are passed programmatically when the command is executed.

Named parameters are not supported in SQL Server CE. Parameters can be used to replace only column values. They cannot be used in queries to replace other objects, such as table or column names. The number and order in which you programmatically specify parameters must correspond to the parameter markers in the query.

The .NET Compact Framework Data Provider for SQL Server CE supports use of parameters in queries. For more information about the System.Data.SqlServerCe.SqlCeParameter and System.Data.SqlServerCe.SqlCeParameterCollection classes, see the .NET Compact Framework SDK in Microsoft Visual Studio® .NET.

The OLE DB Provider for SQL Server CE also supports using parameters in queries. For more information, see Parameters.

Examples
A. Using parameters in an SQL query

In the following simple statement using the Northwind sample database, the requested value for CustomerID is passed programmatically when the SELECT statement is executed.

SELECT * FROM Orders WHERE CustomerID =?
B. Using parameters to an insert a new row

In the following example, an SQL INSERT statement uses parameters to insert a new row into the Employees table of the Northwind sample database.

INSERT INTO Employees(LastName, FirstName, Title, TitleOfCourtesy,
BirthDate, HireDate, Address, City, Region, PostalCode, Country,
HomePhone, Extension, Photo, Notes, ReportsTo, PhotoPath, rowguid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)


Working with Cursors

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports three types of cursors: base table, scrollable query, and forward-only. Each cursor type is different. Carefully choose your cursor in order for your application to work most effectively.

Base Table Cursors

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

Base table cursors have dynamic membership, which means 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). Because base table cursors are updatable, 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 Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE), pass the adCmdTableDirect flag when the Recordset object is opened. If this flag is not passed, the cursor cannot be a base table cursor because ADOCE implicitly prepends SELECT * FROM to the table name. Base table cursors used in ADOCE and SQL Server CE should use adOpenDynamic and adLockOptimistic, for example:

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

Scrollable query cursors are the most functional query-result cursors. These cursors support scrolling backward and forward and using bookmarks to position on rows. They do not support updates or indexes. Scrollable cursors do not see external changes to the data; the results of the query are cached for the lifetime of the cursor. Although scrollable cursors are more functional than forward-only cursors, scrollable cursors are slower and use more memory. Clients should use scrollable cursors only if scrolling or bookmarking is necessary. SQL Server CE does not support updatable cursors from the query processor.

Scrollable cursors can use either adOpenStatic or adOpenKeyset. These cursors should use adLockReadOnly and not specify the adCmdTableDirect flag, for 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, indexes, or updating. These cursors should be used in scenarios in which 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, and the adCmdTableDirect flag should not be used, for example:

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

See Also

Cursors


Using 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 canceled. Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports transactions and exposes the ability to use them directly through both Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE) and the OLE DB layer. Transactions can also be nested. Within a larger transaction, it is possible to have atomic units of work that are individually committed or canceled.

The SQL Server CE transaction model differs from that of Microsoft SQL Server. When you develop applications to run on both, it is important to keep the following information in mind:

  • SQL Server CE supports only single-phase commit transactions.
  • In SQL Server CE, transactions can be nested up to five levels deep.
  • The transaction isolation model exposed in SQL Server CE is "Read Committed," which means SQL Server CE can isolate users from uncommitted changes in a database.
  • SQL Server CE holds an exclusive lock on a table that has been altered in a transaction until that transaction completes. Additional attempts to open the table or perform modifications on it will fail until the lock in the transaction is released. Consequently, it is not generally recommended that DDL operations be performed inside transactions because of the potential for locking conflicts to occur.
  • Transactions also influence the way cursors function. In SQL Server CE, if a cursor is opened within a transaction, the cursor exists within the scope of that transaction. If the transaction is canceled, the cursor ceases to exist. To continue using a cursor after a canceled transaction, the cursor should be created outside the scope of the transaction. Within the context of ADOCE and OLE DB for SQL Server CE, 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.

For more information about using transactions with the OLE DB Provider for SQL Server CE, see Transactions.

Examples

The following Microsoft Visual Basic® example shows the use of transactions using ADOCE.

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 a SQL Server  CE database.
  cn.Open "provider=Microsoft.SQLServer.OLEDB.CE.2.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 canceled
  ' will zombie the rowset. This 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


Using SQL Server CE Query Analyzer

SQL Server CE Query Analyzer is a graphical tool included in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) that you can use to:

  • Create databases.
  • Manage and connect to other databases on a device.
  • Verify remote data access (RDA) and replication applications.
  • Create and modify tables and indexes in a database.
  • Query objects by using the SELECT statement.
  • Insert and delete rows in a table.
  • Modify existing data in a table.
  • Compact and repair a database.

    Note To navigate the graphical interface and execute commands in SQL Server CE Query Analyzer on a device, you must use a stylus. However, when the device is connected to a desktop computer, the desktop keyboard and mouse can be used in conjunction with Microsoft Remote Display Control for Windows CE.

Queries that are 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
Installing and Starting SQL Server CE Query Analyzer

The installation of SQL Server CE Query Analyzer depends on the development environment onto which SQL Server CE is installed. When you install SQL Server CE, SQL Server CE Query Analyzer is not installed by default on a device. For more information, see Installing SQL Server CE Query Analyzer.

To start SQL Server CE Query Analyzer

  • Run the SQL Server CE Query Analyzer executable file, Isqlw20.exe, directly from the Start menu or from the directory in which it is installed.

After SQL Server CE Query Analyzer is installed, you can refer to the following topics that describe how to use it:

  • Navigating the Query Window
  • Managing Databases and Database Connections in the Objects Tab
  • Managing Database Objects in the Objects Tab
  • Executing SQL Statements in the SQL Tab


Navigating the Query Window

When you start SQL Server CE Query Analyzer, the query window contains the following tabs: Objects, SQL, Grid, and Notes.

Objects tab
Use the Objects tab to manage databases and database connections, and explore, add, and drop database objects. When you connect to a database, you can view, add, and drop:
  • Tables
  • Table columns
  • Indexes
  • System tables (view only)

To perform these functions, use the buttons located either at the bottom of the screen on a Pocket PC device, or the top of the screen on a Handheld PC device. The availability of the buttons depends on the node that is selected in the database tree. For example, when you select a table, buttons are available for executing a SELECT * FROM table_name statement, adding a column to the table, creating an index on the table, and dropping the table. The following illustration shows SQL Server CE Query Analyzer as it appears on a Pocket PC device.

Screen shot: Objects tab showing the Employees table selected and the four enabled buttons labeled across the bottom of the tab.

A. Tap to execute a SELECT * FROM Employees statement.
B. Tap to add a column to the Employees table.
C. Tap to create an index on the Employees table.
D. Tap to drop the Employees table.

SQL tab
Is a command-line editor, which you can use to:
  • Type and execute SQL statements.
  • Manage SQL Server CE script files.
  • Save SQL statements directly in SQL Server CE Query Analyzer for editing and reuse.
Grid tab
Shows the results set of a query.
Notes tab
Displays messages after a command has been executed from either the Objects tab or the SQL tab. If a query executes successfully, a message provides information about the elapsed time and rows affected, if any. If a command results in an error or a query itself contains an error or unsupported SQL elements, a message provides error information, which includes the failed query and a short description.

The Notes tab contains a Copy button for selecting text and pasting to the SQL tab or a text editor. For information about errors, see SQL Server CE Errors.

The Tools Menu

The Tools menu is available in all four panes and contains the following items:

Refresh
Refreshes the view of the database tree in the Objects tab after any changes are made to the database.
Logging
When selected, logs corresponding SQL statements in the SQL tab when commands are executed in the Objects tab. Logged statements are not saved automatically. To save logged statements, see "Managing SQL Scripts" in Executing SQL Statements in the SQL Tab.
Fonts...
Changes the font settings of text in all four tabs.
About...
Provides version information about SQL Server CE and SQL Server CE Query Analyzer.
Exit
Exits SQL Server CE Query Analyzer.

Note If you exit SQL Server CE Query Analyzer without closing a database connection, when you restart SQL Server CE Query Analyzer, the Objects tab shows the last database connection and the last view.

The SQL Menu

The SQL menu is available only in the SQL tab. For more information about the SQL menu, see Executing SQL Statements in the SQL Tab.


Managing Databases and Database Connections in the Objects Tab

You must connect to a database before you can view, add, or drop database objects in the Objects tab; or before you can execute queries against a database in the SQL tab. Use the Objects tab to manage database connections. If you are connecting to a database for the first time, it is added to the list of managed databases in the Databases folder. If you are connecting to a database that was connected to previously, the database is listed under the Databases folder.

To connect to a database for the first time

  1. In the Objects tab, select the Databases folder.
  2. Tap the database connection button. The button must show a green arrow. If the button shows a red square, you are already connected to a database. Tap the button to disconnect. Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) allows only one database connection at a time.
    Database connection button | Indicates no current connection to the database. Tap to connect.
    Database connection button | Indicates an established connection to the database. Tap to disconnect.
  3. In the Connect to SQL Server CE dialog box, enter the path for the database or tab the browse (...) button to select a database.

    Note On a Handheld PC device, you can browse to the root directory to locate a database. On a Pocket PC device, you can browse to the My Documents folder. To locate databases at the root directory, which includes any sample databases, type a backslash (\) in front of the database name. For example, to connect to Northwind.sdf, type \Northwind.sdf.

  4. If the database is password protected, enter a password.
  5. Tap Connect.

To connect to a database that was connected to previously

  • In the Objects tab, expand the Databases folder, select the database, and then tap the database connection button.

    Note If a database connection is underway when you try to connect to another database, SQL Server CE drops the current connection and starts a new connection as part of the same operation.

    If you exit SQL Server CE Query Analyzer without closing a database connection, when you restart SQL Server CE Query Analyzer, the Objects tab shows the last database connection and the last view.

To disconnect from the current database

  • In the Objects tab, select either the Databases folder or the database you want to disconnect from, and then tap the database connection button. Before you tap, the button displays a red square. If the button displays a green arrow, you are already disconnected.

To remove a single database from the list of managed databases in the Databases folder

  1. Select the database you want to remove. If you are connected to the database, you must disconnect.
  2. Tap the database management button. In the message window that appears, tap OK.
    Database management button Tap to stop managing the database.

To remove all databases from the list of managed databases in the Databases folder

  1. Disconnect from the current database, if necessary.
  2. Select the Databases folder, and then tap the database management button.

To compact and repair a database

  1. Disconnect from the current database, if necessary.
  2. Select the database you want to compact and repair, and then tap the compact and repair button.
    Compact and repair button Tap to compact and repair the database.

For information about compacting and repairing a database, see Maintaining SQL Server CE Databases.


Managing Database Objects in the Objects Tab

In the Objects tab, you can add and drop databases, tables, and indexes; and define many of the most common properties of tables and indexes when you create them. For more specific table and index definition requirements, however, you must execute an SQL statement in the SQL tab.

To create a database

  1. In the Objects tab, select the Databases folder, and then tap the database connection button. The button must show a green arrow. If the button shows a red square, you are already connected to a database. Tap the button to disconnect. Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) allows only one database connection at a time.
  2. In the Connect to SQL Server CE dialog box, enter the path and name of the database, and then tap New Database.
  3. In the Password box, enter a password if you want the database to be password-protected. In the Sort box, select a database collation. The default collation, General, corresponds to Latin1_general. To encrypt the database, select Encrypt.

    Note Encryption must be used in conjunction with a password. Other conditions apply to implement encryption. For more information about passwords and encryption in SQL Server CE, see Using the SQL Server CE Database Security Features.

  4. Tap Create.

To create a table

  1. In the Objects tab, select either the database to which you are connected or the Tables folder of the database connection, and then tap the create table button.
    Create table button Tap to create a table.
  2. In the Table Definition dialog box, enter a name for the table, and then tap Insert Column.
  3. In the Column Definition dialog box, specify the properties of a column. The properties include: column name, data type, length (if applicable), nullability, precision, scale, and identity. You can also define a UNIQUE or PRIMARY KEY constraint and a default value for the column.

    Note When you create a table with a UNIQUE or PRIMARY KEY constraint, SQL Server CE automatically creates a unique index on that table. For more information, see Viewing and Modifying Index Properties.

    For information about the data types that SQL Server CE supports, see Data Types.

  4. To return to the Table Definition dialog box, tap OK. Either repeat the process for additional columns, or tap OK to finish.

To add a column to a table

  1. In the Objects tab, connect to a database, and expand the Tables folder.
  2. Expand the table you want to add a column to, select the Columns folder, and then tap the add column definition button.
    Column definition button Tap to add a column to a table.
  3. In the Column Definition dialog box, specify the properties of a column. The properties include: column name, data type, length (if applicable), nullability, precision, scale, and identity. You can also define a UNIQUE or PRIMARY KEY constraint and a default value for the column. To create the column, tap OK.

    Note When you create a table with a UNIQUE or PRIMARY KEY constraint, SQL Server CE automatically creates a unique index on that table. For more information, see Viewing and Modifying Index Properties.

For information about the data types that SQL Server CE supports, see Data Types.

To execute a SELECT * FROM table_name statement

  1. In the Objects tab, connect to a database, expand the Table folder, and then select a table.
  2. Tap the execute button. The results of the SELECT * FROM table_name statement appear in the Grid tab, and the messages appear in the Notes tab.
    Execute button Tab to execute a SELECT * FROM table_name statement.

To show/hide system tables

  • In the Objects tab, connect to a database, select the Tables folder, and then tap the system table button.
    View system tables button | Tap to view system tables.
    Hide system tables button | Tap to hide system tables.

To create an index

  1. In the Objects tab, connect to a database, and then expand the Tables folder.
  2. In the Tables folder, select the table you want to index (or expand that table and select the Indexes folder), and then tap the create index button.
    Create index button Tab to create an index.
  3. In the Index Definition dialog box, enter a name for the index. If the index is unique, select Unique.
  4. In the Columns list box, select the column(s) you want to base the index on. If you want the index sorted on that column in ascending order, tap A->. If you want the index sorted on that column in descending order, tap D->. To remove a column from the list of index keys, select the column and tap <-.
  5. Tap OK.

    Note When you create a table with a UNIQUE or PRIMARY KEY constraint, SQL Server CE automatically creates a unique index on that table. For more information, see Viewing and Modifying Index Properties.

For information about how to view and modify index properties, see Viewing and Modifying Index Properties.

To delete databases and database objects

  • To delete databases and database objects in the Objects tab, select the object you want to delete, and then tap the delete button. For example, if you want to drop the Territories table from the Northwind sample database, select Territories and tap the delete button. If you only want to drop the TerritoryDescription column of the Territories table, select TerritoryDescription and tap the delete button. In both cases, a warning message appears asking whether you are sure you want to drop the object.
    Delete button Tap to delete a database object.


Viewing and Modifying Index Properties

By expanding the Indexes folder of a table, you can view all the indexes of a table, including any unique indexes, as shown in the following illustration. (The illustrations in this topic show SQL Server CE Query Analyzer as it appears on a Pocket PC device.)

Screen shot: Objects tab showing the Indexes folder selected in the Order Details table. The enabled button and other screen elements are labeled.

A. Indexes on the Order Details table.
B. Tap to create a new index on the Order Details table.
C. Unique index.

By expanding an individual index, you can view the columns on which the index is built. The columns are listed in sort order (if the index is sorted on more than one column). To change the order in which a column appears, select the column and tap either the MOVE DOWN or MOVE UP arrow (see the following illustration).

You can also view whether a particular index column is sorted in ascending or descending order. The index column icon shows a downward pointing arrow if it is sorted in descending order, and an upward pointing arrow if it is sorted in ascending order. To change whether a particular column is sorted in ascending or descending order, select the column and tap the sort button (see the following illustration).

To remove a column from an index entirely, select the column and tap the delete icon (see the following illustration).

Screen shot: Objects tab showing the OrderID column selected in the PK_Order_Details index of the Order Details table. Screen elements are labeled.

A. Columns on which the PK_Order_Details index is built.
B. Tap to change the sort order of the OrderID column to ascending.
C. Tap to move the OrderID column down in the sort order of the PK_Order_Details index.
D. Tap to move the ProductID column up in the sort order of the PK_Order_Details index. (ProductID must be selected first.)
E. Tap to drop the OrderID column from the PK_Order_Details index.


Executing SQL Statements in the SQL Tab

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

  • You can execute queries comprised of one SQL statement, or multiple statements separated by a semicolon (;).
  • If no text is selected when executing, Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) attempts to execute all text in the SQL tab as a single batch.
  • You can perform text-editing tasks using the cut, copy, and paste buttons.
  • On the SQL menu, when Word Wrap is selected, SQL statements wrap to fit on the screen of the SQL tab. When Word Wrap is not selected, SQL statements flow beyond the screen.
    Execute button | Tap to execute an SQL statement or batch.
    Cut button | Tap to cut text.
    Copy button | Tap to copy text.
    Paste button | Tap to paste text.
Managing SQL Scripts

In the SQL tab, you can create new script files for SQL Server CE, open existing ones, and save the files to a directory. You can also save frequently used SQL statements directly in SQL Server CE Query Analyzer for editing and reuse. The following tasks are performed primarily by using the New, Open, and Save commands on the SQL menu.

To start a new SQL Server CE script file

  • On the SQL menu, tap New. This clears all text from the SQL tab to start a new script file.

To open a SQL Server CE script file

  • To open the most recent SQL Server CE script files that were previously accessed, tap the Tools menu, and then tap the file you want to open.

Or

  • On the SQL menu, tap Open, and in the Name list box, tap the script file you want to open. If the file you want to open does not appear in the Name list box, in the Folder box, select the directory of the file; and in the Type box, specify the file type.

To save a SQL Server CE script file

  • To save the current script file, on the SQL menu, tap Save. If the file already exists, the most recent version that appears in the SQL tab is saved in its current directory.

Or

  • If the script file is new, in the Save As dialog box, enter the appropriate information in the Name, Folder, Type, and Location boxes.
Saving Frequently Used SQL Statements for Editing and Reuse

You can save up to 10 frequently used SQL statements directly in SQL Server CE Query Analyzer, and browse the text of each statement simultaneously to determine which one you want to open for editing and reuse.

To save SQL statements

  1. In the SQL tab, select the text you want to save, and then tap the preset button.
    Preset button Tap to save an SQL statement.
  2. In the Button Presets dialog box, tap the preset button number (1 through 10) you want the statement to correspond to. The first line of the statement appears next to the button number. If any SQL statements have been added previously, the first line of their contents appears next to their assigned button numbers. If the button number corresponds to a previously added statement, the new statement overwrites it.
  3. To save, tap OK.

To open a saved statement

  • In the SQL tab, tap the preset button number corresponding to the saved statement. If you are not sure which button number to choose, tap the preset button to view the list of saved statements, and then tap Cancel to return to the SQL tab. The following illustration shows SQL Server CE Query Analyzer as it appears on a Pocket PC device.

    Screen shot: SQL tab showing the preset button numbers 1 - 10 across the top of screen and the five enabled buttons across the bottom.

    A. Tap to open a saved SQL statement. (Tap the number corresponding to the preset button number the statement was saved under.)
    B. Tap to view a list of saved SQL statements and their corresponding preset button numbers, or to save an SQL statement. (Text must be entered and selected to save an SQL statement.)

    If you edit the SQL statement after opening it, the changes will not be reflected in the Button Presets dialog box. To save the changes, repeat the save process for saving a statement described previously.


SQL Reference for SQL Server CE

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) includes SQL grammar that you can use to query a database and to insert, update, and delete data in tables in a database. The topics in this section describe the SQL grammar, as well as the items listed in the following table.

For information about | See
SQL syntax conventions and query elements | SQL Overview
Data types | Data Types
Functions | Functions
Information schema views | Information Schema
Operators | Operators
Reserved words | Reserved Words

SQL Server CE also includes SQL Server CE Query Analyzer, a tool you can use to query tables in a database. For more information, see Using SQL Server CE Query Analyzer.

The examples in the reference topics were tested using isqlw_wce and are not case sensitive. For more information about SQL grammar and Transact-SQL usage and examples, see SQL Server Books Online.


SQL Overview

You can use SQL grammar to query a database and to insert, update, and delete rows in tables in a database in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Syntax Conventions

The syntax diagrams in this reference use the following 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

You can use identifiers, delimiters, and comments when you query a database in SQL Server CE.

Identifiers

The name of a database object is known as an identifier. The object name is created when the object is defined; the identifier is used to reference the object.

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

  • object_name
  • table_name.object_name
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 as identifiers. The following 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 ' ' | String data values
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 temporarily disable certain parts of a SQL statement.

You can delineate text as comments using either of the following styles:

/* text_of_comment */
---- text_of_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

For more information, see Using SQL Server CE Query Analyzer.


+ (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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following example computes the total number of customers when 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

This 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following examples use the Orders table in the Northwind database to show how the positive and negative unary operators function. 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 a 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 '-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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) of any of the data types in the character and binary data type categories, except the image and ntext data types. 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

The following example uses the + operator to get an alphabetical 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 expression Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following example uses the subtraction arithmetic operator to get the number of days between the time a Northwind customer placed 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following examples use the Northwind database to show how the positive and negative unary operators function. 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'
--With the negative unary operator, the value returned is '12'.

SELECT (DATEPART(day, OrderDate) - DATEPART(day, ShippedDate)) FROM Orders WHERE OrderID = '10248'
--Without a 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 '-12'.


* (Multiply)

Multiplies two expressions (an arithmetic multiplication operator).

Syntax
expression * expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following 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'

This 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following example uses the divide arithmetic operator to determine the average total cost for each order of product 51 in the Northwind database. Product 51 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) of the integer data type category.
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

The following example uses modulo to identify employees in the Northwind database with even-numbered EmployeeID values.

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

This 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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

The following 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 when both operands are equal; otherwise, the result is FALSE.

Syntax
expression = expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following example uses the equals comparison operator to focus a search to a specific customer in the Orders table in the Northwind database.

SELECT * FROM Orders WHERE CustomerID = 'VINET'


> (Greater Than)

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

Syntax
expression > expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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 using this operator, the result is TRUE when the left operand has a value lower than the right operand; otherwise, the result is FALSE.

Syntax
expression < expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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 using this operator, the result is TRUE when the left operand has a value higher than or equal to the right operand; otherwise, the result is FALSE.

Syntax
expression > = expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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 using this operator, the result is TRUE when the left operand has a value lower than or equal to the right operand; otherwise, the result is FALSE.

Syntax
expression < = expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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 using this operator, the result is TRUE when the left operand is not equal to the right operand; otherwise, the result is FALSE.

Syntax
expression < > expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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 Not Equal To (<>).


!< (Not Less Than)

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

Syntax
expression ! < expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following example uses the not less than comparison operator to find all orders in the Order Details table of the Northwind database with quantities that are 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 using this operator, the result is TRUE when the left operand does not have a value higher than the right operand; otherwise, the result is FALSE.

Syntax
expression ! > expression
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence.
Result Types

bit

Examples

The following 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'


@@IDENTITY

Returns the last-inserted identity value.

Syntax
@@IDENTITY
Return Types

numeric


ABS

Returns the absolute, positive value of the given numeric expression.

Syntax
ABS ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that are implicitly convertible to float.
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example returns the absolute value of the difference between the units of products in stock and units of products that have been ordered in the Products table of the Northwind database.

SELECT (UnitsInStock - UnitsOnOrder), ABS(UnitsInStock - UnitsOnOrder)
FROM Products


ACOS

Returns the angle, in radians, whose cosine is the given float expression; also called arccosine.

Syntax
ACOS ( float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float, with a value from -1 through 1. Values outside this range return NULL and report a domain error.
Return Types

float

Examples

The following example returns the arccosine of the cosine of various angles.

CREATE TABLE Acosine ("COS(0)" float, "COS(PI()/6)" float, "COS(PI()/4)" float, "COS(PI()/3)" float, "COS(PI()/2)" float)
INSERT INTO Acosine VALUES (COS(0), COS(PI()/6), COS(PI()/4), COS(PI()/3), COS(PI()/2))
SELECT ACOS ("COS(0)"), ACOS ("COS(PI()/6)"), ACOS ("COS(PI()/4)"), ACOS ("COS(PI()/3)"), ACOS ("COS(PI()/2)")
FROM Acosine


ALL

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

Syntax
scalar_expression { = | <> | != | > | >= | !> | < | <= | !< } ALL ( subquery )
Arguments
scalar_expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
{ = | <> | != | > | >= | !> | < | <= | !< }
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.

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

Return Types

bit

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 > ::=
   [ NULL | NOT NULL ]
   [ CONSTRAINT constraint_name ]
   {
      | { 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 about 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 by 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, Microsoft® SQL Server™ 2000 Windows® CE Edition (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 int 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 that is loaded into the table.
increment
Is the incremental value added to the identity value of the previous row that is loaded.
ADD
Specifies that one or more column definitions, computed column definitions, or table constraints are added.
DROP { [CONSTRAINT] constraint_name | COLUMN column}
Specifies that constraint_name or column_name is to be 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.

ROWGUIDCOL automatically generates values for new rows inserted into the table.

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.
CONSTRAINT
Is an optional keyword indicating the beginning of a definition for a PRIMARY KEY, UNIQUE, or FOREIGN KEY constraint. 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.
PRIMARY KEY
Is a constraint that enforces entity integrity for a given column or columns using 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 using 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. You should not rely on this behavior nor 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 that is created when 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 when the corresponding referenced row is deleted from the parent table. If NO ACTION is specified, SQL Server CE 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 CE 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.
Alternately, if NO ACTION is specified, SQL Server CE raises an error and rolls back the delete action on the row in the Customers table when 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, when 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 CE 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: the 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 CE 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 CE raises an error and rolls back the update action on the referenced row in the Customers table when 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 definition of the constraint.
n
Is a placeholder indicating that the preceding item can be repeated n number of times.
Examples
A. Changing the seed and increment values on the identity column

The following 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 ('A. Datum Corporation')
ALTER TABLE MyCustomers ALTER COLUMN CustId IDENTITY (200, 2)
B. Adding a default value to the identity column

The following example modifies the CompanyName column so that it has a default value.

ALTER TABLE MyCustomers ALTER COLUMN CompanyName SET DEFAULT 'A. Datum Corporation'
C. Dropping a default value from the identity column

The following 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) that returns a Boolean value: TRUE, FALSE, or UNKNOWN.
Result Types

bit

Result Value

Returns TRUE when both expressions are TRUE.

Examples

The following example uses AND to get the total cost of a specific order for a particular product in the Northwind database.

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


ASIN

Returns the angle, in radians, whose sine is the given float expression (also called arcsine).

Syntax
ASIN ( float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float, with a value from -1 through 1. Values outside this range report a domain error.
Return Types

float

Examples

The following example returns the arcsine of the sine of various angles.

CREATE TABLE Asine ("SIN(0)" float, "SIN(PI()/6)" float, "SIN(PI()/4)" float, "SIN(PI()/3)" float, "SIN(PI()/2)" float)
INSERT INTO Asine VALUES (SIN(0), SIN(PI()/6), SIN(PI()/4), SIN(PI()/3), SIN(PI()/2))
SELECT ASIN("SIN(0)"), ASIN("SIN(PI()/6)"), ASIN("SIN(PI()/4)"), ASIN("SIN(PI()/3)"), ASIN("SIN(PI()/2)")
FROM Asine


ATAN

Returns the angle in radians whose tangent is the given float expression (also called arctangent).

Syntax
ATAN ( float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the arctangent of the tangent of various angles.

CREATE TABLE Atangent ("TAN(0)" float, "TAN(PI()/6)" float, "TAN(PI()/4)" float, "TAN(PI()/3)" float, "TAN(PI()/2)" float)
INSERT INTO Atangent VALUES (TAN(0), TAN(PI()/6), TAN(PI()/4), TAN(PI()/3), TAN(PI()/2))
SELECT ATAN("TAN(0)"), ATAN("TAN(PI()/6)"), ATAN("TAN(PI()/4)"), ATAN("TAN(PI()/3)"), ATAN("TAN(PI()/2)")
FROM Atangent


ATN2

Returns the angle, in radians, whose tangent is the quotient of two given float expressions (also called arctangent).

Syntax
ATN2 ( float_expression, float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float.
Return Types

float


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 categories, 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

The following example uses the Orders table in the Northwind database. The example determines the average freight shipped to a company that has a CustomerID of VINET in 1996.

--Get all OrderIDs for the VINET CustomerID.
SELECT OrderID, ShippedDate FROM Orders 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)

This 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). begin_expression must be the same data type as both test_expression and end_expression.
end_expression
Is any valid expression in SQL Server CE. 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

bit

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

The following example identifies the products in the Northwind database with 35 or fewer units in stock.

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


CASE

Evaluates a list of conditions and returns one of multiple possible result expressions.

CASE has two formats:

  • The simple CASE function compares an expression to a set of simple expressions to determine the result.
  • The searched CASE function evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

Syntax

Simple CASE function:

CASE input_expression
    WHEN when_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    ]
END

Searched CASE function:

CASE
    WHEN Boolean_expression THEN result_expression
        [ ...n ]
    [
        ELSE else_result_expression
    ]
END
Arguments
input_expression
Is the expression evaluated when using the simple CASE format. input_expression is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
WHEN when_expression
Is a simple expression to which input_expression is compared when using the simple CASE format. when_expression is any valid SQL Server expression. The data types of input_expression and each when_expression must be the same or must be implicitly converted.
n
Is a placeholder indicating that multiple WHEN when_expression THEN result_expression clauses, or multiple WHEN Boolean_expression THEN result_expression clauses can be used.
THEN result_expression
Is the expression returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid SQL Server expression.
ELSE else_result_expression
Is the expression returned if no comparison operation evaluates to TRUE. If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. else_result_expression is any valid SQL Server expression. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion.
WHEN Boolean_expression
Is the Boolean expression evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression.
Result Types

Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression.

Result Values

Simple CASE function:

  • Evaluates input_expression, and then, in the order specified, evaluates input_expression = when_expression for each WHEN clause.
  • Returns the result_expression of the first (input_expression = when_expression) that evaluates to TRUE.
  • If no input_expression = when_expression evaluates to TRUE, else_result_expression is returned if an ELSE clause is specified, or NULL if no ELSE clause is specified.

Searched CASE function:

  • Evaluates, in the order specified, Boolean_expression for each WHEN clause.
  • Returns result_expression of the first Boolean_expression that evaluates to TRUE.
  • If no Boolean_expression evaluates to TRUE, else_result_expression is returned if an ELSE clause is specified, or NULL if no ELSE clause is specified.
Examples

The following example returns the mode of shipping used for orders placed in the Northwind database.

SELECT ShipVia, CASE ShipVia
    WHEN 1 THEN 'Speedy Express'
    WHEN 2 THEN 'United Package'
    WHEN 3 THEN 'Federal Shipping'
        ELSE 'Unknown'
        END
FROM Orders


CEILING

Returns the smallest integer that is greater than, or equal to, the given numeric expression.

Syntax
CEILING ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that is implicitly convertible to float (except for the bit data type).
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

This example uses the CEILING function to round off the unit price for products in the Northwind database that are priced more than 100 dollars.

SELECT OrderID, UnitPrice, CEILING (UnitPrice) AS "CEILING"
FROM "Order Details"
WHERE UnitPrice > 100
ORDER BY UnitPrice


CHARINDEX

Returns the starting position of the specified expression in a character string.

Syntax
CHARINDEX ( expression1 , expression2 [ , start_location ] )
Arguments
expression1
Is an expression containing the sequence of characters to be found. expression1 is an expression of the ntext type or a data type that can be implicitly converted to nvarchar.
expression2
Is an expression, usually a column searched for the specified sequence. expression2 is an expression of the ntext type or a data type that can be implicitly converted to nvarchar.
start_location
Is the character position to start searching for expression1 in expression2. If start_location is not given, is a negative number, or is 0, the search starts at the beginning of expression2. start_location can be tinyint, smallint, int, or bigint.
Return Types

int

Examples

The following example searches for the expression 'an' from the last names of the employees in the Northwind database.

SELECT LastName, CHARINDEX('an', LastName) AS Position
FROM Employees

This is the result set:

LastName..............Position
------------------------------
Fuller................0
Peacock...............0
Callahan..............7
Davolio...............0
Leverling.............0
Buchanan..............5
Suyama................0
King..................0
Dodsworth.............0


COALESCE

Returns the first nonnull expression among its arguments.

Syntax
COALESCE ( expression [ ,...n ] )
Arguments
expression
Is an expression of any data type.
n
Is a placeholder indicating that multiple expressions can be specified. All expressions must be of the same type or must be implicitly convertible to the same type.
Return Types

Returns the highest precedence type from the set of types in expression.

Examples

In this example, the wages table is shown to include three columns with information about an employee's yearly wage: hourly_wage, salary, and commission. However, an employee receives only one type of pay. To determine the total amount paid to all employees, use the COALESCE function to receive only the nonnull value found in hourly_wage, salary, and commission.

CREATE TABLE wages
(
emp_id      int    identity,
hourly_wage   numeric   NULL,
salary      numeric    NULL,
commission   numeric   NULL,
num_sales   int   NULL
)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(10.00, NULL, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(20.00, NULL, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(30.00, NULL, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(40.00, NULL, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, 10000.00, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, 20000.00, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, 30000.00, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, 40000.00, NULL, NULL)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, NULL, 15000, 3)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, NULL, 25000, 2)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, NULL, 20000, 6)
INSERT wages (hourly_wage, salary, commission, num_sales) VALUES(NULL, NULL, 14000, 4)
SELECT CONVERT(money, COALESCE(hourly_wage * 40 * 52,
salary,commission * num_sales)) AS "Total Salary"
FROM wages


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 Microsoft® SQL Server™ 2000 Windows® CE Edition (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:
  • An alphabet or language whose sorting rules are applied when dictionary sorting is specified.
  • A 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 this option only.
AccentSensitivity
Specifies accent-sensitive (AS). SQL Server CE supports this option only.
Remarks

All databases created without specifying the Windows collation name are assigned Latin1_General, the default collation. This is an example of a Windows collation name: Latin1_General_CI_AS. This collation uses the Latin1 General dictionary sorting rules, code page 1252. It is case-insensitive and accent-sensitive.

Use the optional COLLATE clause to specify a collation different from the default. For example, to specify a Spanish collation, use a query such as:

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

The following table lists the supported Windows collation names. Ensure that the locale is supported on the device on which the database is created.

Note Some collation values might 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 (United Kingdom), 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 (Portugal)
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)


CONVERT

Explicitly converts an expression of one data type to another.

Syntax
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )
Arguments
data_type
Is the target system-supplied data type, including bigint.
length
Is an optional parameter of nchar, nvarchar, binary, or varbinary data types.
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
style
Is the style of date format used to convert datetime data to character data (nchar, nvarchar, nchar, or nvarchar data types), or the string format when converting float, real, or money data to character data (nchar, nvarchar, nchar, or nvarchar data types).

SQL Server CE supports the date format in Arabic style, using the Kuwaiti algorithm.

In the table, the two columns on the left represent the style values for datetime conversion to character data. Add 100 to a style value to get a four-place year that includes the century (yyyy).

Without century (yy) With century (yyyy)
Standard
Input/Output2
- 0 or 100 1 Default mon dd yyyy hh:miAM (or PM)
1 | 101 | USA | mm/dd/yy
2 | 102 | ANSI | yy.mm.dd
3 | 103 | British/French | dd/mm/yy
4 | 104 | German | dd.mm.yy
5 | 105 | Italian | dd-mm-yy
6 106 - dd mon yy
7 107 - Mon dd, yy
8 108 - hh:mm:ss
- 9 or 109 1 Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)
10 | 110 | USA | mm-dd-yy
11 | 111 | JAPAN | yy/mm/dd
12 | 112 | ISO | yymmdd
- 13 or 113 1 Europe default + milliseconds dd mon yyyy hh:mm:ss:mmm(24h)
14 114 - hh:mi:ss:mmm(24h)
- 20 or 120 1 ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
- 21 or 121 1 ODBC canonical (with milliseconds) yyyy-mm-dd hh:mi:ss.mmm(24h)
- 1263 ISO8601 yyyy-mm-dd Thh:mm:ss.mmm(no spaces)
- 1301 Hijri4 dd mon yyyy hh:mi:ss:mmmAM
- 1311 Hijri4 dd/mm/yy hh:mi:ss:mmmAM

1 The default values (style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121) always return the century (yyyy).
2 Input when converting to datetime; output when converting to character data.
3 Designed for XML use. For conversion from datetime or smalldatetime to character data, the output format is as described in the table. For conversion from float, money, or smallmoney to character data, the output is equivalent to style 2. For conversion from real to character data, the output is equivalent to style 1.
4 Hijri is a calendar system with several variations, of which Microsoft SQL Server 2000 uses the Kuwaiti algorithm.

The following table shows the style values for float or real conversion to character data.

Value | Output
0 (default) | Maximum of 6 digits. Use in scientific notation, when appropriate.
1 | Always 8 digits. Always use in scientific notation.
2 | Always 16 digits. Always use in scientific notation.

In the following table, the column on the left represents the style value for money conversion to character data.

Value | Output
0 (default) | No commas every 3 digits to the left of the decimal point, and 2 digits to the right of the decimal point (for example, 4235.98).
1 | Commas every 3 digits to the left of the decimal point, and 2 digits to the right of the decimal point (for example, 3,510.92).
2 | No commas every 3 digits to the left of the decimal point, and 4 digits to the right of the decimal point (for example, 4235.9819).
Return Types

Returns the same value as the data_type argument.

Remarks

Data Type Conversion Table

Examples

The following example converts a datetime value in the Northwind database to an nvarchar value.

SELECT OrderDate, CONVERT(nvarchar(10), OrderDate, 101)
FROM Orders


COS

A mathematic function that returns the trigonometric cosine of the given angle (in radians) in the given expression.

Syntax
COS ( float_expression )
Arguments
float_expression
Is an expression of data types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the cosine of various angles.

CREATE TABLE Cosine ("COS(0)" float, "COS(PI()/6)" float, "COS(PI()/4)" float, "COS(PI()/3)" float, "COS(PI()/2)" float)
INSERT INTO Cosine VALUES (COS(0), COS(PI()/6), COS(PI()/4), COS(PI()/3), COS(PI()/2))
SELECT * FROM Cosine


COT

A mathematic function that returns the trigonometric cotangent of the specified angle (in radians) in the given float expression.

Syntax
COT ( float_expression )
Arguments
float_expression
Is an expression of data types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the cotangent of various angles.

CREATE TABLE Cotangent ("COT(1)" float, "COT(PI()/6)" float, "COT(PI()/4)" float, "COT(PI()/3)" float, "COT(PI()/2)" float)
INSERT INTO Cotangent VALUES (COT(1), COT(PI()/6), COT(PI()/4), COT(PI()/3), COT(PI()/2))
SELECT * FROM Cotangent


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

int

Examples

The following example counts the discontinued items in the Products table in the Northwind database.

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

This 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, you must be connected to a database. For information about 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 is restricted by 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 is created in the current directory. The file extension for a database name in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) is .sdf.
'database_password'
Is the name of the password that allows for the database to be opened. 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 quotation marks.

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

collation_name
Specifies the default collation for the database. collation_name can only be a Windows collation. If collation_name is 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 supports only CI_AS (case insensitive and accent sensitive).

collation_name and comparison_style must not be enclosed in single or double quotation marks.

Examples
A. Creating a password-protected database

The following 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. Creating a database with a collation specified

The following 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.
Microsoft® SQL Server™ 2000 Windows® CE Edition (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. Duplicates must be eliminated before a unique index can be created on the column(s). 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 as NOT NULL.
When a unique index exists, UPDATE or INSERT statements that would generate duplicate key values are rolled back, and SQL Server CE returns an error. This is true even if the UPDATE or INSERT statement changes many rows but causes only one duplicate.
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; and DESC is descending.
n
Is a placeholder indicating that multiple columns can be specified for any particular index. The maximum number of columns that can participate in an index is 10.
Examples

The following example creates a unique index on the MyCustomers table.

CREATE TABLE MyCustomers (CustID int, 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 about 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 by 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, Microsoft® SQL Server™ 2000 Windows® CE Edition (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 int 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 that is loaded into the table.
increment
Is the incremental value added to the identity value of the previous row that is 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.

ROWGUIDCOL automatically generates 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 using 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 using 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. You should not rely on this behavior nor 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 that is created when 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 when the corresponding referenced row is deleted from the parent table. If NO ACTION is specified, SQL Server CE 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 CE 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.
Alternately, if NO ACTION is specified, SQL Server CE raises an error and rolls back the delete action on the row in the Customers table when 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 that is created when 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 when the corresponding referenced row is updated in the parent table. If NO ACTION is specified, SQL Server CE 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: the 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 CE 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 CE raises an error and rolls back the update action on the referenced row in the Customers table when 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
  • 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.
  • 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.
  • 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 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.
    • 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. FOREIGN KEY constraints cannot reference unique indexes.
  • 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

The following 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))

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

CREATE TABLE MyCustomers2 (CustID int CONSTRAINT pkCustId PRIMARY KEY)

The following 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))


DATALENGTH

Returns the number of bytes used to represent any expression.

Syntax
DATALENGTH ( expression )
Arguments
expression
Is an expression of any data type.
Return Types

int

Examples

The following example returns the DATALENGTH of each company name listed in the Customers table in the Northwind database.

SELECT DATALENGTH(CompanyName), CompanyName
FROM Customers


Data Types

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

Note There may be minor differences between Microsoft SQL Server 2000 and SQL Server CE in the way data types are promoted when the execution of a function results in an overflow or underflow. You might have 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 | 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 | Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
smallint | Integer data from –32,768 to 32,767. Storage size is 2 bytes.
tinyint | 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 | Floating point number data from -1.79E + 308 through 1.79E + 308 Storage size is 8 bytes.
real | Floating precision number data from -3.40E + 38 through 3.40E + 38.
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 Storage size, in bytes, is two times the number of characters entered.
national character varying(n) Synonym: nvarchar(n) | Variable-length Unicode data with a length of 1 to 255 characters. Default length = 1 Storage size, in bytes, is two times the number of characters entered.
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 of the integer data types 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 following table lists the dateparts and abbreviations recognized by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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. Is an expression of the exact numeric or approximate numeric data type categories, or types that can be implicitly converted to float. 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 value that can be implicitly converted to datetime, or is 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

The following example adds two months to the order date for A. Datum Corporation.

CREATE TABLE MyOrders (OrderID int IDENTITY(100, 1) PRIMARY KEY, CompanyName nvarchar(50), OrderDate datetime)
INSERT INTO MyOrders (CompanyName, OrderDate) VALUES ('A. Datum Corporation', 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 following table lists dateparts and abbreviations recognized by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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

int

Examples

The following example uses the Northwind database. The 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
-------------------------------------
10295           8
10737           7
10274           10
10248           12
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 following table lists dateparts and abbreviations recognized by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
weekday1 | dw
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

1 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 value that can be implicitly converted to a datetime value. date can also be 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 single 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 CE automatically converts between character and datetime values as necessary, for example, when you compare a character value with a datetime value.

Examples

The following 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 ('A. Datum Corporation', GETDATE())
SELECT DATENAME(month, OrderDate) AS "Month Name" FROM MyOrders

This 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 following table lists dateparts and abbreviations recognized by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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
date
Is an expression that returns a datetime value, or a value that can be implicitly converted to a datetime value. date can also be 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 single 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

int

Examples

The following example assumes the current month is August.

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

This is the result set:

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


DDL Statements

Microsoft® SQL Server™ 2000 Windows® CE Edition (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.

In SQL Server CE, to delimit identifiers that are keywords or do not conform to the rules for identifiers, you must use double quotation marks. Brackets are not supported. For more information, see SQL Overview.


DEGREES

Given an angle in radians, returns the corresponding angle in degrees.

Syntax
DEGREES ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or of types that are implicitly convertible to float.
Return Code Values

Returns the same type as numeric_expression, except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example returns the degree value of various angles expressed in radians.

CREATE TABLE "Degrees" ("PI()/2" float, "PI()/3" float, "PI()/4" float)
INSERT INTO "Degrees" VALUES (DEGREES(PI()/2), DEGREES(PI()/3), DEGREES(PI()/4))
SELECT * FROM "Degrees"


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, 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 might 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. Using DELETE with no parameters

The following example deletes all rows from the Customers table in the Northwind database.

DELETE Customers

B. Using DELETE on a set of rows

The following example uses the Customers table in the Northwind database. Because CompanyName may not be unique, the following example deletes all rows in which CompanyName is Eastern Connection.

DELETE FROM Customers WHERE CompanyName = 'Eastern Connection'


DML Statements

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports the following Data Manipulation Language (DML) statements.

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

In SQL Server CE, to delimit identifiers that are keywords or do not conform to the rules for identifiers, you must use double quotation marks. 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 KEY or UNIQUE 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.


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.

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

bit

Result Values

Returns TRUE if a subquery contains any rows.

Examples

The following example finds, from the Orders table, all the orders with Washington as the Shipping Region for Employees who are listed in the Employees table in the Northwind database.

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


EXP

Returns the exponential value of the given float expression.

Syntax
EXP ( float_expression )
Arguments
float_expression
Is an expression of data types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the exponential value of various float expressions.

CREATE TABLE Exponent ("EXP 5.5" float, "EXP 33.2" float)
INSERT INTO Exponent VALUES(EXP(5.5), EXP(33.2))
SELECT * FROM Exponent


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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) 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 are 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 the following 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 an 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.


FLOOR

Returns the largest integer less than or equal to the given numeric expression.

Syntax
FLOOR ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or of data types that are implicitly convertible to float.
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example applies the FLOOR function to the UnitPrice column of the Order Details table of the Northwind database.

SELECT OrderID, UnitPrice, FLOOR(UnitPrice) AS "Floor Value"
FROM "Order Details"
WHERE UnitPrice > 100
ORDER BY UnitPrice


FROM Clause

Specifies the table(s) from which to retrieve rows. In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), the FROM clause is always required; otherwise, an error is returned.

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 the 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.


Functions

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports the following functions.

Function | Description
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
Mathematical Functions | Perform calculations based on input values provided as parameters to the function, and return a numeric value.
ABS ACOS ASIN ATAN ATN2 CEILING COS COT | DEGREES EXP FLOOR LOG LOG10 PI POWER RADIANS | RAND ROUND SIGN SIN SQRT TAN
String Functions | Perform an operation on a string input value and return a string or numeric value.
NCHAR CHARINDEX LEN LOWER LTRIM | PATINDEX REPLACE REPLICATE RTRIM SPACE | STR STUFF SUBSTRING UNICODE UPPER
System Functions | Perform operations on, and return information about values, objects, and settings in SQL Server CE.
@@IDENTITY CASE | COALESCE CONVERT | DATALENGTH NEWID


GETDATE

Returns the current system date and time in the standard internal format for datetime values that are supported by Microsoft® SQL Server™ 2000 Windows CE Edition (SQL Server CE).

Syntax
GETDATE ( )
Return Types

datetime

Examples

The following 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 ('A. Datum Corporation', 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 nonaggregate 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 nonaggregate 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.

Note GROUP BY ALL is not supported in SQL Server CE.


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 nonaggregate expressions. The only columns that can be used in the nonaggregate 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 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.

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

Remarks

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), the IDENTITY property can be created only on a column of 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))

See Also

ALTER TABLE

CREATE TABLE


IN

Determines whether 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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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

bit

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

The following example selects all customers in the Northwind database who are from Brazil, Argentina, and Venezuela.

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


Information Schema

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) exposes meta data about the current database through the following INFORMATION_SCHEMA views.

View | Contains information about
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] )
       }
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 that the default value defined for a column is to be used by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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.
Remarks

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 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 null values, 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 you insert rows, the following rules apply:

  • If a value is being loaded into columns with an 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 following table.
    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.
Examples

A. Using a simple INSERT statement

The following 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. Inserting data that is not in the same order as the columns

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

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

C. Inserting data with fewer values than columns

The following example adds Liz Smith to the Employees table in the Northwind database without supplying a value for EmployeeID.

INSERT Employees (LastName, FirstName) VALUES ('Smith', 'Liz')


IS [NOT] NULL

Determines whether or not a given expression is NULL.

Syntax
expression IS [ NOT ] NULL
Arguments
expression
Is any valid expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
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

bit

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 whether 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.


LEN

Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks.

Syntax
LEN ( string_expression )
Arguments
string_expression
Is the string expression to be evaluated. string_expression can be any data type that can be implicitly converted to nvarchar. Binary expressions can also be supplied as arguments, in which case, the number of bytes is returned.
Return Types

int

Example

The following example returns the company names listed in the Customers table in the Northwind database along with the number of characters in the company name.

SELECT CompanyName, LEN(CompanyName)
FROM Customers


LIKE

Determines whether 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 a character string data type, Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) converts them to a character string data type, if possible.

Syntax
match_expression [ NOT ] LIKE pattern [ ESCAPE escape_character ]
Arguments
match_expression
Is any valid expression in SQL Server CE of nchar, nvarchar, or ntext data type.
pattern
Is the pattern to search for in match_expression and can include the following 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 expression in SQL Server CE 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

bit

Result Value

LIKE returns TRUE if the match_expression matches the specified pattern.


LOG

Returns the natural logarithm of the given float expression.

Syntax
LOG ( float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the logarithm of various float values.

CREATE TABLE Logarithms ("LOG 2" float, "LOG 20" float, "LOG 200" float)
INSERT INTO Logarithms VALUES (LOG(2), LOG(20), LOG(200))
SELECT * FROM Logarithms


LOG10

Returns the base-10 logarithm of the given float expression.

Syntax
LOG10 ( float_expression )
Arguments
float_expression
Is an expression of the type float, or of types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the base-10 logarithm of various float values.

CREATE TABLE "Base-10 Logarithms" ("LOG10 2" float, "LOG10 20" float, "LOG10 200" float)
INSERT INTO Logarithm VALUES (LOG10(2), LOG10(20), LOG10(200))
SELECT * FROM "Base-10 Logarithms"


LOWER

Returns a character expression after converting uppercase character data to lowercase.

Syntax
LOWER ( character_expression )
Arguments
character_expression
Is an expression of character or binary data type, or a data type that is implicitly convertible to nvarchar or ntext. Otherwise, use CAST to explicitly convert character_expression.
Return Types

nvarchar or ntext

Examples

The following example returns, in lower case, the list of company names in the Customers table in the Northwind database.

SELECT CustomerID, LOWER(CompanyName), City
FROM Customers


LTRIM

Returns a character expression after removing leading blanks.

Syntax
LTRIM ( character_expression )
Arguments
character_expression
Is an expression of character or binary data. character_expression must be of a data type that is implicitly convertible to nvarchar or ntext. Otherwise, use CAST to explicitly convert character_expression.
Return Types

nvarchar or ntext

Examples

The following example removes leading blanks from the names of customers listed in the MyCustomers table.

CREATE TABLE MyCustomers (CustID INTEGER IDENTITY (100,1) PRIMARY KEY, CompanyName nvarchar (50))
INSERT INTO MyCustomers (CompanyName) VALUES ('    A. Datum Corporation')
SELECT CustID, LTRIM(CompanyName)
FROM MyCustomers


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 of the same type as expression.

Remarks

MAX ignores any null values.

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

Examples

The following example uses MAX to determine the highest priced item in the Products table in the Northwind database.

SELECT MAX(UnitPrice)AS "Most Expensive" FROM Products

This is the result set:

Most Expensive
--------------
263.5


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 of the same type as expression.

Remarks

MIN ignores any null values.

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

Examples

The following example uses MIN to determine the lowest priced item in the Products table in the Northwind database.

SELECT MIN(UnitPrice) AS "Least Expensive" FROM Products

This is the result set:

Least Expensive
---------------
2.5


NCHAR

Returns the Unicode character with the given integer code, as defined by the Unicode standard.

Syntax
NCHAR ( integer_expression )
Arguments

integer_expression

Is a positive integer from 0 through 65535. integer_expression can also be of a data type that can be implicitly converted to int within the specified range. If a value outside this range is specified, NULL is returned.

Return Types

nchar(1)

Examples

The following example returns the first letter of each company name listed in the Customers table of the Northwind database.

SELECT CompanyName, NCHAR(UNICODE(CompanyName))
FROM Customers


NEWID

Creates a unique value of type uniqueidentifier.

Syntax
NEWID ( )
Return Types

uniqueidentifier

Examples

The following example returns a uniqueidentifier value that is inserted into a table using the NEWID function.

CREATE TABLE myTable(GuidCol uniqueidentifier, NumCol int)
INSERT INTO myTable Values(NEWID(), 4)
SELECT * FROM myTable


NOT

Negates a Boolean input.

Syntax
[ NOT ] boolean_expression
Arguments
boolean_expression
Is any valid Boolean expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
Result Types

bit

Result Value

NOT reverses the value of any Boolean expression.

Examples

The following example returns a list of all products that have a unit price less than 10 dollars and greater than 100 dollars.

SELECT ProductID, ProductName, UnitPrice
FROM Products
WHERE UnitPrice NOT BETWEEN 10 AND 100


Operators

Microsoft® SQL Server™ 2000 Windows® CE Edition (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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) that returns TRUE, FALSE, or UNKNOWN.
Result Types

bit

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 not valid 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

The following example lists employees by their first names.

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


PATINDEX

Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.

Syntax
PATINDEX ( '%pattern%' , expression )
Arguments
pattern
Is a literal string. Wildcard characters can be used; however, the % character must precede and follow pattern (except when searching for first or last characters). pattern is an expression of types that can be implicitly converted to nchar, nvarchar, or ntext.
expression
Is an expression, usually a column that is searched to find the specified pattern. expression can be nchar, nvarchar, or ntext.
Return Types

int

Examples

The following example searches the list of products that have the word Anton in their name.

SELECT ProductName, PATINDEX('%Anton%', ProductName)
FROM Products


PI

Returns the constant value of PI.

Syntax
PI ( )
Return Types

float


POWER

Returns the value of the given expression to the specified power.

Syntax
POWER ( numeric_expression , y )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that are implicitly convertible to float.
y
Is the power to which to raise numeric_expression. y can be an expression of types that are implicitly convertible to float.
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example raises the employee IDs in the Employees table in the Northwind database to the power of 3.

SELECT EmployeeID, POWER(EmployeeID, 3) AS Cube
FROM Employees
ORDER BY EmployeeID

This is the result set:

EmployeeID................Cube

--------------------------------

1................................1

2................................4

3................................9

4................................16

5................................25

6................................36

7................................49

8................................64

9................................81


RADIANS

Returns radians when a numeric expression, in degrees, is entered.

Syntax
RADIANS ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that are implicitly convertible to float.
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example returns the radian value of various angles.

CREATE TABLE Radians ("30 Degree", "60 Degrees", "90 Degrees")
INSERT INTO Radians VALUES(RADIANS(30.000000), RADIANS(60.000000), RADIANS(90.000000))
SELECT * FROM RADIANS


RAND

Returns a random float value from 0 through 1.

Syntax
RAND ( [ seed ] )
Arguments
seed
Is an integer expression that can be implicitly converted to int, which gives the seed or start value.
Return Types

float

Examples

The following example returns random float numbers based on three different seed values.

CREATE TABLE Random (Seed1 float, Seed5 float, Seed10 float)
INSERT INTO Random Values (RAND(1), RAND(5), RAND(10))
SELECT * FROM Random


REPLACE

Replaces all occurrences of the second given string expression in the first string expression with a third expression.

Syntax
REPLACE ( 'string_expression1' , 'string_expression2' , 'string_expression3' )
Arguments
'string_expression1'
Is the string expression to be searched. string_expression1 can be of data types that are implicitly convertible to nvarchar or ntext.
'string_expression2'
Is the string expression to try to find. string_expression2 can be of data types that are implicitly convertible to nvarchar or ntext.
'string_expression3'
Is the replacement string expression. string_expression3 can be of data types that are implicitly convertible to nvarchar or ntext.
Return Types

nvarchar or ntext

Examples

The following example searches for the name Anton in the list of product names and replaces it with Anthony.

SELECT REPLACE(ProductName, 'Anton', 'Anthony')
FROM Products


REPLICATE

Repeats a character expression for a specified number of times.

Syntax
REPLICATE ( character_expression , integer_expression )
Arguments
character_expression
Is an alphanumeric expression of character data, or other data types that are implicitly convertible to nvarchar or ntext.
integer_expression
Is an expression that can be implicitly converted to int. If integer_expression is negative, a null string is returned.
Return Types

nvarchar or ntext

Examples

The following example replicates (twice) the last name of each employee in the Employee table in the Northwind database.

SELECT REPLICATE (LastName, 2) AS "LastName Twice"
FROM Employees

This is the result set:

LastName Twice
--------------
FullerFuller
PeacockPeacock
CallahanCallahan
DavolioDavolio
LeverlingLeverling
BuchananBuchanan
SuyamaSuyama
KingKing
DodsworthDodsworth


Reserved Words

A reserved word in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) does not necessarily function the same way as the corresponding word in SQL Server 2000. The following table lists the reserved words used in SQL Server CE.

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

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


ROUND

Returns a numeric expression, rounded to the specified length or precision.

Syntax
ROUND ( numeric_expression , length [ , function ] )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that are implicitly convertible to float.
length
Is the precision to which numeric_expression is to be rounded. When length is a positive number, numeric_expression is rounded to the number of decimal places specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.
function
Is the type of operation to perform. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example returns the unit price, rounded to the nearest dollar, of products listed in the Products table of the Northwind database.

SELECT UnitPrice, ROUND(UnitPrice, 0)
FROM Products


RTRIM

Returns a character string after truncating all trailing blanks.

Syntax
RTRIM ( character_expression )
Arguments
character_expression
Is an expression of character or binary data, or other data types that are implicitly convertible to nvarchar or ntext. Otherwise, use CAST to explicitly convert character_expression.
Return Types

nvarchar or ntext

Examples

The following example removes trailing blanks from the names of customers listed in the MyCustomers table.

CREATE TABLE MyCustomers (CustID INTEGER IDENTITY (100,1) PRIMARY KEY, CompanyName nvarchar (50))
INSERT INTO MyCustomers (CompanyName) VALUES ('A. Datum Corporation   ')
SELECT CustID, RTRIM(CompanyName)
FROM MyCustomers


SELECT 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. SELECT does not modify, insert, or delete any data.

Syntax

The main clauses of a SELECT statement are:

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

A SELECT statement describes a query to the system. The execution of the query does not update any data. The query result is 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. The SELECT statement does not tell the system how to execute the query; instead, 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 following canonical execution strategy. 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.

Execution Strategy
  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 not valid.
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 results 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, but it cannot be used in a WHERE, GROUP BY, or HAVING clause.

Remarks

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), the SELECT statement must include a FROM clause to execute successfully; otherwise, SQL Server CE returns an error.


SIGN

Returns the positive (+1), zero (0), or negative (-1) sign of the given expression.

Syntax
SIGN ( numeric_expression )
Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type categories, or types that are implicitly convertible to float (except for the bit data type).
Return Types

Returns the same type as numeric_expression except for the following expressions.

Specified expression | Return type
tinyint, smallint | int
real/float | float
Nonnumeric types that can be implicitly converted to float | float
Examples

The following example returns the SIGN of the difference between the units of products in stock and units of products that have been ordered in the Products table of the Northwind database.

SELECT (UnitsInStock - UnitsOnOrder), SIGN(UnitsInStock - UnitsOnOrder)
FROM Products


SIN

Returns the trigonometric sine of the given angle (in radians) in an approximate numeric (float) expression.

Syntax
SIN ( float_expression )
Arguments
float_expression
Is an expression of data types that can be implicitly converted to float.
Return Types

float

Examples

The following example returns the sine of various angles.

CREATE TABLE Sine ("SIN(0)" float, "SIN(PI()/6)" float, "SIN(PI()/4)" float, "SIN(PI()/3)" float, "SIN(PI()/2)" float)
INSERT INTO Sine VALUES (SIN(0), SIN(PI()/6), SIN(PI()/4), SIN(PI()/3), SIN(PI()/2))
SELECT * FROM Sine


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 expression in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).
{ = | <> | != | > | >= | !> | < | <= | !< }
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

bit

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.


SPACE

Returns a string of repeated spaces.

Syntax
SPACE ( integer_expression )
Arguments
integer_expression
Is a positive integer, or an expression that can be implicitly converted to int, that indicates the number of spaces. If integer_expression is negative or greater than 255, a null string is returned.
Return Types

nvarchar

Examples

The following example uses the Employees table in the Northwind database. The example concatenates the last names of the employees, a comma, two spaces and the first names of the employees.

SELECT LastName + ',' + SPACE(2) + FirstName
FROM Employees


SQRT

Returns the square root of the given expression.

Syntax
SQRT ( float_expression )
Arguments
float_expression
Is an expression whose type can be implicitly converted to float.
Return Types

float

Examples

The following example returns the square root of the freight charges from the Orders table in the Northwind database.

SELECT Freight, SQRT(Freight) AS "Square root of Freight"
FROM Orders


STR

Returns character data converted from numeric data.

Syntax
STR ( float_expression [ , length [ , decimal ] ] )
Arguments
float_expression
Is an expression of that can be implicitly converted to float.

Note Do not use a function or subquery as the float_expression.

length
Is the total length, including decimal point, sign, digits, and spaces. The default is 10. length must be of a data type that can be implicitly converted to int.
decimal
Is the number of places to the right of the decimal point. decimal must be of a data type that can be implicitly converted to int. The default is 0.
Return Types

nvarchar

Examples

The following example converts expressions consisting of five digits and a decimal point to six-position character strings. The fractional part of the first number is rounded to one decimal place. The fractional part of the second number is rounded to two decimal places. The third number is returned without a decimal place.

CREATE TABLE t1 (Col1 float, Col2 float, Col3 float)
INSERT INTO t1 Values(123.45, 123.45, 123.45)
SELECT STR(Col1, 6,1), STR(Col2, 6,2), STR(Col3)
FROM t1


STUFF

Deletes a specified length of characters and inserts another set of characters at a specified starting point.

Syntax
STUFF ( character_expression , start , length , character_expression )
Arguments
character_expression
Is an expression that can be implicitly converted to nvarchar or ntext.
start
Is an integer value, or an expression that can be implicitly converted to int, that specifies the location to begin deletion and insertion. If start is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned.
length
Is an integer, or an expression that can be implicitly converted to int, that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression. If length is negative, a null string is returned.
Return Types

nvarchar or ntext

Examples

The following example deletes the second digit of the ProductID in the Products table in the Northwind database and replaces it with 000.

SELECT STUFF(ProductID, 2,1, '000')
FROM Products


SUBSTRING

Returns part of a character, binary, text, or image expression.

Syntax
SUBSTRING ( expression , start , length )
Arguments
expression
Is a character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.
start
Is an integer, or an expression that can be implicitly converted to int, that specifies where the substring begins.
length
Is an integer, or an expression that can be implicitly converted to int, that specifies the length of the substring (the number of characters or bytes to return).
Return Types

Returns character data if expression is one of the supported character data types. Returns binary data if expression is one of the supported binary data types.

The returned string is the same type as the given expression with the exceptions shown in the following table.

Given expression | Return type
image | varbinary
ntext | nvarchar
Examples

The following example uses the Employees table in the Northwind database. The example returns the initial of the employees' first names and the employees' last names.

SELECT SUBTRING(FirstName,1,1) AS Initial, LastName
FROM Employees

This is the result set:

Initial..........LastName
-------------------------
A................Fuller
M................Peacock
L................Callahan
N................Davolio
J................LeverLing
S................Buchanan
M................Suyama
R................King
A................Dodsworth


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 categories, 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

The following 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'

This is the result set:

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


TAN

Returns the tangent of the input expression.

Syntax
TAN ( float_expression )
Arguments
float_expression
Is an expression of data types that can be implicitly converted to float, interpreted as number of radians.
Return Types

float

Examples

The following example returns the tangent of various angles.

CREATE TABLE Tangent ("TAN(0)" float, "TAN(PI()/6)" float, "TAN(PI()/4)" float, "TAN(PI()/3)" float, "TAN(PI()/2)" float)
INSERT INTO Tangent VALUES (TAN(0), TAN(PI()/6), TAN(PI()/4), TAN(PI()/3), TAN(PI()/2))
SELECT * FROM Tangent


UNICODE

Returns the integer value, as defined by the Unicode standard, for the first character of the input expression.

Syntax
UNICODE ( 'ncharacter_expression' )
Arguments
'ncharacter_expression'
Is an expression whose type can be implicitly converted to nvarchar or ntext.
Return Types

int

Examples

The following example returns the names of the companies in the Northwind database along with the integer value, as defined by the Unicode standard, for the first character of each company name.

SELECT CompanyName, UNICODE(CompanyName)
FROM Customers
ORDER BY CompanyName


UNION

Combines the results of two or more queries into a single result set consisting of all the rows belonging to all queries in the union.

Syntax
    { < query specification > | ( < query expression > ) }
        UNION [ ALL ]
        < query specification | ( < query expression > )
            [ UNION [ ALL ] < query specification | ( < query expression > )
                [ ...n ] ]
Arguments
< query_specification > | ( < query_expression > )
Is a query specification or query expression that returns data to be combined with the data from another query specification or query expression. The definitions of the columns that are part of a UNION operation do not have to be identical, but they must be compatible through implicit conversion.
UNION
Specifies that multiple result sets are combined and returned as a single result set.
ALL
Incorporates all rows into the results, including duplicates. If not specified, duplicate rows are removed.
Examples

The following example returns the union of two SELECT statements.

CREATE TABLE t1 (a int, b nchar(4), c nchar(4))
INSERT INTO t1 VALUES (1, 'abc', 'jkl')
INSERT INTO t1 VALUES (2, 'def', 'mno')
INSERT INTO t1 VALUES (3, 'ghi', 'pqr')

CREATE TABLE t2 (a nchar(4), b float)
INSERT INTO t2 VALUES('jkl', 1.000)
INSERT INTO t2 VALUES('mno', 3.000)

SELECT a, b FROM t1
UNION
SELECT b,a FROM t2

This is the result set:

a ..........b
-------------
1...........abc
1...........jkl
2...........def
3...........ghi
3...........mno


UPDATE

Modifies existing data in a table in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

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. column_name must reside in the specified table and should be specified only once in the SET clause.
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

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

The following example changes the shipping address in the Orders table of the Northwind database for all orders made by the company with the customer ID of VINET.

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


UPPER

Returns a character expression with lowercase character data converted to uppercase.

Syntax
UPPER ( character_expression )
Arguments
character_expression
Is an expression of character or binary data that can be implicitly converted to nvarchar or ntext; otherwise, use CAST to explicitly convert character_expression.
Return Types

nvarchar or ntext

Examples

The following example queries the Customers table of the Northwind database and returns the names of the companies in uppercase.

SELECT CustomerID, UPPER(CompanyName)
FROM Customers
ORDER BY CompanyName


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, separated by an AND clause, that can be included in a search condition.
Examples

The following 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'

This is the result set:

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


Building Applications

This section provides the reference information to programmatically access Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Topic | Description
Development Tools | Provides background information for setting up Microsoft Visual Studio® .NET and Microsoft eMbedded Visual Tools.
ADOCE | Provides programming references for Microsoft ActiveX® Data Objects for Windows CE (ADOCE).
OLE DB and SQL Server CE | Provides programming references for OLE DB for SQL Server CE.
SQL Server CE Engine Object Programmer's Reference for eMbedded Visual Tools | Provides programming references for the SQL Server CE Engine object.
Remote Data Access | Provides programming references for the Remote Data Access (RDA) object.
Replication | Provides programming references for the Replication object.
.NET Compact Framework Data Providers | Provides programming information about the .NET Compact Framework data providers: System.Data.SqlServerCe and System.Data.SqlClient.
Error Handling | Provides programming references for error handling in SQL Server CE.


Development Tools

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports two development environments: Microsoft Visual Studio® .NET and Microsoft eMbedded Visual Tools. This topic provides general information about the setup requirements for these environments. Each environment requires additional configurations to develop applications for SQL Server CE.

Developing a Visual Studio .NET Application

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

To build a SQL Server CE application using Visual Studio .NET, you must install .NET Compact Framework and Microsoft® Visual Studio® .NET. This product provides all the necessary tools for developing Windows CE-based and Pocket PC-based applications for use with SQL Server CE. For more information, see Installing SQL Server CE with Visual Studio .NET.

To access SQL Server CE-specific objects, you must add a reference to the following Microsoft .NET Compact Framework data providers:

  • System.Data.SqlServerCe (for SQL Server CE)
  • System.Data.SqlClient (for SQL Server version 7.0 or later)

In addition, when you use either of these data providers, you must also add a reference to System.Data.Common. For more information, see .NET Compact Framework Data Providers and the .NET Compact Framework SDK.

You can test your application using the emulator; however, you cannot use Secure Sockets Layer (SSL) encryption when running your applications through the emulator.

Developing an eMbedded Visual Basic Application

To build a SQL Server CE application using eMbedded Visual Basic®, you must install SQL Server CE on a computer running the eMbedded Visual Tools environment. For more information, see Installing SQL Server CE with eMbedded Visual Tools

To build a SQL Server CE application by using Microsoft eMbedded Visual Basic, you must add the reference to Microsoft CE SQL Server Control 2.0. For more information, see Installing SQL Server CE on a Device Using eMbedded Visual Tools.

Debugging an eMbedded Visual Basic Application

When you run or debug your application, eMbedded Visual Basic automatically downloads and registers Ssce20.dll and Ssceca20.dll to the Windows CE-based device. Ssce20.dll implements the SQL Server CE database. SQL Server CE Client Agent (Ssceca20.dll) implements the Replication, RDA, and Engine objects.

Developing an eMbedded Visual C++ Application

For applications that call the Replication and RDA objects, you must include the following files in the eMbedded Visual C++® project:

  • Ca_mergex20.h
  • Ca_mergex20.lib
  • Ole32.lib
  • Oleaut32.lib

You must supply all required parameters for the eMbedded Visual C++ application. If all required parameters are not supplied with a method call, a compilation error occurs because default parameter values for method calls are not supported.

Debugging an eMbedded Visual C++ Application

Before you run or debug the application, you must manually download and register Ssce20.dll and Ssceca20.dll on the Windows CE-based device. Ssce20.dll implements the SQL Server CE database. SQL Server CE Client Agent (Ssceca20.dll) implements the Replication, RDA, and Engine objects.

See Also

Deploying Applications


ADOCE

The following topics in this section describe how you can use Microsoft® ActiveX® Data Objects for Windows® CE 3.1 (ADOCE) to create, access, and modify databases in Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE):

  • Setting Up a Project
  • Connecting to a SQL Server CE Database
  • Using ADOCE Batch Update

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.

ADOCE provides a subset of the desktop ADO specifically engineered to work with Microsoft Windows CE. ADOCE includes its own internal database provider and enables you to have access to databases stored locally on a Windows CE-based 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 more information about ADOCE, see the ADOCE documentation in the MSDN® Library at this Microsoft Web site.


Setting Up a Project

Before your applications can work with Microsoft® ActiveX® Data Objects for Windows CE 3.1 (ADOCE) and Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE), you must configure your projects so 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, and then click OK.

    Note Previous versions of the ADOCE control do 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 might be instantiated if it exists in the ROM of a device. If the device's ROM does not contain an earlier version, when you execute your application, the following error message appears:

    Invalid procedure call or argument: 'CreateObject'.

The following table shows the ProgIDs that 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

After you install SQL Server CE on a Windows CE-based device, you can reference SQL Server CE from a program. However, by defining a reference in your project, you 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 2.0 check box, and then 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 a Microsoft® ActiveX® Data Object for Windows® CE (ADOCE) Connection object by using the Set statement and CreateObject function. The following example shows how to do this:

Dim cn As ADOCE.Connection
Set cn = CreateObject("ADOCE.Connection.3.1")

Note When you use 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. Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) can be accessed only through ADOCE 3.1 or later.

After 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 example shows how to open a connection to a database on the device by using the Open method:

cn.ConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0; data source=\Northwind.sdf"
cn.Open

Caution You must specify the SQL Server CE provider string when you open a SQL Server CE database. If you do not specify a provider string in the Open method, Open defaults to using the proprietary Windows CE data source and creates a new Windows CE data source file named Test.sdf. This is the equivalent of specifying CEDB for the Provider property in the connection string.

In the previous 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 connection string. The data source property must be set with the full path and database name.

Disconnecting from a Database

After you make modifications and save them to the database, close the connection to the data source. The following 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 starting replication or remote data access (RDA).


Using ADOCE Batch Update

Microsoft® ActiveX® Data Objects for Windows® CE 3.1 (ADOCE) allows you 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 result in poor performance. Because Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) is running locally, all changes are done within the scope of the current computer. SQL Server CE implements updatable cursors in a very fast, efficient mechanism directly against the local storage engine. This mechanism provides good performance, but 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.


OLE DB and SQL Server CE

The OLE DB Provider for SQL Server CE is a set of COM-based interfaces that exposes data stored in a Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database as well as SQL Server CE Database Engine functionalities. The OLE DB Provider is the lowest level interface for accessing data in SQL Server CE, and all other data access mechanisms call through this interface. The OLE DB Provider for SQL Server CE is an OLE DB version 2.5-compliant provider. For more information about programming OLE DB, see the Microsoft OLE DB section of the Microsoft Data Access Components (MDAC) SDK documentation in the MSDN® Library at this Microsoft Web site.

This section contains two parts:

  • Programming OLE DB Applications for SQL Server CE

    Provides an overview about developing applications using the OLE DB Provider for SQL Server CE and information specific to programming against the OLE DB Provider for SQL Server CE.

  • OLE DB for SQL Server CE Programmer's Reference

    Provides reference material for the OLE DB Provider for SQL Server CE, including provider-specific interfaces, data types, and properties.

Code Examples

The following topics contain code examples that demonstrate using the OLE DB Provider for SQL Server CE.

Creating Databases | Constraints
Accessing Password-protected Databases | Transactions
Session Objects | Working with Large Data Types
Creating Indexes | Using ISSCECompact
Using the Seek Method | Using IRowsetPosition
Parameters |


Programming OLE DB Applications for SQL Server CE

The topics in this section provide a general overview of accessing and changing data in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) using the OLE DB Provider for SQL Server CE. The information is targeted towards direct clients of the OLE DB Provider but is not meant to be a complete resource for information about OLE DB and OLE DB programming. Differences between the OLE DB Provider for SQL Server CE and the core OLE DB interfaces are summarized in Differences in SQL Server CE-supported OLE DB Provider Interfaces. For more information about programming against OLE DB providers, see the Microsoft OLE DB section of the Microsoft Data Access Components (MDAC) SDK in the MSDN® Library at this Microsoft Web site.

This section contains the followings topics:

Data Source Objects | Parameters
Session Objects | Constraints
Commands | Transactions
Rowsets | Managing Database Objects
Cursors | Using SQL Server CE-specific Interfaces
Indexes |

For more information about supported properties, data types, schema rowsets, and provider-specific interfaces, see the OLE DB for SQL Server CE Programmer's Reference.


Data Source Objects

In OLE DB programming, the data source object represents a provider's underlying data store. To connect to an OLE DB provider, a consumer must first create and initialize an instance of the data source object. In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), the data source object is created by calling the OLE CoCreateInstance function and then passing the CLSID (class identifier) for the OLE DB Provider for SQL Server CE (CLSID_SQLSERVERCE_2_0). Because SQL Server CE is an in-process server, instances of SQL Server CE OLE DB objects are created using the CLSCTX_INPROC_SERVER macro to indicate the executable context.

SQL Server CE uses only the DBPROP_INIT_DATASOURCE property to specify the desired data source. This property is passed the full path to the database file to be opened. After setting this property, the consumer initializes the data source object, which establishes the environment necessary to exchange data between the consumer and SQL Server CE. After the data source object is initialized, the consumer can get self-descriptive information about the data store but cannot yet access data. This data source object can then be used to create one or more session objects, which in turn are used to create the necessary transactions, commands, and rowsets.

The OLE DB Provider for SQL Server CE also provides the ability to create a new database. For more information, see Creating Databases.

Password-protected databases are also supported. With this security feature, a password must be passed when the data source object is initialized. For more information, see Accessing Password-protected Databases.

Limitations of the Data Source Object

Some limitations of the data source object in the OLE DB Provider for SQL Server CE include:

  • The concept of a catalog as defined in OLE DB is not used in SQL Server CE. The DBPROP_INIT_DATASOURCE property defines the database to use, and the OLE DB Provider for SQL Server CE treats this database as the current catalog.
  • The ability to change the current data store is not supported. Clients that want to change the data store must uninitialize the data source object, set the new data store name, and then reinitialize the data source object.
  • SQL Server CE is single user, and only supports one initialized Data Source Object per database.
Provider-specific Data Source Properties

SQL Server CE supports the following provider-specific properties in the provider-specific property set DBPROPSET_SSCE_DBINIT:

  • DBPROP_SSCE_DBPASSWORD

    Used to specify the password for a password protected or encrypted database. For more information, see Accessing Password-protected Databases.

  • DBPROP_SSCE_ENCRYPTDATABASE

    Used to create an encrypted database. Encrypted databases are always password protected, so the DBPROP_SSCE_DBPASSWORD property will also be required. For more information, see Creating Databases.

  • DBPROP_SSCE_TEMPFILE_DIRECTORY

    Used to specify the location of the temporary database. For more information, see Specifying the Location of the Temporary Database Using OLE DB and Using SQL Server CE Temporary Databases.

See Also

Provider-specific Properties

Data Source Information Properties

Initialization Properties

Session Objects


Creating Databases

The OLE DB Provider for SQL Server CE exposes the IDBDataSourceAdmin interface through which you can create and manage databases in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). To create a new database, you must specify the DBPROP_INIT_DATASOURCE property to specify a name for the database. For security reasons, the OLE DB Provider for SQL Server CE does not support the ability to delete databases using IDBDataSourceAdmin::DestroyDataSource. If you want to delete a database and you have access to the file system on the computer, you can simply delete the database files that are no longer needed.

Creating Secure Databases

For improved security, SQL Server CE supports the ability to create both password protected and encrypted databases. Encrypted databases must also be password-protected. Data in a password-protected or encrypted database can be accessed by SQL Server CE only after the correct password has been provided.

Note If you forget the password for an encrypted database, the data is essentially lost.

For more information see, Using the SQL Server CE Database Security Features.

To create an encrypted database using the OLE DB Provider for SQL Server CE, you must pass the provider-specific property DBPROP_SSCE_ENCRYPTDATABASE as VARIANT_TRUE and specify a password by using the provider-specific property DBPROP_SSCE_DBPASSWORD. The following table summarizes the properties that must be specified to create each type of database.

Type of database to create | Required properties
Standard database | DBPROP_INIT_DATASOURCE
Password-protected database | DBPROP_INIT_DATASOURCE DBPROP_SSCE_DBPASSWORD
Encrypted database | DBPROP_INIT_DATASOURCE DBPROP_SSCE_DBPASSWORD DBPROP_SSCE_ENCRYPTDATABASE

For an existing database, these properties can be changed when the database is compacted. For more information, see Using ISSCECompact.

Examples

The following example shows how to create an encrypted database by using the OLE DB Provider for SQL Server CE. To create a password-protected only database or a standard database, remove the unnecessary DBPROP structures.

// Object declarations
HRESULT            hr                   = NOERROR;
DBPROPSET          dbpropset[2];
DBPROP             dbprop[1]; // Property array to initialize the provider.
DBPROP             sscedbprop[2]; // Property array for SSCE security properties
INT                i                    = 0;
IDBDataSourceAdmin *pIDBDataSourceAdmin = NULL;
IUnknown           *pIUnknownSession    = NULL;

// Create an instance of the OLE DB provider.
hr = CoCreateInstance( CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBDataSourceAdmin, (void**)& pIDBDataSourceAdmin);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize property structures.
VariantInit(&dbprop[0].vValue);
for (int i = 0; i < sizeof(sscedbprop) / sizeof(sscedbprop[0]); i++)
{
    VariantInit(&sscedbprop[i].vValue);
}

// Specify the property with name of the database.
dbprop[0].dwPropertyID  = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions   = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt   = VT_BSTR;
dbprop[0].vValue.bstrVal = SysAllocString(L"NewDatabase.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Specify the property for encryption.
sscedbprop[0].dwPropertyID = DBPROP_SSCE_ENCRYPTDATABASE;
sscedbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
sscedbprop[0].vValue.vt = VT_BOOL;
sscedbprop[0].vValue.boolVal = VARIANT_TRUE;

// Specify the password.
sscedbprop[1].dwPropertyID = DBPROP_SSCE_DBPASSWORD;
sscedbprop[1].dwOptions = DBPROPOPTIONS_REQUIRED;
sscedbprop[1].vValue.vt = VT_BSTR;
sscedbprop[1].vValue.bstrVal = SysAllocString(L"mypassword");
if(NULL == sscedbprop[1].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize the property sets.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties  = dbprop;
dbpropset[0].cProperties  = sizeof(dbprop)/sizeof(dbprop[0]);

dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT ;
dbpropset[1].rgProperties  = sscedbprop;
dbpropset[1].cProperties  = sizeof(sscedbprop)/sizeof(sscedbprop[0]);

// Create and initialize the database.
hr = pIDBDataSourceAdmin->CreateDataSource(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset, NULL, IID_IUnknown, &pIUnknownSession);
if(FAILED(hr))
{
    goto Exit;
}
// At this point, the new encrypted database is created.

Exit:
// Do cleanup tasks here.

return;

See Also

Data Source Objects

Accessing Password-protected Databases

Using the SQL Server CE Database Security Features


Specifying the Location of the Temporary Database Using OLE DB

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports the ability to specify an alternate location for the temporary database. This location can be set programmatically by specifying the DBPROP_SSCE_TEMPFILE_DIRECTORY property when a data source is initialized or when the ISSCECompact::Compact method is run. For more information, see Using SQL Server CE Temporary Database.

Examples

The following example shows how to specify the temporary database directory by specifying the DBPROP_SSCE_TEMPFILE_DIRECTORY property when calling IDBProperties::SetProperties.

// Object declarations
HRESULT          hr              = NOERROR;
DBPROPSET        dbpropset[2];
DBPROP           dbprop[1];
DBPROP           sscedbprop[1];

// Declare the provider interfaces.
IDBInitialize *  pIDBInitialize  = NULL;
IDBProperties *  pIDBProperties  = NULL;

// Initialize the data source.
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**) &pIDBInitialize);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize property structures
VariantInit(&dbprop[0].vValue);
VariantInit(&sscedbprop[0].vValue);

// 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"Northwind.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Second property set has one property containing the provider-specific
// property to specify an alternate temp file directory.
sscedbprop[0].dwPropertyID = DBPROP_SSCE_TEMPFILE_DIRECTORY;
sscedbprop[0].vValue.vt = VT_BSTR;
sscedbprop[0].vValue.bstrVal = SysAllocString(L"\\NewTempDir");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

// Initialize the provider-specific property set.
dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
dbpropset[1].rgProperties = sscedbprop;
dbpropset[1].cProperties = sizeof(sscedbprop)/sizeof(sscedbprop[0]);

// Set the properties into the provider's data source object.
pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);

hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize the data source.
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
   goto Exit;
}

Exit:
//Clean up resources here

return;

See Also

ISSCECompact

Provider-specific Properties

Using SQL Server CE-specific Interfaces


Accessing Password-protected Databases

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports a file-level access-control mechanism that requires that a password be presented to access a password-protected SQL Server CE database. This password must be passed each time the database is opened. Use the DBPROP_SSCE_DBPASSWORD property in the DBPROPSET_SSCE_DBINIT provider-specific property set to specify this property. When you create a database, this property can be used to specify a database password on the database. Encrypted databases are always password protected.

When you compact a database, this property can be used to change the database password to a new value. For more information about compacting a database, see Maintaining SQL Server CE Databases and Using SQL Server CE-specific Interfaces.

Examples

The following code example shows how to open a password-protected SQL Server CE database: (The password is requested from the user at runtime in a dialog box, the code for which is not included in this sample.)

// Object declarations
HRESULT          hr              = NOERROR;
DBPROPSET        dbpropset[2];
DBPROP           dbprop[1];
DBPROP           sscedbprop[1];
BSTR             pwdPassword; // user input password

// Declare the provider interfaces.
IDBInitialize *  pIDBInitialize  = NULL;
IDBProperties *  pIDBProperties  = NULL;

// Initialize the data source.
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**) &pIDBInitialize);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize property structures
VariantInit(&dbprop[0].vValue);
VariantInit(&sscedbprop[0].vValue);

// 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"ProtectedData.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Second property set has one property containing the provider-specific
// database password in the pwdPassword variable that was obtained from a
// dialog box (not shown).
sscedbprop[0].dwPropertyID = DBPROP_SSCE_DBPASSWORD;
sscedbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
sscedbprop[0].vValue.vt = VT_BSTR;
sscedbprop[0].vValue.bstrVal = SysAllocString(<pwdPassword>);
if(NULL == sscedbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

// Initialize the provider-specific property set.
dbpropset[1].guidPropertySet = DBPROPSET_SSCE_DBINIT;
dbpropset[1].rgProperties = sscedbprop;
dbpropset[1].cProperties = sizeof(sscedbprop)/sizeof(sscedbprop[0]);

// Set the properties into the provider's data source object.
pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);

hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize the data source.
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
   goto Exit;
}

Exit:
//Clean up resources here

return;

See Also

Data Source Objects

Provider-specific Properties

Using the SQL Server CE Database Security Features


Session Objects

The primary function of the session object is to define transactions, commands, and rowsets and for creating and modifying tables and indexes.

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), session properties can be set using the ISessionProperties interface.

From a session, you can:

  • Create a command object by calling IDBCreateCommand::CreateCommand. A single session can support multiple commands. For more information, see Commands.
  • Create a rowset by calling IOpenRowset::OpenRowset. For more information, see Rowsets.
  • Create a schema rowset by calling IDBSchemaRowset::GetRowset. For more information about the schema rowsets supported by SQL Server CE, see SQL Server CE Schema Rowsets.
  • Create or modify tables and indexes by using ITableDefinition and IIndexDefinition.
  • Begin and end transactions. For more information, see Transactions.
Provider-specific Session Properties

SQL Server CE supports the provider specific property DBPROP_SSCE_MAXBUFFERSIZE. This property is used to modify the amount of memory that the engine uses for caching. To change this value, pass DBPROP_SSCE_MAXBUFFERSIZE in the DBPROPSET_SSCE_SESSION property set to the ISessionProperties interface. For more information, see Provider-specific Properties.

Examples

The following example shows how to create a session object and modify the session properties to restrict the amount of cache that the database engine uses to 128 KB.

// Object declarations
HRESULT                  hr;
ULONG                    i                    = 0;
DBPROPSET                dbpropset[1];
DBPROP                   dbprop[1];
DBPROP                   sessionProps[1];

// Declare the provider interfaces.
IDBInitialize *          pIDBInitialize       = NULL;
IDBProperties *          pIDBProperties       = NULL;
IDBCreateSession *       pIDBCreateSession    = NULL;
ISessionProperties *     pISessionProperties  = NULL;

// Initialize the the data source object.
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, NULL, CLSCTX_INPROC_SERVER,
        IID_IDBInitialize, (LPVOID *) &pIDBInitialize);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize the the property set variants.
for (i = 0; i < sizeof(dbprop)/sizeof(dbprop[0]); i++)
{
    VariantInit(&dbprop[i].vValue);
}
for (i = 0; i < sizeof(sessionProps)/sizeof(sessionProps[0]); i++)
{
    VariantInit(&sessionProps[i].vValue);
}

dbprop[0].dwPropertyID   = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt = VT_BSTR;
dbprop[0].vValue.bstrVal = SysAllocString(L"\\windows\\Northwind.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

dbpropset[0].rgProperties    = dbprop;
dbpropset[0].cProperties     = sizeof(dbprop)/sizeof(dbprop[0]);
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;

// Set the properties into the provider's data source object.
hr = pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);
if(FAILED(hr))
{
    goto Exit;
}

hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize the data source.
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
   goto Exit;
}

// Initialize a session object.
hr = pIDBProperties->QueryInterface(IID_IDBCreateSession, (void **) &pIDBCreateSession);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pIDBCreateSession->CreateSession(NULL, IID_ISessionProperties,
    (IUnknown**) &pISessionProperties);

// Initialize the property to change the maximum buffer pool size.
sessionProps[0].dwPropertyID = DBPROP_SSCE_MAXBUFFERSIZE;
sessionProps[0].dwOptions = DBPROPOPTIONS_REQUIRED;
sessionProps[0].vValue.vt = VT_I4;
sessionProps[0].vValue.lVal = 128; // limit cache usage to 128K

// Initialize the session property set.
dbpropset[0].guidPropertySet = DBPROPSET_SSCE_SESSION;
dbpropset[0].rgProperties = sessionProps;
dbpropset[0].cProperties = sizeof(sessionProps)/sizeof(sessionProps[0]);

// Set the session property.
hr = pISessionProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);

Exit:

    // Clean up resources

    return;


Commands

In OLE DB, a command object is used to execute provider-specific text commands, similar to SQL statements. The basic steps for using commands in OLE DB are:

  1. A command object is created from an existing session object using IDBCreateCommand::CreateCommand.
  2. The command text for the query is specified using ICommandText.

    The command syntax supported by the OLE DB Provider for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) is specified as DBGUID_SQL. DBGUID_SQL syntax is primarily SQL-92 syntax with ODBC escape sequences.

  3. The command is executed using ICommand::Execute.

SQL Server CE supports a subset of the SQL Server Transact-SQL query grammar. Queries that can usually be run on SQL Server CE can also run on SQL Server 2000; however, many of the features of Transact-SQL are absent from SQL Server CE and only a single SQL statement can be executed in a command.

SQL Server CE supports parameterized queries in which parameters are delimited with the question mark (?) character; however, named parameterized queries and output parameters for queries are not supported. For more information about the query grammar supported by SQL Server CE, see SQL Reference for SQL Server CE.

Preparing Commands

To be able to execute a query, the database engine must first parse, compile, and optimize the SQL statement. 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. Commands can be prepared prior to execution by calling ICommandPrepare::Prepare. This is equivalent to compiling the command.

Examples

For examples of creating and executing commands using the OLE DB Provider for SQL Server CE, see the example in Parameters or the Employees.cpp file in the NorthwindOLEDB sample that ships with SQL Server CE.


Rowsets

Rowsets are the central objects that enable OLE DB components to expose and manipulate data in tabular form. A rowset object is a set of rows in which each row has columns of data. Using the OLE DB Provider for SQL Server CE, a rowset object is created either when ICommand::Execute returns data or by directly calling IOpenRowset::OpenRowset.

The following issues affect the handling of rowsets in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE):

  • SQL Server CE only supports the ability to retrieve one row at a time.
  • Rows should be retrieved sequentially by calling IRowset::GetNextRows(NULL, 0, 1...).
  • Rowsets can become zombies if the internal resource on which they depend goes away because a transaction aborts.
  • The OLE DB Provider for SQL Server CE supports data binding "by value" but not "by reference."
  • SQL Server CE always returns computed column values when inserting new 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. Because of this, the value for DBPROP_SERVERDATAONINSERT must always be VARIANT_TRUE.
  • There are other properties that correspond to various interfaces that can be supported on a rowset. Clients that do not request the interfaces that they want to use on the resulting interface through the property mechanism cannot necessarily access those interfaces, even if the cursor type selected can actually support that functionality. For more information, see Rowset Properties.

When you use rowsets, a number of factors can affect the efficiency of the operation. For more information, see Using Rowsets Efficiently.

See Also

SQL Server CE Schema Rowsets


Using Rowsets Efficiently

When you plan an efficient data access strategy for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), keep the following issues in mind:

When you use deferred update mode in OLE DB, specified by DBPROP_IRowsetUpdate being set to VARIANT_TRUE, SQL Server CE can only have one pending change at a time. This uses a fast mechanism to update internally.

  • IRowset::RestartPosition is efficient when used with scrollable cursors, but it can cause query reexecution when it is used with nonscrollable cursors. For more information, see Working with Cursors and Cursors.
  • Although SQL Server CE supports OLE DB data type coercions to and from DBTYPE_WSTR, it is best to use native data type bindings where possible to maximize performance against this engine.
  • SQL Server CE supports reading and writing to large image and ntext data types through the ISequentialStream and ILockBytes interfaces. For more information, see Working with Large Data Types.

See Also

Rowsets


Cursors

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports the base table, forward-only, and scrollable cursor types. When any of these supported cursors are used, the client can have only one open row. For more information about cursors, see Working with Cursors and "Cursors" in SQL Server Books Online.

The following table lists the rowset properties values that must be specified for SQL Server CE.

Rowset properties | Value
DBPROP_CANHOLDROWS | VARIANT_FALSE
DBPROP_MAXOPENROWS | 1
DBPROP_CANSCROLLBACKWARDS | VARIANT_FALSE

The following table shows the required property settings for each cursor type.

Property setting | Base table | Forward-only | Scrollable
DBPROP_BOOKMARKS | VARIANT_TRUE | VARIANT_FALSE | VARIANT_TRUE
DBPROP_OWNUPDATEDDELETE | VARIANT_TRUE | VARIANT_FALSE | VARIANT_FALSE
DBPROP_OWNINSERT | VARIANT_TRUE | VARIANT_FALSE | VARIANT_FALSE
DBPROP_OTHERUPDATEDELETE | VARIANT_TRUE | VARIANT_FALSE | VARIANT_FALSE
DBPROP_OTHERINSERT | VARIANT_TRUE | VARIANT_FALSE | VARIANT_FALSE
DBPROP_CANFETCHBACKWARDS | VARIANT_TRUE | VARIANT_FALSE | VARIANT_TRUE
DBPROP_QUICKRESTART | VARIANT_TRUE | VARIANT_FALSE | VARIANT_TRUE
Base Table Cursor

The base table cursor is the fastest of the supported cursors and the only cursor that interacts directly with the storage engine. This cursor supports updates, bookmarks, and indexes, as well as the Seek and SetRange methods of IRowsetIndex. The base table cursor optionally supports delayed update mode by exposing the IRowsetUpdate interface when the client passes DBPROP_IRowsetUpdate as TRUE. This cursor has dynamic membership; both DBPROP_OTHERINSERT and DBPROP_OTHERUPDATEDELETE properties are TRUE.

Base table cursors can be opened only by using IOpenRowset::OpenRowset. Using a "SELECT * FROM table" yields a query processor cursor (forward-only or scrollable) and not a base table cursor. Only base table cursors support updates.

Forward-only Cursor

Although the forward-only read-only cursor is the fastest query processor cursor and the second fastest cursor overall, this cursor provides the least amount of functionality. It does not support bookmarks or updates.

Scrollable Cursor

The scrollable read-only cursor is the most functional query processor cursor. The result set of this cursor is cached. This provides fast cursor restarts but makes it more resource intensive, especially for queries with large result sets. Because the results are cached, changes to the underlying base tables for a query are not reflected in the query results unless the query is reexecuted.


Indexes

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports indexes and several index-based operations to improve application performance.

When you work with indexes in SQL Server CE, it is important to keep the following issues in mind:

  • SQL Server CE supports only "integrated indexes" as defined in the Microsoft OLE DB documentation. This means that the index is logically part of the Rowset object 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 Microsoft SQL Server. For more information, see CREATE INDEX.
  • The name of the index is the only characteristic of an index that can be modified using IAlterIndex::AlterIndex against the OLE DB Provider for SQL Server CE.
  • To dynamically change the index while the rowset is open, you must request DBPROP_IRowsetCurrentIndex with a value of VARIANT_TRUE when opening the base table rowset. For more information, see Changing Indexes.
  • To be able to use the Seek and SetRange methods of the IRowsetIndex interface, you must request the property DBPROP_IRowsetIndex with a value of VARIANT_TRUE when opening the base table rowset.

For more information about index limitations, see Understanding SQL Server CE Database Objects.

See Also

Creating Indexes

Index Properties

Using the Seek Method


Creating Indexes

The OLE DB Provider for SQL Server CE exposes the ability to create indexes through IIndexDefinition::CreateIndex.

There are limitations on the use of indexes in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). For more information, see Indexes and Changing Indexes.

Examples

The following example shows how to use the OLE DB Provider for SQL Server CE to create a composite index over the LastName and FirstName columns in the Employees table of the Northwind database.

//Create an index on two columns.
HRESULT             hr;
DBID                TableName;
DBID                IndexName;
DBPROP              dbprop[1];
DBPROPSET           dbpropset[1];
DBPROP              indexdbprop[2];
DBPROPSET           indexdbpropset[1];
DBINDEXCOLUMNDESC   rgIndexColumnDescs[2];
DBID                dbidColumn1;
DBID                dbidColumn2;
IDBInitialize       *pIDBInitialize     = NULL;
IDBProperties       *pIDBProperties        = NULL;
IDBCreateSession    *pIDBCreateSession  = NULL;
IIndexDefinition    *pIIndexDefinition  = NULL;

VariantInit(&dbprop[0].vValue);
VariantInit(&indexdbprop[0].vValue);

// Create an instance of the OLE DB provider.
hr = CoCreateInstance(    CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**)&pIDBInitialize);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize a property with name of database.
// Open an exsiting database myDatabase.
dbprop[0].dwPropertyID     = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions         = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt         = VT_BSTR;
dbprop[0].vValue.bstrVal = L"\\windows\\Northwind.sdf";
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize the property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties     = dbprop;
dbpropset[0].cProperties     = sizeof(dbprop)/sizeof(dbprop[0]);

//Set initialization properties.
hr = pIDBInitialize->QueryInterface(IID_IDBProperties,

(void **)&pIDBProperties);
if(FAILED(hr))
{
    goto Exit;
}

// Sets properties in the Data Source and initialization property groups
hr = pIDBProperties->SetProperties(1, dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initializes a data source object
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
    goto Exit;
}

// Get the IDBCreateSession interface.
hr = pIDBInitialize->QueryInterface(IID_IDBCreateSession,
    (void**)&pIDBCreateSession);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create a session object.
hr = pIDBCreateSession->CreateSession(NULL, IID_IIndexDefinition,
    (IUnknown**) &pIIndexDefinition);

// (This sample assumes that we have information about the Employees table.
// database schema.)
// Prepare the table name DBID as Employees.
TableName.eKind          = DBKIND_NAME;
TableName.uName.pwszName = L"Employees";

// Prepare index name DBID as full_name_index.
IndexName.eKind          = DBKIND_NAME;
IndexName.uName.pwszName = L"full_name_index";

// Set up properties for IIndexDefinition::CreateIndex call. For this
// index,we enforce uniqueness through the DBPROP_INDEX_NULLS property.
// Index properties must have colid set to DB_NULLID.
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;

// Initialize the 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;
rgIndexColumnDescs[0].pColumnID      = &dbidColumn1;
rgIndexColumnDescs[1].eIndexColOrder = DBINDEX_COL_ORDER_ASC;
rgIndexColumnDescs[1].pColumnID      = &dbidColumn2;

// Specify the column names for the composite index on
// LastName and FirstName.
dbidColumn1.eKind = DBKIND_NAME;
dbidColumn1.uName.pwszName = L"LastName";
dbidColumn2.eKind = DBKIND_NAME;
dbidColumn2.uName.pwszName = L"FirstName";

// Create a two-column composite index named full_name_index over the
// LastName and FirstName columns in the Employees table.
hr = pIIndexDefinition->CreateIndex(&TableName, &IndexName,
    sizeof(rgIndexColumnDescs)/sizeof(rgIndexColumnDescs[0]),
    rgIndexColumnDescs, sizeof(indexdbpropset)/sizeof(indexdbpropset[0]),
    indexdbpropset, NULL);

Exit:

// When finished, clear the properties arrays and release interfaces.
// Uninitialize the environment.

return;

See Also

Index Properties


Changing Indexes

The following restrictions are imposed on clients when they attempt 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.

For more information, see Indexes.

See Also

Creating Indexes

Index Properties


Using the Seek Method

The Seek method is the most widely used method by clients on indexes in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Seek 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.

The IRowsetPosition interface is only supported on scrollable cursors. For more information, see Using IRowsetPosition or Cursors.

Examples

The following example shows how to use IRowsetIndex::Seek on an index using the OLE DB Provider for SQL Server CE. The sample is taken from the Employees.cpp file in the NorthwindOLEDB sample that ships with SQL Server CE. The example contains only the portions of the LoadEmployeeInfo function that relate to the Seek method.

///////////////////////////////////////////////////////////////////////
// The following steps have been removed from this sample. For the
// complete code, see the Employee.cpp file.
// 1) Verify that IDBCreateSession exists on the datasource.
// 2) Create a session object.
// 3) Set up information necessary to open a table
//    using an index and that has the ability to seek.
//    The index or interest is PK_Employees on the EmployeeID column
//    of the Employees table in Northwind.
///////////////////////////////////////////////////////////////////////

TableID.eKind            = DBKIND_NAME;
TableID.uName.pwszName    = (WCHAR*)TABLE_EMPLOYEE; //Northwind Employees

IndexID.eKind            = DBKIND_NAME;
IndexID.uName.pwszName    = L"PK_Employees";

// Request ability to use IRowsetChange interface.
rowsetpropset[0].cProperties     = 1;
rowsetpropset[0].guidPropertySet = DBPROPSET_ROWSET;
rowsetpropset[0].rgProperties    = rowsetprop;

rowsetprop[0].dwPropertyID       = DBPROP_IRowsetIndex;
rowsetprop[0].dwOptions          = DBPROPOPTIONS_REQUIRED;
rowsetprop[0].colid              = DB_NULLID;
rowsetprop[0].vValue.vt          = VT_BOOL;
rowsetprop[0].vValue.boolVal     = VARIANT_TRUE;

// Open the table using the index.
hr = pIOpenRowset->OpenRowset(NULL, &TableID, &IndexID,
    IID_IRowsetIndex, sizeof(rowsetpropset)/sizeof(rowsetpropset[0]),
    rowsetpropset, (IUnknown**) &pIRowsetIndex);
if(FAILED(hr))
{
    goto Exit;
}

// Get the IRowset interface.
hr = pIRowsetIndex->QueryInterface(IID_IRowset, (void**) &pIRowset);
if(FAILED(hr))
{
    goto Exit;
}

///////////////////////////////////////////////////////////////////////
// Steps to get column data using IcolumnsInfo have been removed
///////////////////////////////////////////////////////////////////////

// Create a DBBINDING array.
dwBindingSize = sizeof(pwszEmployees)/sizeof(pwszEmployees[0]);
prgBinding = (DBBINDING*)CoTaskMemAlloc(sizeof(DBBINDING)*dwBindingSize);
if (NULL == prgBinding)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Set initial offset for binding position.
dwOffset = 0;

// Prepare structures to create an accessor for each index.
for (dwIndex = 0; dwIndex < dwBindingSize; ++dwIndex)
{
    if (!GetColumnOrdinal(pDBColumnInfo, ulNumCols, pwszEmployees[dwIndex], &dwOrdinal))
    {
        hr = E_FAIL;
        goto Exit;
    }

    prgBinding[dwIndex].iOrdinal  = dwOrdinal;
    prgBinding[dwIndex].dwPart    = DBPART_VALUE | DBPART_STATUS | DBPART_LENGTH;
    prgBinding[dwIndex].obLength  = dwOffset;
    prgBinding[dwIndex].obStatus  = prgBinding[dwIndex].obLength + sizeof(ULONG);
    prgBinding[dwIndex].obValue   = prgBinding[dwIndex].obStatus + sizeof(DBSTATUS);
    prgBinding[dwIndex].pTypeInfo  = NULL;
    prgBinding[dwIndex].pBindExt   = NULL;
    prgBinding[dwIndex].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
    prgBinding[dwIndex].dwFlags    = 0;
    prgBinding[dwIndex].bPrecision = pDBColumnInfo[dwOrdinal].bPrecision;
    prgBinding[dwIndex].bScale     = pDBColumnInfo[dwOrdinal].bScale;

///////////////////////////////////////////////////////////////////////
// Case-specific binding information has been removed.
///////////////////////////////////////////////////////////////////////

    prgBinding[dwIndex].pObject    NULL;
    prgBinding[dwIndex].wType     = pDBColumnInfo[dwOrdinal].wType;
    if(DBTYPE_WSTR == pDBColumnInfo[dwOrdinal].wType)
    {
        prgBinding[dwIndex].cbMaxLen  = pDBColumnInfo[dwOrdinal].ulColumnSize
            * sizeof(WCHAR);
    }
    else
    {
        prgBinding[dwIndex].cbMaxLen  = pDBColumnInfo[dwOrdinal].ulColumnSize;
    }

    // Calculate and align the offset.
}

// Get IAccessor interface.
hr = pIRowset->QueryInterface(IID_IAccessor, (void**)&pIAccessor);
if(FAILED(hr))
{
    goto Exit;
}

// Create the accessor.
hr = pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA, dwBindingSize,
    prgBinding, 0, &hAccessor, NULL);
if(FAILED(hr))
{
    goto Exit;
}

// Allocate data buffer for seek and retrieve operation.
pData = (BYTE*)CoTaskMemAlloc(dwOffset);
if (NULL == pData)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Set data buffer to zero.
//
memset(pData, 0, dwOffset);

// Set data buffer for seek operation by specifying the
// dwEmployeeID variable that is passed to the function.
*(ULONG*)(pData+prgBinding[0].obLength)    = 4;
*(DBSTATUS*)(pData+prgBinding[0].obStatus) = DBSTATUS_S_OK;
*(int*)(pData+prgBinding[0].obValue)       = dwEmployeeID;

// Seek for the first row where the value of the selected column
// is dwEmployeeID.
hr = pIRowsetIndex->Seek(hAccessor, 1, pData, DBSEEK_FIRSTEQ);
if(FAILED(hr))
{
    goto Exit;
}

// Retrieve a row handle for the row resulting from the seek.
hr = pIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained,
    &prghRows);
if(FAILED(hr))
{
    goto Exit;
}

///////////////////////////////////////////////////////////////////////
// The Employee.cpp code performs programming logic here on the
// returned rowset, and then releases the rowset.
///////////////////////////////////////////////////////////////////////

Exit:

///////////////////////////////////////////////////////////////////////
// This is where the resources are released in Employee.cpp.
///////////////////////////////////////////////////////////////////////

return hr;

See Also

Indexes


Parameters

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports queries that contain parameters. Parameters can be used to replace column values in a query. You can get information about the parameters of a command, such as their data types, by using the ICommandWithParameters::GetParameterInfo. Parameters are then passed when ICommand::Execute is called.

Note The ICommandWithParameters::SetParameterInfo method should not be used to change the data types of parameters. Even when the type for a parameter is set using SetParameterInfo, the query processor in SQL Server CE makes the final decision as to the correct type, potentially overriding any changes.

For more information, see Using Parameters in Queries.

Examples

The following example method uses OLE DB to insert a new row into the Northwind Shippers table:

// Begin the method to insert data using parameters.
// Declarations
HRESULT                  hr;
IDBInitialize *          pIDBInitialize    = NULL;
IDBProperties *          pIDBProperties    = NULL;
IDBCreateSession *       pIDBCrtSession    = NULL;
DBPROPSET                rgPropSets[1];
DBPROP                   rgProps[1];
ULONG                    iPropSet          = 0;
ULONG                    iProp             = 0;
ICommandText *           pICmdText         = NULL;
IDBCreateCommand *       pIDBCrtCmd        = NULL;
ICommandPrepare *        pICmdPrepare      = NULL;
ICommandWithParameters * pICmdWParams      = NULL;
IAccessor *              pIAcc             = NULL;
ULONG                    cParams;
DBPARAMINFO *            rgParamInfo       = NULL;
OLECHAR *                pNamesBuffer      = NULL;
ULONG                    cBindings;
DBBINDING                rgBindings[3];
ULONG                    cbRowSize;
HACCESSOR                hAcc;
BYTE *                   pData             = NULL;
DBPARAMS                 params;
LONG                     cRowsAffected;

// Specify the Northwind database as wzDbName.
WCHAR  wzDbName[]  = L"\\windows\\Northwind.sdf";

// Initialize the property set values.and create the data source object.
for (ULONG i = 0; i < sizeof(rgProps)/sizeof(rgProps[0]); i++)
{
    VariantInit(&rgProps[i].vValue);
}

hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, NULL, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (LPVOID *) &pIDBInitialize);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

iProp = 0;
rgProps[iProp].dwPropertyID   = DBPROP_INIT_DATASOURCE;
rgProps[iProp].dwOptions = DBPROPOPTIONS_REQUIRED;
rgProps[iProp].vValue.vt = VT_BSTR;
rgProps[iProp].vValue.bstrVal = SysAllocString(wzDbName);
if(!(rgProps[iProp].vValue.bstrVal))
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}
iProp++;

iPropSet = 0;
rgPropSets[iPropSet].rgProperties    = rgProps;
rgPropSets[iPropSet].cProperties     = iProp;
rgPropSets[iPropSet].guidPropertySet = DBPROPSET_DBINIT;
iPropSet++;

// Set the properties into the provider's data source object.
pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);

hr = pIDBProperties->SetProperties(sizeof(rgPropSets)/sizeof(rgPropSets[iPropSet]),
    rgPropSets);
if(FAILED(hr))
{
    goto Exit;
}

// Create a session that supports commands.
hr = pIDBProperties->QueryInterface(IID_IDBCreateSession, (void **)
    &pIDBCrtSession);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pIDBCrtSession->CreateSession(NULL, IID_IDBCreateCommand,
    (IUnknown**) &pIDBCrtCmd);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the new command that uses parameters.
hr = pIDBCrtCmd->CreateCommand(NULL, IID_ICommandWithParameters,
    (IUnknown**) &pICmdWParams);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pICmdWParams->QueryInterface(IID_ICommandText, (void**) &pICmdText);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pICmdWParams->QueryInterface(IID_ICommandPrepare, (void**) &pICmdPrepare);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Specify the command text using parameter markers in the query syntax.
hr = pICmdText->SetCommandText(DBGUID_DBSQL, L"INSERT INTO Shippers \
(ShipperID, CompanyName, Phone) VALUES (?, ?, ?)");
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Prepare the current command.
hr = pICmdPrepare->Prepare(1);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Retrieving parameter information
hr = pICmdWParams->GetParameterInfo(&cParams, &rgParamInfo, &pNamesBuffer);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the acessor object and column specific bindings.

hr = pICmdText->QueryInterface(IID_IAccessor, (void**) &pIAcc);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the bindings for the three columns.
cBindings = 3;

rgBindings[0].iOrdinal = 1;
rgBindings[0].obStatus = 0;
rgBindings[0].obLength = rgBindings[0].obStatus + sizeof(DBSTATUS);
rgBindings[0].obValue = rgBindings[0].obLength + sizeof(ULONG);
rgBindings[0].pTypeInfo = NULL;
rgBindings[0].pObject = NULL;
rgBindings[0].pBindExt = NULL;
rgBindings[0].dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
rgBindings[0].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
rgBindings[0].eParamIO = DBPARAMIO_INPUT;
rgBindings[0].cbMaxLen = sizeof(int); //ShipperID is integer
rgBindings[0].dwFlags = 0;
rgBindings[0].wType = DBTYPE_I4;
rgBindings[0].bPrecision = 0;
rgBindings[0].bScale = 0;

rgBindings[1].iOrdinal = 2;
rgBindings[1].obStatus = rgBindings[0].obValue + rgBindings[0].cbMaxLen;
rgBindings[1].obLength = rgBindings[1].obStatus + sizeof(DBSTATUS);
rgBindings[1].obValue = rgBindings[1].obLength + sizeof(ULONG);
rgBindings[1].pTypeInfo = NULL;
rgBindings[1].pObject = NULL;
rgBindings[1].pBindExt = NULL;
rgBindings[1].dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
rgBindings[1].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
rgBindings[1].eParamIO = DBPARAMIO_INPUT;
rgBindings[1].cbMaxLen = 40 * sizeof(WCHAR); //CompanyName is nvarchar(40)
rgBindings[1].dwFlags = 0;
rgBindings[1].wType = DBTYPE_WSTR;
rgBindings[1].bPrecision = 0;
rgBindings[1].bScale = 0;

rgBindings[2].iOrdinal = 3;
rgBindings[2].obStatus = rgBindings[1].obValue + rgBindings[1].cbMaxLen;
rgBindings[2].obLength = rgBindings[2].obStatus + sizeof(DBSTATUS);
rgBindings[2].obValue = rgBindings[2].obLength + sizeof(ULONG);
rgBindings[2].pTypeInfo = NULL;
rgBindings[2].pObject = NULL;
rgBindings[2].pBindExt = NULL;
rgBindings[2].dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
rgBindings[2].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
rgBindings[2].eParamIO = DBPARAMIO_INPUT;
rgBindings[2].cbMaxLen = 24 * sizeof(WCHAR); //Phone is nvarchar(24)
rgBindings[2].dwFlags = 0;
rgBindings[2].wType = DBTYPE_WSTR;
rgBindings[2].bPrecision = 0;
rgBindings[2].bScale = 0;

// Calculate the total memory needed for the input buffer.
cbRowSize = rgBindings[2].obValue + rgBindings[2].cbMaxLen;

// Create the accessor for the parameter data.
hr = pIAcc->CreateAccessor(DBACCESSOR_PARAMETERDATA, cBindings,
    rgBindings, cbRowSize, &hAcc, NULL);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Allocate memory for the parameter data.
pData = (BYTE*) malloc(cbRowSize);
if(!(pData))
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

//Clear out the buffer.
memset(pData, 0, cbRowSize);

// Define the insert data for the parameters.
// Shipper ID
* (DBSTATUS*) (pData + rgBindings[0].obStatus) = DBSTATUS_S_OK;
* (int*)   (pData + rgBindings[0].obValue)  = 1;
* (ULONG*)   (pData + rgBindings[0].obLength) = sizeof(int);

// CompanyName
* (DBSTATUS*) (pData + rgBindings[1].obStatus) = DBSTATUS_S_OK;
wcscpy((WCHAR*) (pData + rgBindings[1].obValue), L"Federal Express");
* (int*)   (pData + rgBindings[1].obLength)  = wcslen(L"Federal Express") * sizeof(WCHAR);

// Phone
* (DBSTATUS*) (pData + rgBindings[2].obStatus) = DBSTATUS_S_OK;
wcscpy((WCHAR*) (pData + rgBindings[2].obValue), L"1-800-555-1212");
* (int*)   (pData + rgBindings[2].obLength)  = wcslen(L"1-800-555-1212") * sizeof(WCHAR);

// Define the DBPARAMS structure.
params.pData = pData;
params.cParamSets = 1;
params.hAccessor = hAcc;

// Execute the command with paramters.
hr = pICmdText->Execute(NULL, IID_NULL, &params, &cRowsAffected, NULL);

// Error handling for the command
if (FAILED(hr) || (1 != cRowsAffected))
{
    MessageBox(NULL,"An error occured","error",MB_OK);
}

Exit:

// Clean up resources.

free(pData);
CoTaskMemFree(rgParamInfo);
CoTaskMemFree(pNamesBuffer);

if(pIAcc)   pIAcc->Release();
if(pIDBProperties) pIDBProperties->Release();
if(pIDBCrtSession) pIDBCrtSession->Release();
if(pICmdPrepare) pICmdPrepare->Release();
if(pICmdWParams) pICmdWParams->Release();
if(pICmdText)  pICmdText->Release();
if(pIDBCrtCmd)  pIDBCrtCmd->Release();

for(i = 0; i < sizeof(rgProps)/sizeof(rgProps[0]); i++)
{
VariantClear(&rgProps[i].vValue);
}

return;


Constraints

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports constraints to enforce the data integrity rules in a database.

Note SQL Server CE database engine does place some limitations on constraint types and how they function. For more information, see Understanding SQL Server CE Database Objects.

Constraints are added to columns using the ITableDefinitionWithConstraints interface. For foreign key constraints, the matchType element of the DBCONSTRAINTDESC structure should always be set to DBMATCHTYPE_FULL.

Examples

The following example shows how to use OLE DB to add a new UNIQUE constraint to the Extension column in the Employees table of the Northwind database using the ITableDefinitionWithConstraints::AddConstraint method.

// Declarations
HRESULT                         hr;
DBID                            TableName;  // name of table for new constraint
DBID                            ColumnList[1]; // name of column for new constraint
DBID                            ConstraintName; // name of new constraint
DBPROP                          dbprop[1];
DBPROPSET                       dbpropset[1];
DBCONSTRAINTDESC                rgConstraintDescs[1]; // Structure for constraint properties
IDBInitialize                   *pIDBInitialize       = NULL;
IDBProperties                   *pIDBProperties       = NULL;
IDBCreateSession                *pIDBCreateSession    = NULL;
ITableDefinitionWithConstraints *pITbleDefWithConstrt = NULL; // supports adding constraints

if (FAILED(hr = CoInitialize(NULL)))
{
    return;
}

VariantInit(&dbprop[0].vValue);

// Create an instance of the OLE DB Provider
hr = CoCreateInstance(    CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**)&pIDBInitialize);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize a property with name of database
// Open an exsiting database myDatabase
dbprop[0].dwPropertyID     = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions         = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt         = VT_BSTR;
dbprop[0].vValue.bstrVal = L"\\windows\\Northwind.sdf";

// Initialize the property set
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties     = dbprop;
dbpropset[0].cProperties     = sizeof(dbprop)/sizeof(dbprop[0]);

//Set initialization properties.
hr = pIDBInitialize->QueryInterface(IID_IDBProperties,

(void **)&pIDBProperties);
if(FAILED(hr))
{
    goto Exit;
}

// Sets properties in the Data Source and initialization property groups
hr = pIDBProperties->SetProperties(1, dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initializes a data source object
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
    goto Exit;
}

// Get IDBCreateSession interface
hr = pIDBInitialize->QueryInterface(IID_IDBCreateSession,
    (void**)&pIDBCreateSession);
if (FAILED(hr))
{
    //Send error-specific message and do error handling
    goto Exit;
}

// Create a session object.
hr = pIDBCreateSession->CreateSession(NULL, IID_ITableDefinitionWithConstraints,
    (IUnknown**) &pITbleDefWithConstrt);

// (This sample assumes that we have information about the Employees table
// database schema.)
// Prepare the table name DBID as Employees.
TableName.eKind          = DBKIND_NAME;
TableName.uName.pwszName = L"Employees";

// Prepare the list of columns that will get the UNIQUE constraint.
// In this case, just the Extension column.
ColumnList[0].eKind = DBKIND_NAME;
ColumnList[0].uName.pwszName = L"Extension";

// Build the DBCONSTRAINTDESC structure needed to make the
// ITableDefinitionWithConstraints::AddConstraint
// call to add the constraint.
rgConstraintDescs[0].pConstraintID = &ConstraintName;
rgConstraintDescs[0].ConstraintType = DBCONSTRAINTTYPE_UNIQUE;
rgConstraintDescs[0].cColumns = 1;
rgConstraintDescs[0].rgColumnList = ColumnList;
rgConstraintDescs[0].Deferrability = 0;  // SQL Server CE constraints are not deferrable.
// The following properties are not used in UNIQUE constraints
rgConstraintDescs[0].pReferencedTableID = NULL;
rgConstraintDescs[0].cForeignKeyColumns = 0;
rgConstraintDescs[0].rgForeignKeyColumnList = NULL;
rgConstraintDescs[0].pwszConstraintText = NULL;
rgConstraintDescs[0].UpdateRule = DBUPDELRULE_NOACTION;
rgConstraintDescs[0].DeleteRule = DBUPDELRULE_NOACTION;
rgConstraintDescs[0].MatchType = DBMATCHTYPE_NONE;

// Add the new constraint
hr = pITbleDefWithConstrt->AddConstraint(&TableName, rgConstraintDescs);

Exit:

// When finished, clear the properties arrays and release interfaces.
// Uninitialize the environment.

Return;

See Also

Understanding SQL Server CE Database Objects


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 ITransactionLocal::Commit) or aborted (using ITransactionLocal::Abort).

Because the use of transactions in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) differs somewhat from that of Microsoft SQL Server, it is important to keep in mind the following provider-specific issues:

  • The ITransactionJoin interface is not supported because this interface requires that a provider be able to support two-phased commit transactions.
  • When a maximum of five levels of transaction nesting have been reached, StartTransaction returns an error indicating that no further transactions can be started.
  • The transaction isolation level, set by the DBPROP_SUPPORTEDTXNISOLEVELS property is always DBPROPVAL_TI_READCOMMITTED because SQL Server CE supports only the "Read Committed" isolation level. Attempting to specify a higher transaction isolation level causes StartTransaction to fail.
SQL Server CE holds an exclusive lock on a table that has been altered in a transaction until that transaction completes, which means that the value of DBPROP_SUPPORTEDTXNDDL property is always DBPROPVAL_TC_ALL.

For more information, see Using Transactions.

Examples

The following example that shows how to create and execute a transaction using the OLE DB Provider for SQL Server CE is taken from the Employees.cpp file in the NorthwindOLEDB sample that ships with SQL Server CE. The example contains only the transaction related portions of the InsertEmployeeInfo function.

///////////////////////////////////////////////////////////////////////
// The following steps have been removed from this sample. For the
// complete code, see the Employee.cpp file.
// 1) Verify that IDBCreateSession exists on the datasource.
// 2) Create a session object.
// 3) Set up information necessary to open a table using an index.
// 4) Set the binding properties and create the accessor.
///////////////////////////////////////////////////////////////////////

// Begins a new local transaction to insert employee data
hr = pITxnLocal->StartTransaction(ISOLATIONLEVEL_READCOMMITTED | ISOLATIONLEVEL_CURSORSTABILITY, 0, NULL, NULL);
// Error handling for failed creation of the transaction
if(FAILED(hr))
{
    goto Exit;
}
///////////////////////////////////////////////////////////////////////
// The code to prepare the sample data to insert has been removed.
// See the original source file Employee.cpp for the complete method.
///////////////////////////////////////////////////////////////////////

hr = pIRowsetChange->InsertRow(DB_NULL_HCHAPTER, hAccessor, pData, prghRows);
// Error handling that aborts the transaction on failure
if (FAILED(hr))
{
    goto Abort;
}

// Get the row data.
hr = pIRowset->GetData(rghRows[0], hAccessor, pData);
if(FAILED(hr))
{
    goto Abort;
}

// Check the status.
if (DBSTATUS_S_OK != *(DBSTATUS*)(pData+prgBinding[dwPhotoCol].obStatus))
{
    hr = E_FAIL;
    pIRowset->ReleaseRows(1, prghRows, NULL, NULL, NULL);
    goto Abort;
}

///////////////////////////////////////////////////////////////////////
// The complete sample performs a transactional task here.
///////////////////////////////////////////////////////////////////////

// Commit the transaction using ITransactionLocal::Commit
// to insert the data.
if (pITxnLocal)
{
    pITxnLocal->Commit(FALSE, XACTTC_SYNC, 0);
}

goto Exit;

 // Calling goto Abort uses the ITransactionLocal::Abort
 // to cancel the transaction.

Abort:
// Cancel the transaction.
if (pITxnLocal)
{
    pITxnLocal->Abort(NULL, FALSE, FALSE);
}

Exit:
// Release the resources.


Data Types Supported in SQL Server CE

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) contains a subset of data types that are upwardly compatible with SQL Server; however, there are some differences:

  • 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.
  • The maximum sizes of variable-length columns differ between SQL Server and SQL Server CE. SQL Server supports variable-length nvarchar and varbinary types up to 8,000 bytes long, and SQL Server CE supports a maximum size of 510 bytes. If necessary, the appropriate larger types (ntext and image) can be used to store more data in a column. For more information, see Working with Large Data Types.

For generically exposed type information about the OLE DB Provider for SQL Server CE, see the PROVIDER_TYPES schema rowset in SQL Server CE Schema Rowsets.

The following table shows the mapping of native data types in SQL Server CE to the standard OLE DB data types, including any related properties and limitations. For a table showing the data type mapping between SQL Server CE and Microsoft ActiveX® Data Objects Extensions (ADOX), see SQL Server CE Data Type Mapping from ADOX.

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
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_BYTES | DBPROP_COL_FIXEDLENGTH = VARIANT_FALSE |


SQL Server CE Data Type Mapping from ADOX

The following table shows the data type mapping between Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) and Microsoft ActiveX® Data Objects Extensions (ADOX).

ADOX data type | SQL Server CE data type | Notes
adSmallInt | smallint |
adInteger | integer |
adSingle | real |
adDouble | float |
adCurrency | money |
adBoolean | bit |
adUnsignedTinyInt | tinyint |
adBigInt | bigint |
adGUID | uniqueidentifier |
adVarBinary | varbinary |
adBinary | binary |
adVarWChar | nvarchar | The size of this column must be specified.
adWChar | nchar | The size of this column must be specified.
adNumeric | numeric | The precision must be specified.
adDBTimestamp | datetime |
adLongVarBinary | image |
adLongVarWChar | ntext |


Working with Large Data Types

The OLE DB Provider for SQL Server CE supports the ISequentialStream and ILockBytes interfaces for accessing large data values in the provider in pieces. ISequentialStream allows clients to read parts of a long-value column in a sequential, forward-only manner, and ILockBytes can access data in a random fashion. By using these structured storage interfaces to access arbitrarily large data values (image and ntext data types), you can avoid potential errors caused by the system trying to read the value into memory in one complete piece.

Examples

The following example shows how to use the ILockBytes::ReadAt method to retrieve binary large object (BLOB) data. This example reads image data from the Photo column of the Employees table in the Northwind sample database.

// Declarations
HRESULT            hr;
DBBINDING          rgBindings[1];
DBPROP             dbprop[1];
DBPROPSET          dbpropset[1];
DBOBJECT           dbObject;
BYTE               pData[100];    //buffer for holding the ILockBytes pointer
HROW               rghRows[1]; // Array of row handles obtained from the rowset object
HROW               *prghRows           = rghRows;
BYTE               pBuffer[1000];  //Buffer for holding a chunck of BLOB data
ULARGE_INTEGER     ulOffset;
ULONG              cRows               = 0;
IDBInitialize      *pIDBInitialize     = NULL;
IDBProperties      *pIDBProperties     = NULL;
IDBCreateSession   *pIDBCreateSession  = NULL;
IDBCreateCommand   *pIDBCreateCommand  = NULL;
ICommandText       *pICommandText      = NULL;
IAccessor          *pIAccessor         = NULL;
IRowset            *pIRowset           = NULL;
ILockBytes         *pILockBytes        = NULL;
HACCESSOR          hAccessor           = DB_NULL_HACCESSOR;

if (FAILED(hr = CoInitialize(NULL)))
{
    return;
}

VariantInit(&dbprop[0].vValue);

// Create an instance of the OLE DB Provider
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
                IID_IDBInitialize, (void**)&pIDBInitialize);
if(FAILED(hr))
{
    //Send error-specific message and do error handling
    goto Exit;
}

// Initialize a property with name of the database
// Open an exsiting database myDatabase
dbprop[0].dwPropertyID     = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions         = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt         = VT_BSTR;
dbprop[0].vValue.bstrVal = SysAllocString(L"\\windows\\Northwind.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize the property set
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties     = dbprop;
dbpropset[0].cProperties     = sizeof(dbprop)/sizeof(dbprop[0]);

//Set initialization properties.
hr = pIDBInitialize->QueryInterface(IID_IDBProperties,
                (void **)&pIDBProperties);
if(FAILED(hr))
{
    goto Exit;
}

// Sets properties in the data source and initialization property groups
hr = pIDBProperties->SetProperties(1, dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initializes a data source object
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
    goto Exit;
}

// Get the IDBCreateSession interface
hr = pIDBInitialize->QueryInterface(IID_IDBCreateSession,
    (void**)&pIDBCreateSession);
if (FAILED(hr))
{
    //Send error-specific message and do error handling
    goto Exit;
}
// Get the interface to create a command
hr = pIDBCreateSession->CreateSession(NULL, IID_IDBCreateCommand,
    (IUnknown**) &pIDBCreateCommand);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the new command that uses parameters.
hr = pIDBCreateCommand->CreateCommand(NULL, IID_ICommandText, (IUnknown**) &pICommandText);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Specify the command text using parameter markers in the query syntax.
// We know that this command will return 1 row and one image column (Photo).
hr = pICommandText->SetCommandText(DBGUID_DBSQL, L"SELECT Photo FROM Employees WHERE \"Employee ID\" = 2");
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pICommandText->Execute(NULL, IID_IRowset, NULL, NULL, (IUnknown**) &pIRowset);
if(FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the acessor object and column specific bindings.

hr = pIRowset->QueryInterface(IID_IAccessor, (void**) &pIAccessor);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Create the bindings for the photo (BLOB) column
dbObject.dwFlags = STGM_READ;
dbObject.iid     = IID_ILockBytes;
rgBindings[0].iOrdinal = 1;
rgBindings[0].obStatus = 0;
rgBindings[0].obLength = rgBindings[0].obStatus + sizeof(DBSTATUS);
rgBindings[0].obValue = rgBindings[0].obLength + sizeof(ULONG);
rgBindings[0].pTypeInfo = NULL;
rgBindings[0].pObject = &dbObject;
rgBindings[0].pBindExt = NULL;
rgBindings[0].dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
rgBindings[0].dwMemOwner = DBMEMOWNER_CLIENTOWNED;
rgBindings[0].eParamIO = DBPARAMIO_NOTPARAM;
rgBindings[0].cbMaxLen = sizeof(IUnknown*);
rgBindings[0].dwFlags = 0;
rgBindings[0].wType = DBTYPE_IUNKNOWN;
rgBindings[0].bPrecision = 0;
rgBindings[0].bScale = 0;

// Create accessor.
hr = pIAccessor->CreateAccessor(DBACCESSOR_ROWDATA, 1, rgBindings,
    0, &hAccessor, NULL);
if(FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

//Get the first row
hr = pIRowset->GetNextRows(NULL, 0, 1, &cRows, &prghRows);
if(FAILED(hr) || (0 == cRows))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

//Get the ILockBytes pointer
hr = pIRowset->GetData(rghRows[0], hAccessor, pData);
if(FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

if(DBSTATUS_S_OK != *(DBSTATUS*)(pData + rgBindings[0].obStatus))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Get the ILockBytes pointer from the buffer.
pILockBytes = *(ILockBytes**)(pData + rgBindings[0].obValue);

// Initialize Offset.
ulOffset.QuadPart = 0;

// Retrieve data from the interface in chunks.
// The infinite loop, for(;;), will terminate when the ReadAt call fails
// or if less bytes are returned than were requested.
for(;;)

{

    ULONG cbRead;

    // Read data at the specified offset
    hr = pILockBytes->ReadAt(ulOffset, pBuffer, sizeof(pBuffer)-sizeof(WCHAR),
    &cbRead);

/////////////////////////////////////////////////////////////////////////
// Do some useful things here with the chunks of data
/////////////////////////////////////////////////////////////////////////

    if(cbRead < sizeof(pBuffer)-sizeof(WCHAR) || FAILED(hr)) break;

    ulOffset.QuadPart += cbRead;
}

//If more rows need to be read, then release the ILockBytes pointer and
// row handle here

Exit:

// When finished, clear the properties arrays and release interfaces.
// Uninitialize the environment.

return;

See Also

Data Types

ILockBytes

Data Types Supported in SQL Server CE


Managing Database Objects

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) requires that objects be opened exclusively to modify those objects. All ITableDefinition methods open tables for exclusive access. If another method already has the table open, the ITableDefinition method call fails. 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. It is recommended that you be aware of locking issues when designing your application, particularly when using transactions. For more information, see Using Transactions.

Some information about columns can also be modified using IAlterTable::AlterColumn. Because columns have more items that could potentially be modified, the DBPROP_ALTERCOLUMN property describes the portions of the DBCOLUMNDESC structure defining the column that can be modified. However, even if the provider supports modifying properties, this 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)

See Also

SQL Server CE-specific OLE DB Properties


Using SQL Server CE-specific Interfaces

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) exposes two provider-specific interfaces: ISSCECompact and IRowsetPosition. The following topics describe how to use these interfaces:

  • Using ISSCECompact
  • Using IRowsetPosition

For a complete programming reference for these interfaces, see ISSCECompact and IRowsetPosition.


Using ISSCECompact

The ISSCECompact interface is used to compact databases. Compaction of SQL Server CE databases is essential to maintain good performance, and users should compact SQL Server CE databases regularly.

Note Although a data source can be initialized prior to compacting, initialization is not a requirement, because the initialization of corrupt databases is likely to fail. Also, compacting requires that no sessions exist against the database. For more information, see Maintaining SQL Server CE Databases.

Compacting the database also provides an opportunity to manage global database settings, such as sort orders, the database password, or the use of encryption. You can change the password and encryption properties by specifying the necessary provider-specific properties: DBPROP_SSCE_DBPASSWORD and DBPROP_SSCE_ENCRYPTDATABASE. For more information about using these properties, see Creating Databases.

When the DBPROP_INIT_LCID property is used to change the LCID value and define a new collation at Data Source object initialization, the new sort order is applied when the Compact method is executed. For more information, see ISSCECompact and Initialization Properties.

Examples

The following example shows how to use ISSCECompact::Compact to compact the Northwind database:

// Object declarations
HRESULT          hr              = NOERROR;
DBPROPSET        dbpropset[1];
DBPROP           dbprop[1];

// Declare the provider interfaces.
IDBProperties *  pIDBProperties  = NULL;
ISSCECompact *   pISSCECompact   = NULL;

// Create an instance of the OLE DB Provider.
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBProperties, (void**) &pIDBProperties);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize property structures
VariantInit(&dbprop[0].vValue);

// 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"Northwind.sdf");
if(NULL == dbprop[0].vValue.bstrVal)
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize the property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);

// Set the database properties.
hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Get the ISSCECompact interface.
hr = pIDBProperties->QueryInterface(IID_ISSCECompact, (void **)
    &pISSCECompact);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
 }
// Compact the database using the provider-specific interface.
// The data source does not need to be initialized before compacting.
hr = pISSCECompact->Compact(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}
Exit:

// When finished, clear the properties arrays and release interfaces.
// Uninitialize the environment.

return;


Using IRowsetPosition

The IRowsetPosition interface is an interface that is specific to the OLE DB Provider for SQL Server CE. The GetRecordCount and GetCurrentPosition methods on this interface are used to obtain information about the current position of the cursor in the recordset. For more information, see IRowsetPosition.

Examples

The following example shows using IRowsetPosition::GetRecordCount to count the number of rows in the rowset that is returned when "SELECT * FROM Employees" is executed against the Northwind database:

//Declarations
HRESULT     hr            = NOERROR;
DBPROPSET   dbpropset[1];
DBPROP      dbprop[1];
DBPROPSET   rowsetpropset[1];
DBPROP      rowsetprop[2];
ULONG       cbRecordCount;

// Provider interfaces
IDBProperties *      pIDBProperties    = NULL;
IDBInitialize *      pIDBInitialize    = NULL;
IDBCreateSession *   pIDBCreateSession = NULL;
IRowsetPosition *    pIRowsetPos       = NULL;
ICommandProperties * pICmdProps        = NULL;
IDBCreateCommand *   pIDBCrtCmd        = NULL;
ICommandText *       pICmdText         = NULL;
IRowset *            pIRowset          = NULL;

// Initialize the environment.
hr = CoCreateInstance(CLSID_SQLSERVERCE_2_0, 0, CLSCTX_INPROC_SERVER,
    IID_IDBInitialize, (void**) &pIDBInitialize);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Initialize property structures
VariantInit(&dbprop[0].vValue);

// Initialize the property with the 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"\\Windows\\Northwind.sdf");
if(!(dbprop[0].vValue.bstrVal))
{
    hr = E_OUTOFMEMORY;
    goto Exit;
}

// Initialize the property set.
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties    = dbprop;
dbpropset[0].cProperties     = sizeof(dbprop)/sizeof(dbprop[0]);

// Set the properties into the provider's data source object.
pIDBInitialize->QueryInterface(IID_IDBProperties,(void**)&pIDBProperties);

hr = pIDBProperties->SetProperties(sizeof(dbpropset)/sizeof(dbpropset[0]),
    dbpropset);
if(FAILED(hr))
{
    goto Exit;
}

// Initialize the data source.
hr = pIDBInitialize->Initialize();
if(FAILED(hr))
{
   goto Exit;
}

// Create the Session and Command objects.
hr = pIDBProperties->QueryInterface(IID_IDBCreateSession, (void **)
    &pIDBCreateSession);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pIDBCreateSession->CreateSession(NULL, IID_IDBCreateCommand,
    (IUnknown**) &pIDBCrtCmd);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}
hr = pIDBCrtCmd->CreateCommand(NULL, IID_ICommandText, (IUnknown**)
    &pICmdText);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Request the ability to use the IRowsetPosition interface.
rowsetpropset[0].cProperties     = 1;
rowsetpropset[0].guidPropertySet = DBPROPSET_ROWSET;
rowsetpropset[0].rgProperties    = rowsetprop;

rowsetprop[0].dwPropertyID   = DBPROP_CANFETCHBACKWARDS;
rowsetprop[0].dwOptions      = DBPROPOPTIONS_REQUIRED;
rowsetprop[0].vValue.vt      = VT_BOOL;
rowsetprop[0].vValue.boolVal = VARIANT_TRUE;

// Set the query text for the command.
hr = pICmdText->SetCommandText(DBGUID_SQL, L"Select * from Employees");
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

hr = pICmdText->QueryInterface(IID_ICommandProperties, (void**) &pICmdProps);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}
hr = pICmdProps->SetProperties(1, rowsetpropset);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Creates an IRowsetPosition object for the returned rowset.
hr = pICmdText->Execute(NULL, IID_IRowsetPosition, NULL, NULL,
    (IUnknown**)&pIRowsetPos);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
} // Get a count of the number or rows returned in the rowset.

hr = pIRowsetPos->GetRecordCount(DB_NULL_HCHAPTER, &cbRecordCount);
if (FAILED(hr))
{
    //Send an error-specific message and do error handling.
    goto Exit;
}

// Do something here with the aquired row count information.

Exit:

// When finished, clear the properties arrays, release
// the interfaces and uninitialize the environment.

return;

See Also

Provider-specific Properties


OLE DB for SQL Server CE Programmer's Reference

This reference supplements the Microsoft® OLE DB documentation that ships with the Microsoft Data Access Components (MDAC) SDK and is available in the MSDN® Library at this Microsoft Web site. The purpose of this reference is to fully document any provider-specific interfaces, properties, and data types; as well as highlight any differences between the OLE DB Provider for Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) and the core OLE DB specifications.

The OLE DB Provider for SQL Server CE is an OLE DB version 2.5-compliant provider.

This section includes the following main reference topics:

  • Implemented OLE DB Interfaces
  • SQL Server CE Schema Rowsets
  • SQL Server CE-specific OLE DB Properties

For more information about programming against the OLE DB Provider for SQL Server CE, see Programming OLE DB Applications for SQL Server CE.


Implemented OLE DB Interfaces

The OLE DB Provider for SQL Server CE implements the following OLE DB interfaces that are specific to Microsoft® SQL Server™ 2000 Windows® CE Edition 2.0 (SQL Server CE):

  • ISSCECompact
  • IRowsetPosition
  • ILockBytes

In addition, the OLE DB Provider for SQL Server CE supports the core OLE DB interfaces shown in the following table. For more information about the differences between the OLE DB Provider for SQL Server CE and the generic OLE DB interfaces, see Differences in SQL Server CE-supported OLE DB Interfaces.

Fully implemented | Implemented with differences
IColumnsInfo | IAccessor
ICommand | IAlterIndex
ICommandPrepare | IAlterTable
ICommandProperties | IDBDataSourceAdmin
ICommandText | IOpenRowset
ICommandWithParameters | IRowsetCurrentIndex
IConvertType | ITransactionLocal
IDBCreateCommand |
IDBCreateSession |
IDBInfo |
IDBInitialize |
IDBProperties |
IDBSchemaRowset |
IGetDataSource |
IIndexDefinition |
IRowset |
IRowsetBookmark |
IRowsetChange |
IRowsetIndex |
IRowsetInfo |
IRowsetUpdate |
ISequentialStream |
ISessionProperties |
ISupportErrorInfo |
ITableCreation |
ITableDefinition |
ITableDefinitionWithConstraints |


Differences in SQL Server CE-supported OLE DB Interfaces

Some OLE DB interfaces used with Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) differ from the generic interfaces described in the OLE DB specification. These differences are described in the following table.

Implemented interface | Description of differences
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.
IAlterIndex | Only the name of an index that can be modified using IAlterIndex::AlterIndex.
IAlterTable | SQL Server CE supports changing the seed of and incrementing an autoincrement column, but not changing a column to or from autoincrement. 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 can modify the same things about tables in their data stores. SQL Server CE supports changing the name of an existing table or column as well as the DBPROP_COL_DEFAULT, DBPROP_COL_SEED, and DBPROP_COL_INCREMENT properties.
IDBDataSourceAdmin | This interfaces is used to create a new database. The CreateDataSource and GetCreationProperties methods on this interface are supported. Methods for modifying or deleting databases are not supported.
IOpenRowset | This interface is used to open base tables and integrated indexes. This interface cannot be used to open views.
IRowsetCurrentIndex | 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
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 supports only single-phase commit.

See Also

Implemented OLE DB Interfaces


ISSCECompact

ISSCECompact is used to compact databases in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), perform database repair, and manage compaction-related properties, such as database encryption.

This interface is defined under the DataSource cotype in "Cotypes, Structures, and Enumerated Types" in the Microsoft OLE DB Programmer's Reference.

When to Implement

The OLE DB Provider for SQL Server CE implements ISSCECompact.

Method | Description
Compact | Compacts or repairs a database, creating a new copy.

See Also

ISSCECompact::Compact

Using ISSCECompact


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 0, 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 0, this parameter is ignored.
Return Codes
S_OK
The method succeeded.
E_INVALIDARG
cPropertySets was not equal to 0, and rgPropertySets was a null pointer. In an element of rgPropertySets, cProperties was not 0, 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. For the complete description of this return code, see "IDBProperties::SetProperties" in the Microsoft OLE DB Programmer's Reference in the MSDN® Library at this Microsoft Web site.
E_FAIL
An error occurred during compaction.
Remarks

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. Although a data source can be initialized prior to compacting, initialization is not a requirement as the initialization of a corrupt database is likely to fail. Also, compacting requires that no sessions exist against the database. For more information, see Maintaining SQL Server CE Databases.

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 unencrypted form. This is controlled using the DBPROP_SSCE_ENCRYPTDATABASE (Boolean) property. Note that encrypted databases must have a database password. The database password is specified by DBPROP_SSCE_DBPASSWORD.

See Also

ISSCECompact

Using ISSCECompact


IRowsetPosition

IRowsetPosition is used to return exact row count and position information for the rowset. Because the OLE DB Provider for SQL Server CE does not support IRowsetLocate or IRowsetScroll, this interface is used to expose row count and position information.

Note This interface is supported only on scrollable cursors.

When to Implement

The OLE DB Provider for SQL Server CE implements IRowsetPosition.

Method | Description
GetRecordCount | Used to retrieve the number of rows in the current rowset.
GetCurrentPosition | Gets the number of the current row.

See Also

IRowsetPosition::GetCurrentPosition

IRowsetPosition::GetRecordCount

Using IRowsetPosition


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 value must be allocated by the client.
Return Codes
S_OK
The method succeeded.
E_INVALIDARG
pcRows was NULL.
E_UNEXPECTED
The rowset is in a zombied state.
Remarks

This is an exact count of the number of records in the rowset.

See Also

IRowsetPosition

IRowsetPosition::GetCurrentPosition

Using IRowsetPosition


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 Codes
S_OK
The method succeeded.
E_INVALIDARG
pulPosition was NULL.
E_UNEXPECTED
The rowset is in a zombied state.
Remarks

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.

See Also

IRowsetPosition

IRowsetPosition::GetRecordCount

Using IRowsetPosition


ILockBytes

ILockBytes is a structured storage interface used for accessing long text and long binary data.

Method | Description
ReadAt | Reads a specified number of bytes starting at a specified offset from the beginning of the byte array.
WriteAt | Writes a specified number of bytes to a specified location in the byte array.
Flush | Ensures that any internal buffers maintained by the byte array object are written out to the backing storage. Not supported in SQL Server CE.
SetSize | Changes the size of the byte array.
LockRegion | Restricts access to a specified range of bytes in the byte array. Not supported in SQL Server CE.
UnlockRegion | Removes the access restriction on a range of bytes previously restricted with ILockBytes::LockRegion. Not supported in SQL Server CE.
Stat | Retrieves a STATSTG structure for this byte array object.

See Also

ILockBytes::ReadAt

ILockBytes::SetSize

ILockBytes::Stat

ILockBytes::WriteAt


ILockBytes::ReadAt

ReadAt reads a specified number of bytes starting at a specified offset from the beginning of the byte array.

Syntax
HRESULT ReadAt(
         ULARGE_INTEGER ulOffset,
         void *pv,
         ULONG cb,
         ULONG *pcbRead);
Parameters

ulOffset

[in]
Specifies the starting point from the beginning of the byte array for reading data.

pv

[in]
Pointer to the buffer into which the byte array is read.

cb

[in]
Specifies the number of bytes of data to attempt to read from the byte array.

pcbRead

[out]
Pointer to a location where this method writes the actual number of bytes read from the byte array. You can set this pointer to NULL to indicate that you are not interested in this value. In this case, this method does not provide the actual number of bytes that were read.

Return Codes

NOERROR

The method succeeded.

E_UNEXPECTED

Rowset is in a "zombied" state.

STG_E_INVALIDPOINTER

A pointer that was passed was not valid.

Remarks

TBD

See Also

ILockBytes

ILockBytes::SetSize

ILockBytes::Stat

ILockBytes::WriteAt


ILockBytes::WriteAt

WriteAt writes the specified number of bytes starting at a specified offset from the beginning of the byte array.

Syntax
HRESULT WriteAt(
         ULARGE_INTEGER uliOffset,
         Void const *pData,
         ULONG cbWrite,
         ULONG *pcbWrote);
Parameters

uliOffset

[in]
Specifies the starting point from the beginning of the byte array for the data to be written.

pData

[in]
Pointer to the buffer containing the data to be written.

cbWrite

[in]
Specifies the number of bytes of data to attempt to write into the byte array.

pcbWrote

[out]
Pointer to a location where this method specifies the actual number of bytes written to the byte array. You can set this pointer to NULL to indicate that you are not interested in this value. In this case, this method does not provide the actual number of bytes written.

Return Codes

NOERROR

The method succeeded.

E_UNEXPECTED

Rowset is in a "zombied" state.

Remarks

TBD

See Also

ILockBytes

ILockBytes::ReadAt

ILockBytes::SetSize

ILockBytes::Stat


ILockBytes::SetSize

SetSize changes the size of the byte array.

Syntax
HRESULT SetSize(
         ULARGE_INTEGER uliSize);
Parameters

uliSize

[in]
Specifies the new size of the byte array as a number of bytes.

Return Codes

NOERROR

The method succeeded.

E_UNEXPECTED

Rowset is in a "zombied" state.

Remarks

TBD

See Also

ILockBytes

ILockBytes::ReadAt

ILockBytes::Stat

ILockBytes::WriteAt


ILockBytes::Stat

Retrieves a STATSTG type structure containing information about this byte array object.

Syntax
HRESULT Stat(
         STATSTG *pStat,
         DWORD grfStatFlag);
Parameters

pStat

[out]
Pointer to a STATSTG type structure that contains information about this byte array object.

grfStatFlag

[in]
Specifies whether this method should supply the pwcsName member of the STATSTG structure through values taken from the STATFLAG enumeration. If STATFLAG_NONAME is specified, the pwcsName member of STATSTG is not supplied, thus saving a memory-allocation operation. The other possible value, STATFLAG_DEFAULT, indicates that all members of the STATSTG structure be supplied.

Return Codes

NOERROR

The method succeeded.

E_UNEXPECTED

Rowset is in a "zombied" state.

STG_E_INVALIDFLAG

A flag value that was set for grfStatFlag was not valid.

STG_E_INVALIDPOINTER

A pointer that was passed was not valid.

Remarks

TBD

See Also

ILockBytes

ILockBytes::ReadAt

ILockBytes::SetSize

ILockBytes::WriteAt


SQL Server CE Schema Rowsets

The following schema rowsets are used by the OLE DB Provider for SQL Server CE to expose functionality specific to Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

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.
Provider-specific Schema Rowset Values

The DBSCHEMA_COLUMNS rowset returns the following columns that are specific to SQL Server CE:

  • AUTOINC_MIN
  • AUTOINC_MAX
  • AUTOINC_STEP


SQL Server CE-specific OLE DB Properties

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. The OLE DB Provider for SQL Server CE exposes the following properties:

  • Provider-specific Properties
  • Column Properties
  • Data Source Information Properties
  • Index Properties
  • Initialization Properties
  • Rowset Properties
  • Table Properties


Provider-specific Properties

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) defines a several provider-specific properties in the DBPROPSET_SSCE_DBINIT and DBPROPSET_SSCE_SESSION property sets.

DBPROPSET_SSCE_DBINIT Property Set

The DBPROPSET_SSCE_DBINIT property set contains the following properties that are specific to the OLE DB Provider for SQL Server CE.

Property ID | Description
DBPROP_SSCE_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, and a user password is per user.
DBPROP_SSCE_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.
DBPROP_SSCE_TEMPFILE_DIRECTORY | Type: VT_BSTR Typical R/W: R/W Description: SQL Server CE OLEDB: Temp File Directory Used to specify the temp file directory.
DBPROPSET_SSCE_SESSION Property Set

The DBPROPSET_SSCE_SESSION property set contains the following property that is specific to the OLE DB Provider for SQL Server CE.

Property ID | Description
DBPROP_SSCE_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.
DBPROPSET_SSCE_COLUMN

The DBPROPSET_SSCE_COLUMN property set contains the following properties that are specific to the OLE DB Provider for SQL Server CE.

Property ID | Description
DBPROP_SSCE_COL_ROWGUID | Type: VT_BOOL Typical R/W: R/W Description: SQL Server CE OLE DB: Row GUID Column. Specifies a column as a row GUID column. For this provider, the default value is VARIANT_FALSE.


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 can 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. String literals must be enclosed with single quotation marks, for example: 'default'.
DBPROP_COL_FIXEDLENGTH | Type: VT_BOOL Typical R/W: R/W Description: Fixed Length
DBPROP_COL_INCREMENT | Type: VT_I4 Typical R/W: R/W Only used if autoincrement is VARIANT_TRUE. Can only be used on identity columns.
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 Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) supports all types as nullable.
DBPROP_COL_SEED | Type: VT_I4 Typical R/W: R/W Only used if autoincrement is VARIANT_TRUE. Can only be used on identity columns.


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 OLE DB Provider for SQL Server CE and constitute a set of static information about the provider and data store.

Property ID | Description
DBPROP_ALTERCOLUMN | Type: VT_I4 R/W: R Description: Alter Column Support This provider returns DBCOLUMNDESCFLAGS_DBCID and DBCOLUMNDESCFLAGS_PROPERTIES. 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 be set only on an identity column.
DBPROP_COLUMNDEFINITION | Type: VT_I4 R/W: R Description: Column Definition For this provider, the value is always DBPROPVAL_CD_NOTNULL.
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 "2.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. Because identifiers in SQL Server CE are case-insensitive and are stored in mixed case in the system catalog, the value for this provider must be DBPROPVAL_IC_MIXED.
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_OPENROWSETSUPPORT | Type: VT_I4 R/W: R Description: Open Rowset Support This provider supports the values DBPROPVAL_ORS_TABLE and DBPROPVAL_ORS_INTEGRATEDINDEX.
DBPROP_PERSISTENTIDTYPE | Type: VT_I4 R/W: R Description: Persistent ID Type For this provider, the value is DBPROPVAL_PT_NAME.
DBPROP_PROVIDERFILENAME | Type: VT_BSTR Typical R/W: R only Description: Provider Name Specifies the file name of the provider. (Prior to Microsoft Data Access Components (MDAC) 2.5, this property is named DBPROP_PROVIDERNAME.)
DBPROP_PROVIDEROLEDBVER | Type: VT_BSTR Typical R/W: R only Description: OLE DB Version This provider returns 02.50.00.
DBPROP_PROVIDERVER | Type: VT_BSTR R/W: R Description: Provider Version For this provider, the version returned is 02.00.0000.
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, a combination of zero or more of DBPROPVAL_SS_ISEQUENTIALSTREAM or DBPROPVAL_SS_ILOCKBYTES.
DBPROP_SUPPORTEDTXNDDL | 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 Data Manipulation Language (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 the following values: 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.


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 null values 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.
DBPROP_INDEX_UNIQUE | Type: VT_BOOL Typical R/W: R/W Description: Unique Specifies whether index keys must be unique. The provider supports the following values: VARIANT_TRUE, which indicates that the index keys must be unique, or 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 either DB_MODE_READWRITE or DB_MODE_SHARE_EXCLUSIVE.


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_SSCE_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 aborting a transaction, the only operations allowed on a rowset are to release row and accessor handles and to release the rowset.
DBPROP_ACCESSORDER Type: VT_I4
R/W: R
Description: Access Order
For this provider, the value is always DBPROPVAL_AO_RANDOM.
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. The provider supports the following values:
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 example, 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. Modifying the row's columns does not change the validity of numeric bookmarks.
DBPROP_CANFETCHBACKWARDS Type: VT_BOOL
Typical R/W: R/W
Description: Fetch Backward
Specifies whether the rowset can fetch backward. The providers supports the following values:
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 nonnegative.
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 nonnegative.
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, which indicates that 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) follow 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_LOCKMODE TYPE: VT_I4
R/W: R
Description: Lock Mode
For this provider, the value is always DBPROPVAL_LM_SINGLEROW.
DBPROP_MAXOPENROWS Type: VT_I4
Typical R/W: R
Description: Maximum Open Rows
This value is 1 for Microsoft® SQL Server™ 2000 Windows® CE Edition (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 either of the following values:
VARIANT_TRUE, which indicates that the rowset can see updates and deletes made by a user other than a consumer of the rowset. For example, suppose a user 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_SERVERDATAONINSERT TYPE: VT_BOOL
R/W: R
Description: Server Data on Insert
For this provider, the value is always VARIANT_TRUE.
DBPROP_UPDATABILITY Type: VT_I4
Typical R/W: R/W
Description: Updatability


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 Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

The following table lists the properties that are not supported.

Property ID | Description
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 nonnull-valued character data type columns. The value is DBPROPVAL_CB_NON_NULL, which indicates that the result is the concatenation of the nonnull-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 Engine Object

You can program access to engine-specific features in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) in an application running on a Windows CE-based platform by using either the Microsoft eMbedded Visual Tools or Microsoft Visual Studio® .NET development environments.

To program SQL Server CE engine functionality in the eMbedded Visual Tools environment, use the Engine object within the SQL Server CE ActiveX® control that exposes the CompactDatabase method and the ErrorRecords property.

To program SQL Server CE engine functionality in the Visual Studio .NET environment, use the .NET Compact Framework Data Provider for SQL Server CE, which provides the System.Data.SqlServerCe.SqlCeEngine class. The SqlCeEngine class exposes two methods: Compact and CreateDatabase. For information about the methods and properties of the SqlCeEngine class and other classes in the System.Data.SqlServerCe namespace, see .NET Compact Framework Data Providers.

The following topics describe using these exposed methods:

  • Using the CompactDatabase and Compact Methods
  • Using the CreateDatabase Method

See Also

CompactDatabase Method

ErrorRecords Property


Using the CompactDatabase and Compact Methods

CompactDatabase and Compact are the same methods in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), but are used in different development environments. Use CompactDatabase in applications created with the Microsoft eMbedded Visual Tools, and use Compact in applications created with Microsoft Visual Studio® .NET.

These methods are essential in maintaining and changing databases. They can be used for compacting and reclaiming wasted space. They can also be used to change the collating order, encryption, and/or password in a SQL Server CE database.

Because a new version of the database is created when compacting, the source database path and destination database path must be different. In addition, the source database must be closed and the destination database must not exist. An error occurs if the destination database already exists or another file with that name already exists.

If SQL Server CE is terminated when data is being written (as a result of power failure or a full disk), the data can become corrupted.

Examples

C#

        string src     = "Northwind.sdf";
        string dest    = "Northwind.sdf.tmp";
      // Initialize SqlCeEngine object.
      SqlCeEngine engine = new SqlCeEngine("Data Source = " + src);

      try {
         engine.Compact("Data Source = " + dest);
         engine.Dispose();

          File.Delete(src);
          File.Move(dest, src);
      }
      catch(SqlCeException e)
      {
         //Use your own error handling routine.
         //ShowErrors(e);
      }
      finally
      {
         //Dispose of the SqlCeEngine object.
         engine.Dispose();
      }

Visual Basic .NET

    Dim src  As String = "Northwind.sdf"
    Dim dest As String = "Northwind.sdf.tmp"
    ' Initialize SqlCeEngine Object.
    Dim engine As New SqlCeEngine("Data Source = " + src)

    Try
        engine.Compact(("Data Source = " + dest))
        engine.Dispose()

        File.Delete(src)
        File.Move(dest, src)

    Catch e As SqlCeException
    'Use your own error handling routine.
    'ShowErrors(e)
    Finally
        'Dispose of the SqlCeEngine object.
         engine.Dispose()
    End Try

eMbedded Visual Tools

Dim engine As SSCE.Engine
Set engine = CreateObject("SSCE.Engine.2.0")

Dim src As String
Dim dest As String

src = "Data Source=Northwind.sdf"
dest = "Data Source=Northwind.sdf.tmp"

engine.CompactDatabase src, dest
FileSystem1.FileCopy "Northwind.sdf.tmp", "Northwind.sdf"
FileSystem1.Kill "Northwind.sdf"

See Also

Maintaining SQL Server CE Databases

CompactDatabase Method

ErrorRecords Property


Using the CreateDatabase Method

Use the CreateDatabase method to create a new database in the Microsoft® Visual Studio® .NET development environment.

Examples

C#

if (File.Exists("Test.sdf"))
File.Delete("Test.sdf");

string connStr = "Data Source = Test.sdf; Password = <password>;";

SqlCeEngine engine = new SqlCeEngine(connStr);
engine.CreateDatabase();
engine.Dispose();
SqlCeConnection conn = null;

try
{
   conn = new SqlCeConnection(connStr);
   conn.Open();

   SqlCeCommand cmd = conn.CreateCommand();
   cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)";
   cmd.ExecuteNonQuery();
}

catch {}

finally
{
   conn.Close();
}

Visual Basic .NET

If File.Exists("Test.sdf") Then
   File.Delete("Test.sdf")
End If
Dim connStr As String = "Data Source = Test.sdf; Password = <password>;"

Dim engine As New SqlCeEngine(connStr)
engine.CreateDatabase()
engine.Dispose()

Dim conn As SqlCeConnection = Nothing

Try
   conn = New SqlCeConnection(connStr)
   conn.Open()

   Dim cmd As SqlCeCommand = conn.CreateCommand()

   cmd.CommandText = "CREATE TABLE myTable (col1 int, col2 ntext)"
   cmd.ExecuteNonQuery()

Catch
Finally
   conn.Close()
End Try

See Also

SSCEError Object

CompactDatabase Method

SSCEErrors Collection


SQL Server CE Engine Object Programmer's Reference for eMbedded Visual Tools

This section provides reference information about the CompactDatabase method and ErrorRecords property of the Microsoft® SQL Server™ 2000 Windows® Edition (SQL Server CE) Engine object for the Microsoft eMbedded Visual Tools development environment.

  • CompactDatabase Method
  • ErrorRecords Property


CompactDatabase Method

The CompactDatabase method compacts and reclaims wasted space. This method can also be used to change the collating order, encryption, and/or password of a database in Microsoft® SQL Server™ 2000 Windows® Edition (SQL Server CE).

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 occurs 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 occurs 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 | Description
Provider | Indicates the name of the provider to use to connect to the data source. If this property is not specified, the OLE DB Provider for SQL Server CE 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 | Indicates the name of the database. This property is required for both the source and destination connection information.
Locale Identifier | Indicates the locale ID (LCID) 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.
SSCE:Database Password | 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 you want to remove the password from the destination database, the database password must be set to an empty string. The database password can be up to 40 characters.
SSCE:Encrypt Database | 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 wanted.
SSCE:Temp File Directory | Specifies the location of the temporary database. If this parameter is omitted, the temporary database is stored in the temp directory of the device.

Locale identifier values are supported. Use the unique LCID for the value of Locale Identifier. To find a list of unique LCID values, see Collate. You must ensure that the locale is supported on the device on which the database is being created.

See Also

ErrorRecords Property


ErrorRecords Property

The ErrorRecords property contains the SSCEErrors collection for the Microsoft® SQL Server™ 2000 Windows® Edition (SQL Server CE) Engine object.

Syntax
object.ErrorRecords
Part | Description
object | SQL Server CE Engine object
Remarks

The SSCEErrors 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


Remote Data Access (RDA)

The Remote Data Access (RDA) object is a Microsoft® SQL Server™ 2000 Windows® CE (SQL Server CE) ActiveX® control that enables programmatic access to a Microsoft SQL Server 2000 or Microsoft SQL Server version 7.0 database. This access is provided by a Microsoft Visual Studio® .NET or Microsoft eMbedded Visual Tools application running on a Windows CE-based device.

To program RDA in the Visual Studio .NET development environment, use the .NET Compact Framework Data Provider for SQL Server CE, which provides the System.Data.SqlServerCe.SqlCeRemoteDataAccess class. For more information about the methods and properties of the SqlCeRemoteDataAccess class and the other classes in the System.Data.SqlServerCe namespace, see .NET Compact Framework Data Provider for SQL Server CE.

To program RDA in the eMbedded Visual Tools development environment, use the RDA object. The following topics describe the concepts for building Windows CE-based applications using the SQL Server CE RDA object with the .NET Compact Framework data provider and eMbedded Visual Tools.

  • Using the Pull Method
  • Using the Push Method
  • Using the SubmitSQL Method
  • Handling RDA Errors

This section also contains a programmer's reference that describes the methods and properties of the RDA object for the Microsoft eMbedded Visual Tools environment. For more information, see RDA Programmer's Reference for eMbedded Visual Tools.

Guidelines for Developing RDA Applications

When designing Windows CE-based applications that use RDA to access SQL Server databases, use the following guidelines:

  • The application always initiates and controls RDA. The application is responsible for pulling a table from a SQL Server table:
    • If the table is tracked, the application is responsible for 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.
    • The application also is responsible for deleting the table from the SQL Server CE database when it is no longer needed.
  • Users should be shielded from the details of RDA.

    If the table pulled from SQL Server was marked as tracked, the application should use the RDA object to initiate table-level synchronization whenever synchronization is required. For example, the application might trigger synchronization when it detects that the Windows CE-based 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.


Using the Pull Method

An application calls the Pull method to extract data from a Microsoft® SQL Server™ database and store the data in a table in a Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) database. For more information, see Pull Method.

An application can track the changes made on a SQL Server CE table by setting the appropriate tracking options. SQL Server CE tracks all inserts, updates, and deletes. Applications can then call the Push method to propagate the changes back to the original SQL Server table.

Remote data access (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 might 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 logically partitioned and conflicts are unlikely. For example, tracked Pull and Push methods might be used in a field service application which tracks each technician who has a unique list of service calls.

The following examples show how an application calls the Pull method. These examples assume that the SQL Server CE Server Agent is configured with the Microsoft Internet Information Services (IIS) virtual directory name sqlce, and that it is configured to require HTTP Basic authentication. The examples also assume that the SQL Server database is located on the SampleServer server. The LocalConnectionString property specifies the name of the SQL Server CE database that receives the pulled table. By convention, SQL Server CE databases are assigned the file extension .sdf.

Examples

C#

        // Connection string to the instance of SQL Server
        string rdaOleDbConnectString  = "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " +
                                        "User Id=username;Password=<password>";

        // Initialize the RDA object.
        SqlCeRemoteDataAccess rda = null;

        try {
            //Try the Pull operation.
            rda = new SqlCeRemoteDataAccess();

            rda.InternetLogin          = "MyLogin";
            rda.InternetPassword       = "<password>";
            rda.InternetUrl            = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            rda.LocalConnectionString  = @"Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf";

            rda.Pull(
                "Employees",
                "Select * from Employees",
                rdaOleDbConnectString,
                RdaTrackOption.TrackingOnWithIndexes,
                "ErrorTable");
        }
        catch(SqlCeException e) {
            //Use your own error handling routine.
            //ShowErrors(e)
        }
        finally {
            //Dispose of the RDA object.
            rda.Dispose();
        }

Visual Basic .NET

      ' Connection string to the instance of SQL Server
      Dim rdaOleDbConnectString As String = _
          "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " + _
          "User Id=username;Password=<password>"

      ' Initialize the RDA object.
      Dim rda As SqlCeRemoteDataAccess = Nothing

      Try
          'Try the Pull operation.
          rda = New SqlCeRemoteDataAccess()

          rda.InternetLogin         = "MyLogin"
          rda.InternetPassword      = "<password>"
          rda.InternetUrl           = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
          rda.LocalConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"

          rda.Pull("Employees", "Select * from Employees", _
             rdaOleDbConnectString, _
             RdaTrackOption.TrackingOnWithIndexes, _
             "ErrorTable")

      Catch e As SqlCeException
      'Use your own error handling routine.
      'ShowErrors(e)
      Finally
         'Dispose of the RDA object.
         rda.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the SQL Server CE ActiveX control RDA object control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA object.
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.2.0")

   ' Set RDA properties.
   ceRDA .InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "<password>"
   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=<password>", TRACKINGON_INDEXES, "tblErrCustomers"

   Set ceRDA = Nothing

See Also

Using the Push Method

Using the SubmitSQL Method


Using the Push Method

An application calls the Push method to transmit changes from a pulled tracked table in Microsoft® SQL Server™ 2000 Window CE Edition (SQL Server CE) back to a SQL Server table. For more information, see Push Method.

The application must have created the local SQL Server CE table by calling the Pull method with the tracking option set on.

Remote data access (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 might cause changes made by other users of the SQL Server database to be lost.

The following examples show how an application calls the Push method. These examples assume that the SQL Server CE Server Agent is configured with the Microsoft Internet Information Services (IIS) virtual directory name sqlce, and that it is configured to require HTTP Basic authentication.

Examples

C#

        // Connection string to the instance of SQL Server
        string rdaOleDbConnectString = "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " +
            "User Id=username;Password=<password>";

        // Initialize the RDA object.
        SqlCeRemoteDataAccess rda = null;

        try {
            //Try the Pull operation.
            rda = new SqlCeRemoteDataAccess();

            rda.InternetLogin          = "MyLogin";
            rda.InternetPassword       = "<password>";
            rda.InternetUrl            = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            rda.LocalConnectionString = @"Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf";

            rda.Push("MyLocalTable",
                rdaOleDbConnectString,
                RdaBatchOption.BatchingOn);
        }
        catch(SqlCeException e) {
            //Use you own Error Handling Routine.
            //ShowErrors(e)
        }
        finally {
            //Dispose of the RDA object.
            rda.Dispose();
        }

Visual Basic .NET

      ' Connection string to the instance of SQL Server
      Dim rdaOleDbConnectString As String = _
          "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " + "User Id=username;Password=<password>"

      ' Initialize the RDA object.
      Dim rda As SqlCeRemoteDataAccess = Nothing

      Try
         'Try the Pull operation.
         rda = New SqlCeRemoteDataAccess()

         rda.InternetLogin         = "MyLogin"
         rda.InternetPassword      = "<password>"
         rda.InternetUrl           = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
         rda.LocalConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"

         rda.Push("MyLocalTable", rdaOleDbConnectString, RdaBatchOption.BatchingOn)

      Catch e As SqlCeException
      'Use you own Error Handling Routine.
      'ShowErrors(e)
      Finally
         'Dispose of the RDA object.
         rda.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the SQL Server CE ActiveX control RDA object control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA object.
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.2.0")

   ' Set the RDA properties.
   ceRDA .InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "<password>"
   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=<password>; BATCHINGON"

   Set ceRDA = Nothing

See Also

RDA Conflict Detection and Resolution

Using the Pull Method

Using the SubmitSQL Method


Using the SubmitSQL Method

An application calls the SubmitSQL method to submit SQL statements for execution on a database on a remote instance of Microsoft® SQL Server™. For more information, see SubmitSQL Method.

The following examples show how an application calls the SubmitSQL. These examples assume that the SQL Server CE Server Agent is configured with the Microsoft Internet Information Services (IIS) virtual directory name sqlce, and that it is configured to require HTTP Basic authentication.

Examples

C#

        // Connection string to the instance of SQL Server
        string rdaOleDbConnectString = "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " +
            "User Id=username;Password=<password>";

        // Initialize the RDA object.
        SqlCeRemoteDataAccess rda = null;

        try {
            //Try the Pull operation.
            rda = new SqlCeRemoteDataAccess();

            rda.InternetLogin          = "MyLogin";
            rda.InternetPassword       = "<password>";
            rda.InternetUrl            = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            rda.LocalConnectionString = @"Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf";

            rda.SubmitSql("MyLocalTable", rdaOleDbConnectString);
        }
        catch(SqlCeException e) {
            //Use your own error handling routine.
            //ShowErrors(e)
        }
        finally {
            //Dispose of the RDA object.
            rda.Dispose();
        }

Visual Basic .NET

      ' Connection string to the instance of SQL Server
      Dim rdaOleDbConnectString As String = _
          "Provider=sqloledb; Data Source=MySqlServer;Initial Catalog=Northwind; " + "User Id=username;Password=<password>"

      ' Initialize the RDA object.
      Dim rda As SqlCeRemoteDataAccess = Nothing

      Try
         'Try the Pull operation.
         rda = New SqlCeRemoteDataAccess()

         rda.InternetLogin         = "MyLogin"
         rda.InternetPassword      = "<password>"
         rda.InternetUrl           = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
         rda.LocalConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"

         rda.SubmitSql("MyLocalTable", rdaOleDbConnectString)

      Catch e As SqlCeException
      'Use you own Error Handling Routine.
      'ShowErrors(e)
      Finally
         'Dispose of the RDA object.
         rda.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the SQL Server CE ActiveX control RDA object control.
   Dim ceRDA As SSCE.RemoteDataAccess

   ' Create the RDA object.
   Set ceRDA = CreateObject("SSCE.RemoteDataAccess.2.0")

   ' Set the RDA properties.
   ceRDA .InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
   ceRDA .InternetLogin = "MyInternetLogin"
   ceRDA .InternetPassword = "<password>"

   ' Update the Employees table in the Northwind database on the instance of SQL Server.
   ceRDA .SubmitSQL "UPDATE Employees SET City='Redmond' WHERE LastName='Davolio'", "Provider=sqloledb;Data Source=SampleServer;Initial Catalog=Northwind;user id=SampleUser;password=<password>"

   Set ceRDA = Nothing

See Also

Using the Pull Method

Using the Push Method


Handling RDA Errors

The type of Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) application that you develop determines the way in which remote data access (RDA) errors are handled:

  • Handling Errors in eMbedded Visual Tools Applications

    In Microsoft eMbedded Visual Basic® and eMbedded Visual C++® applications, RDA errors are handled by using the SQL Server CE error control objects and collections.

  • Handling Errors in Smart Device Applications

    In C# and Visual Basic .NET, RDA errors are handled by using the Microsoft .NET Framework data providers error control objects and collections.

See Also

SQL Server CE Error Control Objects and Collections

Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections


RDA Programmer's Reference for eMbedded Visual Tools

The topics in this section describe the methods and properties of the Remote Data Access (RDA) object for the Microsoft® eMbedded Visual Tools environment. Applications use the RDA object to access a database on a remote instance of Microsoft SQL Server™. For more information about eMbedded Visual Tools, see Development Tools.

  • RDA Object Methods
  • RDA Object Properties


RDA Object Methods

The following table lists and describes the methods that the RDA object supports for the Microsoft® eMbedded Visual Tools environment. For more information about eMbedded Visual Tools, see Development Tools.

Method | Description
Pull Method | Extracts data from a Microsoft SQL Server™ database and stores that data in a table in a Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE) database.
Push Method | Sends changes from a locally tracked SQL Server CE table back to an existing SQL Server table.
SubmitSQL Method | Submits SQL statements for execution on a remote SQL Server database.


Pull Method

Applications call the Pull method to extract data from a Microsoft® SQL Server™ database and stores that data in a table in a Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) database.

Applies To

SQL Server CE RDA object

Syntax
object.Pull (LocalTableName, SQLSelectString, OLEDBConnectionString, RDA_TRACKOPTION, ErrorTableName)
Part | Description
object | SQL Server CE RDA object
LocalTableName | Name of the SQL Server CE table that receives the extracted SQL Server records. An error occurs if the table already exists.
SQLSelectString | 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 SQL statement that returns rows, including SELECT statements or stored procedures.
OLEDBConnectionString | OLE DB connection string used when connecting to the SQL Server database.
RDA_TRACKOPTION | Indicates whether SQL Server CE should track changes made to the pulled table. When indexes are requested, indexes that exist on the table being pulled are brought down to the device with the PRIMARY KEY constraints.
ErrorTableName | Name of the local error table that is created if an error occurs when the Push method is later called to send changes back to SQL Server. This option can be specified only when RDA_TRACKOPTION is TRACKINGON.

The RDA_TRACKOPTION enum specifies whether 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. PRIMARY KEY constraints related to the specified SQLSelectString are created on the local table. (Default)
TRACKINGOFF | 0 | SQL Server CE does not track changes to the pulled table. No PPRIMARY KEY constraints are created locally.
TRACKINGON_INDEXES | 2 | SQL Server CE tracks all changes to the pulled table. Indexes and PRIMARY KEY constraints that existed on the SQL Server table specified in SQLSelectString are created on the local table.
TRACKINGOFF_INDEXES | 3 | SQL Server does not track changes to the pulled table. Indexes and PRIMARY KEY constraints that existed on the SQL Server table specified in SQLSelectString are created on the local table.
Remarks

The InternetURL property must contain the URL of the SQL Server CE Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE-based device.

The InternetLogin and InternetPassword properties must be specified if the SQL Server CE Server Agent is configured to use Basic authentication.

SQLSelectString controls which data is pulled from the SQL Server table. An error occurs 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' retrieves customers who live in California only. SQLSelectString also supports stored procedures and views that return rows. SQLSelectString can also pull selected columns from multiple tables into a single table using TRACKINGOFF. For more information about data access and limitation, see Supported Data Types and Data Type Mappings and RDA Limitations.

RDA_TRACKOPTION specifies whether SQL Server CE should track changes to the pulled table. Specify TRACKINGON or TRACKINGON_INDEXES if you want to update the pulled table on the Windows CE-based device and then push changed records back to the original SQL Server table. When TRACKINGON is specified, PRIMARY KEY constraints are created on the pulled table. When TRACKINGON_INDEXES is specified, PRIMARY KEY constraints and related indexes are created on the pulled table. In both cases, SQL Server CE keeps track of every record that is inserted, updated, or deleted in the local table.

Note An index is created only if the column(s) that makes up the index is pulled.

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 or TRACKINGON_INDEXES:

  • An error occurs if the SELECT statement returns a nonupdatable recordset.
  • A primary key must be defined on the updatable recordset returned by the SELECT statement.
  • The SELECT statement can reference a view or stored procedure, but the view or stored procedure must reference only one table and must be updatable.
  • When TRACKINGON_INDEXES is specified, indexes that exist on the SQL Server table and are relevant to the columns specified in SQLSelectString are created against the SQL Server CE local table specified in LocalTableName.

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 creates the error table and inserts 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 be specified only when TRACKINGON or TRACKINGON_INDEXES is specified. For more information about how the error table works, see RDA Conflict Detection and Resolution.

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 Windows authentication is used by setting INTEGRATED SECURITY="SSPI" in OLEDBConnectionString, the Internet user must have the authority to read the SQL Server table.

  • When Microsoft Internet Information Services (IIS) is configured to use Anonymous access, 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 Integrated Windows authentication, the Internet user runs under the client's identity.

See Also

Configuring Security for Connectivity

OLE DB and SQL Server CE

RDA Object Methods


Push Method

Applications call the Push method to transmit changes from a pulled tracked table in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) back to the originating table in Microsoft SQL Server. These changes can either be individually applied to the server or batched together in a single transaction.

Applies To

SQL Server CE RDA object

Syntax
object.Push (LocalTableName, OLEDBConnectionString, RDA_BATCHOPTION)
Part | Description
object | SQL Server CE RDA object
LocalTableName | Name of the pulled tracked SQL Server CE table containing updated records to be sent back to the SQL Server table.
OLEDBConnectionString | OLE DB connection string for the SQL Server database.
RDA_BATCHOPTION | Specifies whether the rows being sent back to the SQL Server table should be batched together in a single transaction or individually applied.

The RDA_BATCHOPTION enum specifies whether the rows associated with the Push should be batched together in a single transaction.

Constant | Value | Description
BATCHINGOFF | 0 | SQL Server CE does not batch rows pushed to SQL Server. The server processes each row. (Default)
BATCHINGON | 1 | SQL Server CE batches the rows pushed to SQL Server into a single transaction.
Remarks

The InternetURL property must contain the URL of the SQL Server CE Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE-based device.

The InternetLogin and InternetPassword properties must be specified if the SQL Server CE Server Agent is configured to use 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 are logged in the error table. For more information about how the error table works, see RDA Conflict Detection and Resolution.

RDA_BATCHOPTION specifies whether SQL Server CE should batch the changes being sent to the SQL Server table. The default setting is BATCHINGOFF, where changes (insert, update, and delete) are applied to the SQL Server table as individual transactions. Each transaction is not dependent on the other to succeed. BATCHINGON specifies that all changes be sent as a single transaction. In this case, all changes must succeed ifor the transaction to be successful. If one change fails, the entire transaction fails, and no changes are applied to the SQL Server table.

Both BATCHINGON and BATCHINGOFF return all errors to the error table, not just the first error that occurs. For example, if BATCHINGON is specified and three out of five changes fail, no changes are applied and all three failures are stored in the error table. If BATCHINGOFF is specified, the same three failures are stored in the error table and the other two changes are applied to the SQL Server table. For more information about handling batch errors, see RDA Conflict Detection and Resolution.

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 Windows authentication is used by setting INTEGRATED SECURITY="SSPI" in OLEDBConnectionString, the Internet user must have the authority to read and update the SQL Server table.

  • When Microsoft Internet Information Services (IIS) is configured to use Anonymous access, 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 Integrated Windows authentication, the Internet user runs under the client's identity.

See Also

Configuring Security for Connectivity

OLE DB and SQL Server CE

RDA Object Methods


SubmitSQL Method

Applications call the SubmitSQL method to submit SQL statements for execution on a database on a remote instance of Microsoft® SQL Server™.

Applies To

SQL Server CE RDA object

Syntax
object.SubmitSQL (SQLString, OLEDBConnectionString)
Part | Description
object | SQL Server CE RDA object
SQLString | Any SQL statement that does not return rows
OLEDBConnectionString | OLE DB connection string for the remote SQL Server database
Remarks

The InternetURL property must contain the URL of the SQL Server CE Server Agent.

The LocalConnectionString property must contain the OLE DB connection string for the SQL Server CE database on the Windows CE-based device.

The InternetLogin and InternetPassword properties must be specified if the SQL Server CE 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 Windows authentication is used by setting INTEGRATED SECURITY="SSPI" in OLEDBConnectionString, the Internet user must have the authority to execute the SQL statement.

  • When Microsoft Internet Information Services (IIS) is configured to use Anonymous access, 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 Integrated Windows authentication, the Internet user runs under the client's identity.

See Also

Configuring Security for Connectivity

OLE DB and SQL Server CE

RDA Object Methods


RDA Object Properties

The following table lists the properties that the Remote Data Access (RDA) object supports, and the methods to which they apply, for the Microsoft® eMbedded Visual Tools development environment.

Property | Pull | Push | SubmitSQL
ErrorRecords Property | Read-only | Read-only | Read-only
InternetURL Property | Required | Required | Required
InternetLogin Property | Optional | Optional | Optional
InternetPassword Property | Optional | Optional | Optional
InternetProxyServer Property | Optional | Optional | Optional
InternetProxyLogin Property | Optional | Optional | Optional
InternetProxyPassword Property | Optional | Optional | Optional
LocalConnectionString Property | Required | Required | N/A


ErrorRecords Property (RDA)

The ErrorRecords property contains the SSCEErrors collection for the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) RDA object.

Applies To

SQL Server CE RDA object

Syntax
object.ErrorRecords [= value]
Part | Description
object | SQL Server CE RDA object
value | Error records string
Remarks

The SSCEErrors 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 (RDA)

The InternetURL property specifies the URL used to connect to the SQL Server CE Server Agent. The SQL Server CE Server Agent connects the Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) client to the Microsoft SQL Server database. This property must be specified.

Applies To

SQL Server CE RDA object

Syntax
object.InternetURL [= value]
Part | Description
object | SQL Server CE RDA object
value | URL string, including the location of the SQL Server CE Server Agent (Sscesa20.dll), for example: http://www.northwindtraders.com/sqlce/sscesa20.dll.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetURL(BSTR *pVal);
HRESULT put_ InternetURL (BSTR newVal);

See Also

Configuring Security for Connectivity

RDA Object Properties


InternetLogin Property (RDA)

The InternetLogin property specifies the Microsoft® Internet Information Services (IIS) login name that is used when connecting to the SQL Server CE Server Agent.

Applies To

SQL Server CE RDA object

Syntax
object.InternetLogin [= value]
Part | Description
object | SQL Server CE RDA object
value | IIS login name. The default is no login.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetLogin(BSTR *pVal);
HRESULT put_ InternetLogin (BSTR newVal);
Remarks

InternetLogin is required if the SQL Server CE Server Agent is configured to use Basic authentication or Integrated Windows authentication. When Integrated Windows authentication is used, InternetLogin is not passed across the network.

See Also

Configuring Security for Connectivity

RDA Object Properties


InternetPassword Property (RDA)

The InternetPassword property specifies the Microsoft® Internet Information Services (IIS) password that is used when connecting to the SQL Server CE Server Agent.

Applies To

SQL Server CE RDA object

Syntax
object.InternetPassword [= value]
Part | Description
object | SQL Server CE RDA object
value | IIS password string. The default is no password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetPassword(BSTR *pVal);
HRESULT put_InternetPassword(BSTR newVal);
Remarks

InternetPassword is required if the SQL Server CE Server Agent is configured to use Basic authentication or Integrated Windows authentication. When Integrated Windows authentication is used, InternetPassword is not passed across the network.

When using Basic authentication, you should configure IIS to use Secure Sockets Layer (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, it is strongly recommend that you always use SSL or PCT encryption to safeguard passwords when you use Basic authentication.

See Also

Configuring Security for Connectivity

RDA Object Properties


InternetProxyServer Property (RDA)

The InternetProxyServer property specifies the proxy server to use when you access the HTTP resource specified in the InternetURL property.

Applies To

SQL Server CE RDA object

Syntax
object.InternetProxyServer [= value]
Part | Description
object | SQL Server CE RDA object
value | Proxy name (or IP address) and port number (ProxyServerName:Port)
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyServer(BSTR *pVal);
HRESULT put_ InternetProxyServer (BSTR newVal);
Remarks

If SQL Server CE Relay is properly configured on a desktop computer for serial, USB, or IR synchronization, InternetProxyServer must be set to ppp_peer:nn where nn is a specified client port number, for example: exampleproxy:80.

If InternetProxyServer is not set or is empty, no proxy server is used.

See Also

Using SQL Server CE Relay

RDA Object Properties


InternetProxyLogin Property (RDA)

The InternetProxyLogin property specifies the login name used when you connect 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 | SQL Server CE RDA object
value | Proxy server login name. The default is no login.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyLogin(BSTR *pVal);
HRESULT put_ InternetProxyLogin (BSTR newVal);
Remarks

InternetProxyLogin 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.

See Also

InternetProxyServer Property (RDA)

Configuring Security for Connectivity

RDA Object Properties


InternetProxyPassword Property (RDA)

The InternetProxyPassword property specifies the password used when you connect 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 | SQL Server CE RDA object
value | Proxy server password string. The default is no password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyPassword(BSTR *pVal);
HRESULT put_InternetProxyPassword(BSTR newVal);
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.

See Also

InternetProxyServer Property (RDA)

Configuring Security for Connectivity

Using SQL Server CE Relay

RDA Object Properties


LocalConnectionString Property (RDA)

The LocalConnectionString property specifies the OLE DB connection string for the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database on the Microsoft Windows CE-based device.

Applies To

SQL Server CE RDA object

Syntax
object.LocalConnectionString [= value]
Part | Description
object | SQL Server CE RDA object
value | OLE DB connection string for the SQL Server CE database

The following connection properties are supported. All other connection properties are ignored.

Property | Required/ optional | Description
Provider | Optional | Indicates the name of the data source provider. If the provider is not specified, Microsoft.sqlserver.oledb.ce.2.0 is assumed.
Data source | Required | Indicates the name of the database. By convention, specify the .sdf file extension for the SQL Server CE databases.
SSCE:Database Password | Optional | Indicates the database password. This property must be specified if the database was created with a password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_LocalConnectionString(BSTR *pVal);
HRESULT put_LocalConnectionString(BSTR newVal);
Examples

object.LocalConnectionString = "Data Source=\NorthwindRDA.sdf; SSCE:Database Password=mypassword"

See Also

OLE DB and SQL Server CE

RDA Object Properties


Replication

You can programmatically access the replication features of Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) through a Microsoft Visual Studio® .NET or Microsoft eMbedded Visual Tools application running on a Microsoft Windows CE-based device. Replication features that allow you to create, synchronize and manage replicated SQL Server data are supported between SQL Server CE and SQL Server 2000 Service Pack 1 or higher.

To program SQL Server CE replication functionality in a Visual Studio .NET development environment, use the .NET Compact Framework Data Provider for SQL Server CE, which provides the System.Data.SqlServerCe.SqlCeReplication class. For information about the methods and properties of the SqlCeReplication class and other classes in the System.Data.SqlServerCe namespace, see .NET Compact Framework Data Providers.

To program replication in the eMbedded Visual Tools development environment, use the SQL Server CE ActiveX® Control Replication object. The following topics in this section describe the concepts for building Windows CE-based applications by using the SQL Server CE Replication object with eMbedded Visual Tools and the SqlCeReplication class with the .NET Compact Framework Data Provider for SQL Server CE:

  • Creating a Subscription.
  • Synchronizing a Subscription
  • Reinitializing a Subscription
  • Dropping a Subscription

This section also contains a programmer's reference that describes the methods and properties of the Replication object for the Microsoft eMbedded Visual Tools environment. For more information, see Replication Programmer's Reference for eMbedded Visual Tools.

Automating Management of Replication Processes

Users should be shielded from the details of replication by automatically subscribing to and downloading any publications the application needs. An application should use the Replication object to initiate database synchronization whenever synchronization is required. For example, an application might trigger synchronization when it detects that the Windows CE-based 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-based device, it should delete any Subscriber databases that it no longer needs from the device.

For more information, see "Programming the SQL Merge ActiveX Control" and "Replication ActiveX Control Interface Reference" in SQL Server Books Online.


Creating a Subscription

Before you can create a subscription, you must configure Microsoft® SQL Server™ replication, create the SQL Server publication, and enable the publication for anonymous subscriptions. For information about this process, see Implementing Replication.

After the publication is enabled for anonymous subscriptions and Microsoft Internet Information Services (IIS) is properly configured, you can create a Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) subscription by using either of these ways:

  • Calling the AddSubscription method
  • Copying an existing subscription
Calling the AddSubscription Method

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 Microsoft Windows CE-based device. The application does this by creating the Replication object, setting the appropriate Replication object properties, and calling the appropriate methods. The following examples show how this is done.

Copying an Existing Subscription

You can create a new subscription by copying an existing subscription from one Windows CE-based device to another. This makes it easy to deploy a Windows CE-based application on many devices when all of the Subscribers are using the same publication. You can create the initial subscription on one Windows CE-based device and then deploy the application by copying the application and the initial subscription to as many devices as you want. When the 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. An efficient way to deploy large SQL Server CE databases is to distribute them on these storage devices.

Note These storage devices have relatively long access times when compared to RAM. Using these devices may affect the performance of your application.

The following examples show how an application subscribes to an existing SQL Server publication that has been enabled for anonymous subscriptions. The examples assume that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name of sqlce and that it is configured to require HTTP Basic authentication. The examples also assume 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.

Examples

C#

        SqlCeReplication repl = null;

        try {
            // Set the Replication object.
            repl = new SqlCeReplication();
            repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            repl.InternetLogin     = "MyLogin";
            repl.InternetPassword  = "<MyPassword>";
            repl.Publisher         = "MyPublisher";
            repl.PublisherDatabase = "MyPublisher Database";
            repl.PublisherLogin    = "MyPublisher Login";
            repl.PublisherPassword = "<MyPublisher Password>";
            repl.Publication       = "MyPublication";
            repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\\ssce.sdf";
            repl.Subscriber        = "MySubscriber";

            // Create the Local SSCE Database subscription.
            repl.AddSubscription(AddOption.CreateDatabase);

            // Synchronize to the instance of SQL Server 2000 to populate the Subscription.
            repl.Synchronize();
        }

        catch(SqlCeException e) {
            // Use your own error handling routine to show error information.
            // ShowError.ShowErrors(e);
        }

        finally {
            // Dispose of the Replication object.
            repl.Dispose();
        }

Visual Basic .NET

      Dim repl As SqlCeReplication = Nothing

      Try
         ' Set the Replication object.
         repl = New SqlCeReplication()
         repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
         repl.InternetLogin     = "MyLogin"
         repl.InternetPassword  = "<MyPassword>"
         repl.Publisher         = "MyPublisher"
         repl.PublisherDatabase = "MyPublisher Database"
         repl.PublisherLogin    = "MyPublisher Login"
         repl.PublisherPassword = "<MyPublisher Password>"
         repl.Publication       = "MyPublication"
         repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"
         repl.Subscriber        = "MySubscriber"

         ' Create the Local SSCE Database subscription.
         repl.AddSubscription(AddOption.CreateDatabase)

         ' Synchronize to the instance of SQL Server 2000 to populate the Subscription.
         repl.Synchronize()

      Catch e As SqlCeException
      ' Use your own error handling routine to show error information.
      ' ShowErrors(e)

      Finally
         ' Dispose of the Replication object.
         repl.Dispose()
      End Try

eMbedded Visual Basic

' Declare the Replication object.
   Dim ce As SSCE.Replication

' Create the Replication object.
  Set ce = CreateObject("SSCE.Replication.2.0")

' Set Internet properties.
  ce.InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.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=\ssce.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, and 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

eMbedded Visual C++

   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.northwindtraders.com/sqlce/sscesa20.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=\\ssce.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

Replication Object Methods

SubscriberConnectionString Property


Synchronizing a Subscription

An application uses the Replication object to synchronize an existing Microsoft® SQL Server™ subscription. In Microsoft Visual Studio® .NET, the application must call the Synchronize and Dispose methods on a single instance of the Replication object. In Microsoft eMbedded Visual Tools, the application must call the Initialize, Run, and Terminate methods in succession on a single instance of the Replication object.

Note 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 following examples show how an application initiates synchronization. The examples assume that the SQL Server CE Server Agent is configured with the Microsoft Internet Information Services (IIS) Web virtual directory name of sqlce and that it is configured to require HTTP Basic authentication. The examples also assume that the SQL Server Publisher uses SQL Server authentication and the SQL Server Distributor is located on the same server as the Publisher.

Examples

C#

        SqlCeReplication repl = null;

        try {
            // Set the Replication object.
            repl = new SqlCeReplication();
            repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            repl.InternetLogin     = "MyLogin";
            repl.InternetPassword  = "<MyPassword>";
            repl.Publisher         = "MyPublisher";
            repl.PublisherDatabase = "MyPublisher Database";
            repl.PublisherLogin    = "MyPublisher Login";
            repl.PublisherPassword = "<MyPublisher Pwd>";
            repl.Publication       = "MyPublication";
            repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\\ssce.sdf";
            repl.Subscriber        = "MySubscriber";

            // Synchronize to the instance of SQL Server 2000 to populate the Subscription.
            repl.Synchronize();
        }
        catch(SqlCeException e) {
            // Use your own error handling routine to show error information.
            // ShowError.ShowErrors(e);
        }

        finally {
            // Dispose of the Replication object.
            repl.Dispose();
        }

Visual Basic .NET

      Dim repl As SqlCeReplication = Nothing

      Try
         ' Set the Replication object.
         repl = New SqlCeReplication()
         repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
         repl.InternetLogin     = "MyLogin"
         repl.InternetPassword  = "<MyPassword>"
         repl.Publisher         = "MyPublisher"
         repl.PublisherDatabase = "MyPublisher Database"
         repl.PublisherLogin    = "MyPublisher Login"
         repl.PublisherPassword = "<MyPublisher Pwd>"
         repl.Publication       = "MyPublication"
         repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"
         repl.Subscriber        = "MySubscriber"

         ' Synchronize to the instance of SQL Server 2000 to populate the Subscription.
         repl.Synchronize()

      Catch e As SqlCeException
      ' Use your own error handling routine to show error information.
      ' ShowErrors(e)

      Finally
         ' Dispose of the Replication object.
         repl.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the Replication object.
   Dim ce As SSCE.Replication

   ' Create the Replication object.
  Set ce = CreateObject("SSCE.Replication.2.0")

  ' Set Internet properties.
  ce.InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.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=\Ssce.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

eMbedded Visual C++

   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.northwindtraders.com/sqlce/sscesa20.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=\\Ssce.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();
      }

See Also

Initialize Method

Run Method

Terminate Method


Reinitializing a Subscription

An application uses the Replication object to reinitialize an existing Microsoft® SQL Server™ subscription so that a new snapshot is 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.

In Microsoft eMbedded Visual Tools, 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 after 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 Microsoft Windows® CE-based device. In Microsoft Visual Studio® .NET the process is the same, except the Synchronize and Dispose methods are used in place of Initialize, Run and Terminate.

The following examples show how an application reinitializes a subscription. The examples assume that the SQL Server CE Server Agent is configured with the IIS Web virtual directory name of 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.

Examples

C#

        SqlCeReplication repl = null;

        try {
            // Set the Replication object.
            repl = new SqlCeReplication();
            repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll";
            repl.InternetLogin     = "MyLogin";
            repl.InternetPassword  = "<MyPassword>";
            repl.Publisher         = "MyPublisher";
            repl.PublisherDatabase = "MyPublisher Database";
            repl.PublisherLogin    = "MyPublisher Login";
            repl.PublisherPassword = "<MyPublisher Password>";
            repl.Publication       = "MyPublication";
            repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\\ssce.sdf";
            repl.Subscriber        = "MySubscriber";

            // Mark the subscription for reinitialization with Upload first.
            repl.ReinitializeSubscription(true);

            // Synchronize to the instance of SQL Server 2000 to populate the Subscription.
            repl.Synchronize();
        }

        catch(SqlCeException e) {
            // Use your own error handling routine to show error information.
            // ShowError.ShowErrors(e);
        }

        finally {
            // Dispose of the Replication object.
            repl.Dispose();
        }

Visual Basic .NET

      Dim repl As SqlCeReplication = Nothing

      Try
         ' Set the Replication object.
         repl = New SqlCeReplication()
         repl.InternetUrl       = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
         repl.InternetLogin     = "MyLogin"
         repl.InternetPassword  = "<MyPassword>"
         repl.Publisher         = "MyPublisher"
         repl.PublisherDatabase = "MyPublisher Database"
         repl.PublisherLogin    = "MyPublisher Login"
         repl.PublisherPassword = "<MyPublisher Password>"
         repl.Publication       = "MyPublication"
         repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"
         repl.Subscriber        = "MySubscriber"

         ' Mark the subscription for reinitialization with Upload first.
         repl.ReinitializeSubscription(true)

         ' Synchronize to the instance of SQL Server 2000 to populate the Subscription.
         repl.Synchronize()

      Catch e As SqlCeException
      ' Use your own error handling routine to show error information.
      ' ShowErrors(e)

      Finally
         ' Dispose of the Replication object.
         repl.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the Replication object.
   Dim ce As SSCE.Replication

   ' Create the Replication object.
  Set ce = CreateObject("SSCE.Replication.2.0")

  ' Set Internet properties.
  ce.InternetURL = "http://www.northwindtraders.com/sqlce/sscesa20.dll"
  ce.InternetLogin = "sample_internetlogin"
  ce.InternetPassword = "<sample_internetpassword>"

  ' 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=\Ssce.sdf"
  ce.Subscriber = "SQLCE Sub #1"

  ' Mark the anonymous subscription for reinitialization.
   ' The bUploadBeforeReinit parameter is TRUE; therefore the changed data is uploaded.
  ce.ReinitializeSubscription TRUE

  ' Download the most current snapshot for the subscription.
  ' 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

See Also

ReinitializeSubscription Method

Initialize Method

Run Method

Terminate Method


Dropping a Subscription

A Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) application can use the Replication object to drop an anonymous subscription and optionally delete the SQL Server CE database from the Microsoft Windows CE-based device.

In the following examples, an application drops an existing subscription and deletes the SQL Server CE database from the Windows CE-based device.

Examples

C#

SqlCeReplication repl = null;

try {

// Set the Replication object.

repl = new SqlCeReplication();

repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\\ssce.sdf";

// Drop the subscription and delete the database.

repl.DropSubscription(DropOption.DropDatabase);

}

catch(SqlCeException e) {

// Use your own error handling routine to show error information.

// ShowError.ShowErrors(e);

}

finally {

// Dispose of the Replication object.

repl.Dispose();

}

Visual Basic .NET

      Dim repl As SqlCeReplication = Nothing

      Try
         ' Set the Replication object.
         repl = New SqlCeReplication()
         repl.SubscriberConnectionString = "Provider=Microsoft.SQLSERVER.OLEDB.CE.2.0;Data Source=\ssce.sdf"

         ' Drop the subscription and delete the database.
         repl.DropSubscription(DropOption.DropDatabase)

      Catch e As SqlCeException
      ' Use your own error handling routine to show error information.
      ' ShowErrors(e)

      Finally
         ' Dispose of the Replication object.
         repl.Dispose()
      End Try

eMbedded Visual Basic

   ' Declare the Replication object.
   Dim ce As SSCE.Replication

   ' Create the Replication object.
  Set ce = CreateObject("SSCE.Replication.2.0")

  ' Set Subscriber properties.
  ce.SubscriberConnectionString = "data source=\Ssce.sdf"

  ' Drop the anonymous subscription and delete the SQL Server CE database.
  ce.DropSubscription DROP_DATABASE

  Set ce = Nothing

eMbedded C++

   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=\\Ssce.sdf");
   pISSCEMerge->put_SubscriberConnectionString(bstr);
   SysFreeString(bstr);

   /* Drop the subscription and delete the database. */
   pISSCEMerge->DropSubscription(DROP_DATABASE));


Handling Replication Errors

The type of Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) application that you develop determines the way in which replication errors are handled:

  • Handling Errors in eMbedded Visual Tools Applications

    In the Microsoft® eMbedded Visual Basic® and Microsoft eMbedded Visual C++®, replication errors are handled by using SQL Server CE error control objects and collections.

  • Handling Errors in Smart Device Applications

    In C# and Visual Basic .NET, replication errors are handled by using the Microsoft .NET Framework data providers error control objects and collections.

See Also

SQL Server CE Error Control Objects and Collections

Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections


Replication Programmer's Reference for eMbedded Visual Tools

The topics in this section describe the methods and properties of the Replication object used in the Microsoft® eMbedded Visual Tools development environment. For more information about eMbedded Visual Tools, see Development Tools.

  • Replication Object Methods
  • Replication Object Properties


Replication Object Methods

The following table lists and describes the methods that the Replication object supports for the Microsoft® eMbedded Visual Tools development environment. For more information about eMbedded Visual Tools, see Development Tools.

Method | Description
AddSubscription Method | Creates a new anonymous subscription to an existing Microsoft SQL Server™ publication.
DropSubscription Method | Drops the subscription to a SQL Server publication and optionally deletes the Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE) database from the Microsoft Windows CE-based 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 Microsoft® SQL Server™ publication. After calling the AddSubscription method, the application must call the Initialize, Run, and Terminate methods to 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 database in Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE).

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 Microsoft Windows CE-based device (Default).
Prototype eVC++
HRESULT AddSubscription(DBADDOPTION DBAddOption);
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.
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

The DBADDOPTION value EXISTING_DATABASE specifies that the database already exists, but contents are obtained from the Publisher over 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 over 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-based device from the server.

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 Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) database from the Microsoft Windows CE-based 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. (Optional)

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 three replication system columns in the user tables but does not delete the database.
Prototype eVC++
HRESULT DropSubscription(DBDROPOPTION DBDropOption);
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.

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 the latest snapshot of the publication to the Microsoft® Windows® CE-based device.

Applies To

SQL Server CE Replication object

Syntax
object.ReinitializeSubscription(bUploadBeforeReInit)
Part | Description
object | SQL Server CE Replication object
bUploadBeforeReInit | If True, the changes in the subscription database are uploaded to the Publisher before the snapshot is applied at the Subscriber. The default is False.
Prototype eVC++
HRESULT ReinitializeSubscription(VARIANT_BOOL bUploadBeforeReInit);
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.
Remarks

A flag is marked in the subscription system table in Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE) 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-based device.

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
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.
Prototype eVC++
HRESULT Initialize( );
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.

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
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.
Prototype eVC++
HRESULT Run( );
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.

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
Returns
Return code | Description
S_OK | Method succeeded.
Any FAILED(HRESULT) | Check the SSCEErrors collection for detailed error information.
Prototype eVC++
HRESULT Terminate( );
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.

See Also

Replication Object Methods


Replication Object Properties

The following table lists the properties that the Replication object supports, and the methods to which they apply, for the Microsoft® eMbedded Visual Tools development environment.

Property | Add Subscription | Initialize, Run, 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


Distributor Property (Replication)

The Distributor property specifies the Microsoft® 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
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_Distributor(BSTR *pVal);
HRESULT put_Distributor(BSTR newVal);
Remarks

The Distributor is the computer running the instance of SQL Server on which the snapshots are stored and on which replication history and statistics are logged.

If the DistributorNetwork and DistributorAddress properties are specified, they are used instead of Distributor when connecting to the Distributor.

Distributor is optional. If none of the Distributor connection properties are specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor properties, you must set all of the required Distributor properties.

See Also

DistributorNetwork Property (Replication)

DistributorAddress Property (Replication)

Replication Object Properties


DistributorNetwork Property (Replication)

The DistributorNetwork property specifies the network protocol used when the SQL Server Reconciler 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 Reconciler communicates with the Distributor
Data Type

NETWORK_TYPE

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);
Remarks

DistributorNetwork must be specified when the SQL Server Reconciler connects to the Distributor using a network protocol other than the default protocol specified in Client Network Utility.

DistributorNetwork is optional. If none of the Distributor connection properties are specified, it is assumed the Publisher and Distributor are on the same instance of Microsoft® SQL Server™, and the Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor connection properties, you must set all of the required properties.

The DistributorAddress property must be specified if the value of DistributorNetwork is not DEFAULT_NETWORK (default).

See Also

DistributorAddress Property (Replication)

Distributor Property (Replication)

Replication Object Properties


DistributorAddress Property (Replication)

The DistributorAddress property specifies the network address used when connecting to the Distributor. DistributorAddress 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
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_DistributorAddress(BSTR *pVal);
HRESULT put_DistributorAddress(BSTR newVal);
Remarks

This is a required property only when DistributorNetwork is set to a value other than DEFAULT_NETWORK.

Specify this property to indicate how the SQL Server Reconciler 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 TCP/IP_SOCKETS, and DistributorAddress could be set to a specific IP address. If the DistributorNetwork is TCP/IP_SOCKETS or MULTI_PROTOCOL using TCP/IP, the DistributorNetwork value is in the form: 'IP address,socket' (for example, '111.11.11.11,1433')

If none of the Distributor connection properties are specified, it is assumed the Publisher and Distributor are on the same instance of SQL Server, and the Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor connection properties, you must set all of the required Distributor properties.

See Also

DistributorNetwork Property (Replication)

Distributor Property (Replication)

Replication Object Properties


DistributorSecurityMode Property (Replication)

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
Data Type

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);
Remarks

If the value is DB_AUTHENTICATION (default), DistributorLogin and DistributorPassword are used when connecting to the Distributor. If the value is NT_AUTHENTICATION, the Microsoft Internet Information Services (IIS) Windows user account is used when connecting to the Distributor.

If none of the Distributor connection properties are not specified, it is assumed the Publisher and Distributor are on the same instance of Microsoft SQL Server™, and the Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor connection properties, you must set all of the required Distributor properties.

See Also

DistributorLogin Property (Replication)

DistributorPassword Property (Replication)

Replication Object Properties


DistributorLogin Property (Replication)

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
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_DistributorLogin(BSTR *pVal);
HRESULT put_DistributorLogin(BSTR newVal);
Remarks

DistributorLogin is required if DistributorSecurityMode is set to DB_AUTHENTICATION.

If none of the Distributor connection properties are specified, it is assumed that the Publisher and Distributor are the same instance of Microsoft® SQL Server™ and that the Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor connection properties, you must set all of the required Distributor properties.

See Also

DistributorSecurityMode Property (Replication)

Replication Object Properties


DistributorPassword Property (Replication)

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. The default is no password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_DistributorPassword(BSTR *pVal);
HRESULT put_DistributorPassword(BSTR newVal);
Remarks

DistributorPassword is used only when DistributorSecurityMode is set to DB_AUTHENTICATION.

If none of the Distributor connection properties are specified, it is assumed that the Publisher and Distributor are the same instance of Microsoft® SQL Server™ and that Publisher connection properties are used when connecting to the Distributor. However, if you set any of the Distributor connection properties, you must set all of the required Distributor properties.

See Also

DistributorSecurityMode Property (Replication)

Replication Object Properties


ErrorRecords Property (Replication)

The ErrorRecords property contains the SSCEErrors collection for the Microsoft® SQL Server™ 2000 Windows® CE Edition (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
Data Type

SSCEErrors

Modifiable

Read-only

Prototype eVC++
HRESULT get_ErrorRecords(SSCEErrors *pVal);
Remarks

The SSCEErrors 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.

See Also

Replication Object Properties

SSCEError Object


ExchangeType Property (Replication)

The ExchangeType property specifies whether the synchronization between the Publisher and the Subscriber is bidirectional or upload-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
Data Type

EXCHANGE_TYPE

Constant | Value | Description
BIDIRECTIONAL | 3 | Merge all changes between the Publisher and Subscriber (Default).
UPLOAD | 1 | Only merge Subscriber changes with the Publisher.
Modifiable

Read/write

Prototype eVC++
HRESULT get_ExchangeType(EXCHANGE_TYPE *pVal);
HRESULT put_ExchangeType(EXCHANGE_TYPE newVal);
Remarks

BIDIRECTIONAL is used to first upload data to the Publisher. After the upload is complete, data is then downloaded to the Subscriber. Exchange_Type is forced to BIDIRECTIONAL during initial synchronization or when a ReinitializeSubscription is requested. Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) does not support the Exchange_Type value DOWNLOAD.

See Also

ReinitializeSubscription Method

Replication Object Properties


HostName Property (Replication)

The HostName property sets the host name used for the device when connecting to the Publisher. HostName is used when the publication is dynamically filtered based on the Microsoft® SQL Server™ HOST_NAME( ) function. HostName is optional.

Applies To

SQL Server CE Replication object

Syntax
object.HostName [= value]
Part | Description
object | SQL Server CE Replication object
value | Host name. The default is no host name.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_HostName(BSTR *pVal);
HRESULT put_ HostName (BSTR newVal);
Remarks

Use HostName to set a value for HOST_NAME( ) in a dynamic filter. For example, if the subset filter clause is specified for an article as "LName = HOST_NAME( )", and you set HostName to "Jones" before calling the Run method, only rows having "Jones" in the LName column are present in the subscription. For more information, see "Dynamic Filters" in SQL Server Books Online.

An application must call the ReinitializeSubscription method if it changes the value of HostName after the subscription is created.

See Also

ReinitializeSubscription Method

Replication Object Properties


InternetURL Property (Replication)

The InternetURL property specifies the URL used to connect to the SQL Server CE Server Agent. SQL The SQL Server CE Server Agent connects the Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) client to the Microsoft SQL Server database. This property must be specified.

Applies To

SQL Server CE Replication object

Syntax
object.InternetURL [= value]
Part | Description
object | SQL Server CE Replication object
value | URL string, including the location of the SQL Server CE Server Agent (Sscesa20.dll)
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetURL(BSTR *pVal);
HRESULT put_ InternetURL (BSTR newVal);
Remarks

InternetURL can include a port number if you want to override the default port, for example: http://yourserver:81/ssce/sscesa20.dll, where port 81 is used on the IIS server. The default port for HTTP is 80, and the default port for HTTPS is 443.

See Also

Configuring Security for Connectivity

Replication Object Properties


InternetLogin Property (Replication)

The InternetLogin property specifies the Microsoft® Internet Information Services (IIS) login name used when connecting to the SQL Server CE Server Agent.

Applies To

SQL Server CE Replication object

Syntax
object.InternetLogin [= value]
Part | Description
object | SQL Server CE Replication object
value | IIS login name. The default is no login.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetLogin(BSTR *pVal);
HRESULT put_ InternetLogin (BSTR newVal);
Remarks

InternetLogin is required if the SQL Server CE Server Agent is configured to use Basic authentication or Integrated Windows authentication. When Integrated Windows authentication is used, InternetLogin is not passed across the network.

See Also

Configuring Security for Connectivity

Replication Object Properties


InternetPassword Property (Replication)

The InternetPassword property specifies the Microsoft® Internet Information Services (IIS) 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. The default is no password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetPassword(BSTR *pVal);
HRESULT put_InternetPassword(BSTR newVal);
Remarks

InternetPassword is required if the SQL Server CE Server Agent is configured to use Basic authentication or Integrated Windows authentication. When Integrated Windows authentication is used, InternetPassword is not passed across the network.

When using Basic authentication, you should configure IIS to use Secure Sockets Layer (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 unsafe; therefore, we strongly recommend that you always use SSL or PCT encryption to safeguard passwords when using Basic authentication.

See Also

Configuring Security for Connectivity

Replication Object Properties


InternetProxyServer Property (Replication)

The InternetProxyServer property specifies the proxy server to use when you access 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 | Proxy name (or IP address) and port number (ProxyServerName:Port)
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyServer(BSTR *pVal);
HRESULT put_ InternetProxyServer (BSTR newVal);
Remarks

If SQL Server CE Relay is properly configured on a desktop computer for serial, USB, or infrared (IR) synchronization, InternetProxyServer must be set to ppp_peer:nn where nn is a specified client port number, for example: exampleproxy:80.

If InternetProxyServer is not set or is empty, no proxy server is used.

See Also

InternetURL Property (Replication)

Using SQL Server CE Relay

Replication Object Properties


InternetProxyLogin Property (Replication)

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 | Proxy server login name. The default is no login.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyLogin(BSTR *pVal);
HRESULT put_ InternetProxyLogin (BSTR newVal);
Remarks

InternetProxyLogin 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.

See Also

InternetProxyServer Property (Replication)

Configuring Security for Connectivity

Using SQL Server CE Relay

Replication Object Properties


InternetProxyPassword Property (Replication)

The InternetProxyPassword property specifies the password used when you connect 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 | Proxy server password string. The default is no password.
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_InternetProxyPassword(BSTR *pVal);
HRESULT put_InternetProxyPassword(BSTR newVal);
Remarks

InternetProxyPassword 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.

See Also

InternetProxyServer Property (Replication)

Configuring Security for Connectivity

Using SQL Server CE Relay

Replication Object Properties


LoginTimeout Property (Replication)

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. The default is 15 seconds.
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 (Replication)

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 time-out values. You can override the default values by creating a profile on the Distributor and specifying its name through ProfileName.

Applies To

SQL Server CE Replication object

Syntax
object.ProfileName [= value]
Part | Description
object | SQL Server CE Replication object
value | Agent profile name
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_ProfileName(BSTR *pVal);
HRESULT put_ProfileName(BSTR newVal);
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. For more information, see "Agent Profiles" in SQL Server Books Online.

The profile allows you to easily change key parameters for synchronization. For example, if you have five Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) clients that share a profile and you want to change the query time-out value, you simply change the QueryTimeOut value in the profile, and then 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 time-out value, and a client that uses a high-speed intranet connection might use a different time-out value. ProfileName is used to specify the name of the profile.

If ProfileName is not specified, the default profile values are used.

If ProfileName is specified, the LoginTimeOut and QueryTimeOut parameters specified in the profile will override the LoginTimeOut and QueryTimeOut property values specified through the Replication object.

See Also

LoginTimeout Property (Replication)

QueryTimeout Property (Replication)

Replication Object Properties


Publisher Property (Replication)

The Publisher property specifies the name of the Publisher. The Publisher is the computer that is running Microsoft® SQL Server™ and contains the publication. The Publisher property is required.

Applies To

SQL Server CE Replication object

Syntax
object.Publisher [= value]
Part | Description
object | SQL Server CE Replication object
value | Publisher name
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_Publisher(BSTR *pVal);
HRESULT put_Publisher(BSTR newVal);
Remarks

If the PublisherNetwork and PublisherAddress properties are specified, they are used instead of Publisher when connecting to the Publisher.

See Also

PublisherNetwork Property (Replication)

PublisherAddress Property (Replication)

Replication Object Properties


PublisherNetwork Property (Replication)

The PublisherNetwork property specifies the network protocol used when the SQL Server Replication Provider 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 constant specifies the network protocol used when the SQL Server Replication Provider communicates with the Publisher.
Data Type

NETWORK_TYPE

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);
Remarks

PublisherNetwork must be specified when the SQL Server Replication Provider connects to the Publisher using a network protocol other than the default protocol specified in Client Network Utility.

The PublisherAddress property must be specified if the value of PublisherNetwork is not DEFAULT_NETWORK (default).

See Also

PublisherAddress Property (Replication)

Replication Object Properties


PublisherAddress Property (Replication)

The PublisherAddress property specifies the network address used when connecting to the Publisher. PublisherAddress 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
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_PublisherAddress(BSTR *pVal);
HRESULT put_PublisherAddress(BSTR newVal);
Remarks

PublisherAddress is required when PublisherNetwork is set to a value other than DEFAULT_NETWORK.

Specify this property to indicate how the SQL Server Replication Provider 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 TCP/IP_SOCKETS, and PublisherAddress could be set to a specific IP address.

If PublisherNetwork is TCP/IP_SOCKETS or MULTI_PROTOCOL using TCP/IP, the PublisherAddress value is in the form of 'IP address,socket' (for example, '111.11.11.11,1433').

See Also

PublisherNetwork Property (Replication)

Replication Object Properties


PublisherSecurityMode Property (Replication)

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_TYPE constant that specifies the security type.
Data Type

SECURITY_TYPE

Constant | Value | Description
DB_AUTHENTICATION | 0 | SQL Server authentication (Default)
NT_AUTHENTICATION | 1 | Windows authentication
Modifiable

Read/write

Prototype eVC++
HRESULT get_PublisherSecurityMode(SECURITY_TYPE *pVal);
HRESULT put_PublisherSecurityMode(SECURITY_TYPE newVal);
Remarks

If PublisherSecurityMode is DB_AUTHENTICATION (default), PublisherLogin must be specified. The default for PublisherPassword is an empty string.

See Also

PublisherLogin Property (Replication)

PublisherPassword Property (Replication)

Replication Object Properties


PublisherLogin Property (Replication)

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 | Publisher login name
Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_PublisherLogin(BSTR *pVal);
HRESULT put_PublisherLogin(BSTR newVal);
Remarks

PublisherLogin is a required property if PublisherSecurityMode is set to DB_AUTHENTICATION.

See Also

PublisherSecurityMode Property (Replication)

Replication Object Properties


PublisherPassword Property (Replication)

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 | Publisher login password. 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 (Replication)

The PublisherDatabase property specifies the name of the publication database. PublisherDatabase is a required property.

Applies To

SQL Server CE Replication object

Syntax
object.PublisherDatabase [= value]
Part | Description
object | SQL Server CE Replication object
value | Publication database name
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 (Replication)

The Publication property specifies the publication name that has been enabled for anonymous merge subscriptions. Publication is a required property.

Applies To

SQL Server CE Replication object

Syntax
object.Publication [= value]
Part | Description
object | SQL Server CE Replication object
value | Publication name
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 (Replication)

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 (Replication)

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 (Replication)

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. The default is 300 seconds.
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 (Replication)

The Subscriber property specifies the name of the Subscriber. This is a required property.

Applies To

SQL Server CE Replication object

Syntax
object.Subscriber [= value]
Part | Description
object | SQL Server CE Replication object
value | Subscriber name
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 (Replication)

The SubscriberConnectionString property specifies the OLE DB connection string for the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database on the Microsoft Windows CE-based 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

The connection properties listed in the following table are supported. All other connection properties are ignored.

Property | Required or optional | Description
Provider | Optional | Specifies the name of the data source provider. If the provider is not specified, Microsoft.sqlserver.oledb.ce.2.0 is assumed.
Data Source | Required | Specifies the name of the database. By convention, you should name the SQL Server CE databases with the file extension .sdf.
Locale Identifier | Optional | Specifies the database locale, which specifies the collation order for string comparisons in the database. This property is meaningful only when calling AddSubscription(CREATE_DATABASE). The default database locale is Latin1_General (0x00000409). For other supported values, see Collate.
SSCE:Database Password | Optional | Specifies 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 | Specifies 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. To find a list of Unique LCID values, see Collate. You must ensure that the locale is supported on the device on which the database is being created.

Data Type

string

Modifiable

Read/write

Prototype eVC++
HRESULT get_SubscriberConnectionString(BSTR *pVal);
HRESULT put_SubscriberConnectionString(BSTR newVal);
Examples

object.SubscriberConnectionString = "Data Source=\ssce.sdf; Locale Identifier=0x00000409; SSCE:Database Password=mypassword; SSCE:Encrypt Database=TRUE"

See Also

AddSubscription Method

Replication Object Properties


SubscriberChanges Property (Replication)

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 (Replication)

The SubscriberConflicts property is not used by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Applies To

SQL Server CE Replication object

Syntax
object.SubscriberConflicts [= value]
Part | Description
object | SQL Server CE Replication object
value | Always 0 because 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 (Replication)

The Validate property controls whether Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) replication performs data validation during 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
Data Type

VALIDATE_TYPE

Constant | Value | Description
NO_VALIDATION | 0 | Do not validate (Default).
ROWCOUNT_ONLY | 1 | Do a row count comparison on the published data.
Modifiable

Read/write

Prototype eVC++
HRESULT get_Validate(VALIDATE_TYPE *pVal);
HRESULT put_Validate(VALIDATE_TYPE newVal);
Remarks

SQL Server CE does not support ROWCOUNT_AND_CHECKSUM, FAST_ROWCOUNT_ONLY, or FAST_ROWCOUNT_AND_CHECKSUM validation. For more information, see "Validating Replicated Data" in SQL Server Books Online.

See Also

Replication Object Properties


.NET Compact Framework Data Providers

Microsoft® ADO.NET is a set of classes that expose data access services. ADO.NET is an evolutionary improvement to Microsoft ActiveX® Data Objects (ADO). ADO.NET is an integral part of the .NET Compact Framework, providing access to relational data, XML documents, and application data. ADO.NET supports a variety of development needs, including the creation of database-client applications and middle-tier business objects used by applications, tools, languages, or Internet browsers.

Core elements in the ADO.NET architecture are the .NET Compact Framework Data Provider for SQL Server CE (System.Data.SqlServerCe) and the .NET Compact Framework Data Provider for SQL Server (System.Data.SqlClient). These data providers are used to connect to, execute commands in, and retrieve results from databases in Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) and Microsoft SQL Server™, respectively.

System.Data.SqlServerCe is used for programming Windows CE .NET-based applications that are semiconnected to or disconnected from SQL Server databases. System.Data.SqlClient is used for programming Windows CE .NET-based applications that have direct connections to SQL Server databases (however, these applications must have network access).

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

The following topics in this section provide general programming information about the System.Data.SqlServerCe and System.Data.SqlClient namespaces. This section also contains walkthrough information about how to programmatically perform basic tasks using System.Data.SqlServerCe objects.

  • Data Provider for SQL Server CE (SqlServerCe)
  • System.Data.SqlServerCe Objects
  • Getting Started with System.Data.SqlServerCe
  • Advanced Programming Using System.Data.SqlServerCe
  • Data Provider for SQL Server (SqlClient)
Setting Up a Project

Before an application can work with ADO.NET, you must configure your projects to reference the .NET Compact Framework data providers that you plan to use.

To create a reference to the .NET Compact Framework data provider

  1. In an open Microsoft Visual Studio® .NET project, on the Project menu, click Add References.
  2. On the .NET tab, select either System.Data.SqlServerCe for SQL Server CE or System.Data.SqlClient for SQL Server version 7.0 or later.

    Note In some cases, you may need to reference System.Data.Common if your application uses DataAdapter or CommandBuilder classes.

  3. Click Select, and then click OK.


Data Provider for SQL Server CE (SqlServerCe)

System.Data.SqlServerCe provides programmatic access to databases in Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) from a Microsoft Visual Studio® .NET application running on a Windows CE-based platform. System.Data.SqlServerCe provides a set of classes designed to expose the functionality of SQL Server CE. For a list of classes in this namespace, see System.Data.SqlServerCe Objects. For more information about the classes in this namespace, see the .NET Compact Framework SDK in Microsoft Visual Studio .NET.

Supported Functionality

System.Data.SqlServerCe provides the following functionality:

  • Consistent access to SQL Server CE data sources.

    Consumer applications that share data can use the SQL Server CE data provider to connect to SQL Server CE data sources, and retrieve, manipulate, and update data.

  • Components for connecting to a database, executing commands, and retrieving results.

    The retrieved results can be processed directly or placed in an ADO.NET DataSet object to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or propagated remotely between tiers.

  • Functionality to developers writing managed code.

    This functionality is similar to that provided by ADO to native COM developers.

  • Index functionality for optimal performance.

    SqlCeCommand.SetRange restricts the set of row entries visible through calls to SqlCeDataReader.Read and SqlCeDataReader.Seek. SqlCeDataReader.Seek allows direct positioning at a key value within the current range.

  • Interfaces needed to interact with the SQL Server CE Replication and Remote Data Access (RDA) objects through the SqlCeReplication and SqlCeRemoteDataAccess classes.
  • SqlCeEngine class methods that enable database creation and compaction.
  • Parameterized query functionality.

    All parameter placeholders must be substituted with question marks (?) in the SqlCeCommand.CommandText property. Named parameters are not supported.

  • Database encryption and password protection.
Provider Limitations

The data provider for SQL Server CE has the following limitations:

  • Support for only one concurrent connection to SQL Server CE data source. Unlike the data provider for SQL Server, however, System.Data.SqlServerCe supports multiple data readers created on the same connection.
  • No support for batch queries. Queries must be a single SQL statement. For example, the following statement is valid:
    SELECT * FROM Customers

    This statement is not valid:

    SELECT * FROM Customers; SELECT * FROM Customers2

    Datasets must be refreshed from a SqlCeDataAdapter. If you are using code from a Visual Studio .NET project, you must modify your SQL statement to conform to this restriction.

  • No support for nested or parallel transactions.
  • No support for named parameters.


System.Data.SqlServerCe Objects

System.Data.SqlServerCe is the .NET Compact Framework Data Provider for SQL Server CE. The following tables list the collection of classes, delegates, and enumerations that comprise the System.Data.SqlServerCe namespace. For more information about these objects, see the .NET Compact Framework SDK in Microsoft® Visual Studio® .NET.

Classes
Class | Description
SqlCeCommand | Represents an SQL statement to execute against a data source.
SqlCeCommandBuilder | Provides a means of automatically generating single-table commands used to reconcile changes made to a DataSet with the associated Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database. This class cannot be inherited.
SqlCeConnection | Represents an open connection to a data source.
SqlCeDataAdapter | Represents a set of data commands and a database connection that are used to fill the DataSet and update the data source.
SqlCeDataReader | Provides a way of reading a forward-only stream of data rows from a data source. This class cannot be inherited.
SqlCeEngine | Represents the properties, methods, and other objects of the SQL Server CE Engine object. This class cannot be inherited.
SqlCeError | Collects information relevant to a warning or error returned by the data source. This class cannot be inherited.
SqlCeErrorCollection | Collects all errors generated by the .NET Compact Framework Data Provider for SQL Server CE. This class cannot be inherited.
SqlCeException | The exception that is thrown when the underlying provider returns a warning or error from a SQL Server CE data source. This class cannot be inherited.
SqlCeInfoMessageArgs | Provides data for the InfoMessage event. This class cannot be inherited.
SqlCeParameter | Represents a parameter to a SqlCeCommand and optionally its mapping to a DataSet column. This class cannot be inherited.
SqlCeParameterCollection | Collects all parameters relevant to a SqlCeCommand as well as their respective mappings to DataSet columns.
SqlCeRemoteDataAccess | Initializes a new instance of the SqlCeRemoteDataAccess object.
SqlCeReplication | Initializes a new instance of the SqlCeReplication object.
SqlCeRowUpdatedEventArgs | Provides data for the RowUpdated event.
SqlCeRowUpdatingEventArgs | Provides data for the RowUpdating event.
SqlCeTransaction | Represents an SQL transaction to be made at a data source. This class cannot be inherited.
Delegates
Delegate | Description
SqlCeInfoMessageEventHandler | Represents the method that will handle the InfoMessage event of a SqlCeConnection.
SqlCeRowUpdatedEventHandler | Represents the method that will handle the RowUpdated event of a SqlCeDataAdapter.
SqlCeRowUpdatingEventHandler | Represents the method that will handle the RowUpdating event of a SqlCeDataAdapter.
Enumerations
Enumeration | Description
AddOption | Specifies the source of the newly created SQL Server CE database.
DbRangeOptions | Options used by SetRange when specifying the index range over which to Seek.
DbSeekOptions | Options that specify how to Seek on an index.
DropOption | Specifies whether to leave or delete the SQL Server CE database during a drop subscription.
ExchangeType | Specifies whether data merges up to the Publisher or in both directions between the Publisher and the Subscriber.
NetworkType | Specifies the network protocol used.
RdaBatchOption | Specifies whether or not the rows associated with the Push should be batched together in a single transaction.
RdaTrackOption | Specifies whether or not the table being pulled to the device is tracked.
SecurityType | Specifies the mode of security enforced.
ValidateType | Specifies the type of data validation to perform.


Getting Started with System.Data.SqlServerCe

This topic provides a walkthrough that shows how to use the System.Data.SqlServerCe namespace to perform the following basic tasks programmatically:

  • Creating a SQL Server CE Database
  • Reading SQL Server CE Database Data
  • Updating Data in a SQL Server CE Database

Ensure that you have installed the Microsoft® .NET Compact Framework and Microsoft Visual Studio® .NET. For more information, see Installing SQL Server CE with Visual Studio .NET.

The following code is the complete C# code that performs all the tasks contained in the walkthrough. You can copy, paste, and run this code in a Visual Studio .NET project.

Walkthrough Sample

using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using System.Data.Common;

public class WalkThrough
{
    static void Main()
    {
        SqlCeConnection conn = null;

        try
        {
            if (File.Exists ("Test.sdf") )
                File.Delete ("Test.sdf");

            SqlCeEngine engine = new SqlCeEngine ("Data Source = Test.sdf");
            engine.CreateDatabase ();

            conn = new SqlCeConnection ("Data Source = Test.sdf");
            conn.Open();

            SqlCeCommand cmd = conn.CreateCommand ();

            cmd.CommandText =
                "CREATE TABLE TestTbl (col1 INT PRIMARY KEY, col2 NTEXT, col3 MONEY)";

            cmd.ExecuteNonQuery();

            cmd.CommandText =
                "INSERT INTO TestTbl (col1, col2, col3) VALUES (0, 'abc', 15.66)";

            cmd.ExecuteNonQuery();

            cmd.CommandText = "INSERT INTO TestTbl (col1, col2, col3) VALUES (?, ?, ?)";

            cmd.Parameters.Add(new SqlCeParameter("p1", SqlDbType.Int));
            cmd.Parameters.Add(new SqlCeParameter("p2", SqlDbType.NText));
            cmd.Parameters.Add(new SqlCeParameter("p3", SqlDbType.Money));

            cmd.Parameters["p2"].Size = 50;

            cmd.Prepare();

            cmd.Parameters["p1"].Value = 1;
            cmd.Parameters["p2"].Value = "abc";
            cmd.Parameters["p3"].Value = 15.66;
            cmd.ExecuteNonQuery();

            cmd.Parameters.Clear();

            cmd.CommandText = "SELECT * FROM TestTbl";

            SqlCeDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                MessageBox.Show(" col1 = " + rdr.GetInt32(0) +
                    " col2 = " + rdr.GetString(1) +
                    " col3 = " + rdr.GetSqlMoney(2));
            }

            cmd.CommandText = "UPDATE TestTbl set col2='some new value' WHERE col1=0";
            cmd.ExecuteNonQuery();

            cmd.CommandText = "SELECT * FROM TestTbl";

            rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                MessageBox.Show(" col1 = " + rdr.GetInt32(0) +
                    " col2 = " + rdr.GetString(1) +
                    " col3 = " + rdr.GetSqlMoney(2));
            }

        }
        catch (SqlCeException e)
        {
            ShowErrors(e);
        }
        finally
         {
            if(conn.State == ConnectionState.Open)
               conn.Close();
         }
    }

    public static void ShowErrors(SqlCeException e)
    {
        SqlCeErrorCollection errorCollection = e.Errors;

        StringBuilder bld = new StringBuilder();
        Exception   inner = e.InnerException;

        foreach (SqlCeError err in errorCollection)
        {
            bld.Append("\n Error Code: " + err.HResult.ToString("X"));
            bld.Append("\n Message   : " + err.Message);
            bld.Append("\n Minor Err.: " + err.NativeError);
            bld.Append("\n Source    : " + err.Source);

            foreach (int numPar in err.NumericErrorParameters)
            {
                if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
            }

            foreach (string errPar in err.ErrorParameters)
            {
                if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
            }

            MessageBox.Show(bld.ToString());
            bld.Remove(0, bld.Length);
        }
    }
}
Creating a SQL Server CE Database

The following procedures show how to create a new Microsoft® SQL Server™ Windows® CE Edition (SQL Server CE) database in a new Microsoft Visual Studio® .NET project.

By performing the steps in these procedures, you can:

  • Create a new SQL Server CE database.
  • Create a table in the database.
  • Populate the table with data.

For the complete code that you can copy, paste, and run in a Visual Studio .NET project, see "Walkthrough Sample" earlier in this topic.

To create a new SQL Server CE database

  1. Start Visual Studio .NET and open a new project.
  2. Create references to the namespaces you are using:
    using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Collections;
using System.Windows.Forms;
using System.Data.Common;
  3. Create the WalkThrough class:
    public class WalkThrough
{
    static void Main()
    {
        SqlCeConnection conn = null;

        try
        {
  4. Verify that a database with the name you plan to use does not already exist:
                if (File.Exists ("Test.sdf") )
                File.Delete ("Test.sdf");
  5. Create an empty database, by using the SqlCeEngine object:
                SqlCeEngine engine = new SqlCeEngine ("Data Source = Test.sdf");
            engine.CreateDatabase ();
  6. Connect to the new database, by using the SqlCeConnection object:
    conn = new SqlCeConnection ("Data Source = Test.sdf");
conn.Open();

To create a new table

  1. Create an instance of the command class, by using the SqlCeCommand object:
    SqlCeCommand cmd = conn.CreateCommand();
  2. Run a command to create the table:
    cmd.CommandText = "CREATE TABLE TestTbl(col1 int PRIMARY KEY, col2 ntext, col3 money)";
cmd.ExecuteNonQuery();

To populate a new table with data

  1. Run a command to insert a row of data:
    cmd.CommandText =  "INSERT INTO TestTbl(col1, col2, col3) VALUES (0, 'abc', 15.66)";
cmd.ExecuteNonQuery();
  2. Using SqlCeParameter, create a command using parameters to insert data to the table multiple times:
    cmd.CommandText = "INSERT INTO TestTbl(col1, col2, col3) VALUES (?, ?, ?)";

cmd.Parameters.Add(new SqlCeParameter("p1", SqlDbType.Int));
cmd.Parameters.Add(new SqlCeParameter("p2", SqlDbType.NText));
cmd.Parameters.Add(new SqlCeParameter("p3", SqlDbType.Money));

cmd.Parameters["p2"].Size = 50;

cmd.Prepare();
  3. Execute the parameterized command to insert data to the table:
    cmd.Parameters["p1"].value = 1;
cmd.Parameters["p2"].value = "abc";
cmd.Parameters["p3"].value = 15.66;
cmd.ExecuteNonQuery();
  4. Clear the parameter, and check the data you inserted into the table:
    cmd.Parameters.Clear();
//Set the command text to a SELECT query.
//
cmd.CommandText = "SELECT * FROM TestTbl";
Reading SQL Server CE Database Data

The following example shows how to read data in an existing SQL Server CE database by using the SqlCeDataReader class:

SqlCeDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
   MessageBox.Show("col1 = " + rdr.GetInt32(0) +
      "col2 = " + rdr.GetString(1) +
      "col3 = " + rdr.GetSqlMoney(2));

For the complete code that you can copy, paste, and run in a Visual Studio .NET project, see "Walkthrough Sample" earlier in this topic.

Updating Data in a SQL Server CE Database

The following procedures show how to update a SQL Server CE table by using the objects and classes that are used earlier in Creating a SQL Server CE Database and Reading SQL Server CE Data.

By performing the steps in these procedures, you can:

  • Change existing data in a SQL Server CE table.
  • Read data in a SQL Server CE table.
  • Handle errors.

For the complete code that you can copy, paste, and run in a Visual Studio .NET project, see the "Walkthrough Sample" earlier in this topic.

To update data in a SQL Server CE table

  • Set the command object to use the UPDATE statement:
    cmd.CommandText = "UPDATE TestTbl SET col2 = 'some new value' WHERE col1 = 0";
cmd.ExecuteNonQuery();

To read data in a SQL Server CE table

  1. Set the command object to use the SELECT statement:
    cmd.CommandText = "SELECT * FROM TestTbl";
  2. Create an instance of SqlCeDataReader to read the data:
    rdr = cmd.ExecuteReader();
while (rdr.Read())
{
MessageBox.Show("col1 = " + rdr.GetInt32(0) +
   "col2 = " + rdr.GetString(1) +
   "col3 = " + rdr.GetSqlMoney(2));
}
}
  3. Catch any errors by using SqlCeException, and close the connection to the database:
    catch (SqlCeException e)
{
      ShowErrors(e);
}
finally
{
   if(conn.State == ConnectionState.Open)
      conn.Close();
}
}

    public static void ShowErrors(SqlCeException e)
    {
        SqlCeErrorCollection errorCollection = e.Errors;

        StringBuilder bld = new StringBuilder();
        Exception   inner = e.InnerException;

        foreach (SqlCeError err in errorCollection)
        {
            bld.Append("\n Error Code: " + err.HResult.ToString("X"));
            bld.Append("\n Message   : " + err.Message);
            bld.Append("\n Minor Err.: " + err.NativeError);
            bld.Append("\n Source    : " + err.Source);

            foreach (int numPar in err.NumericErrorParameters)
            {
                if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
            }

            foreach (string errPar in err.ErrorParameters)
            {
                if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
            }

            MessageBox.Show(bld.ToString());
            bld.Remove(0, bld.Length);
        }
    }
}

For more information about handling errors in SQL Server CE, see Handling Errors in Smart Device Applications.


Advanced Programming Using System.Data.SqlServerCe

This topic describes advanced programming issues relating to the Microsoft® .NET Compact Framework Data Provider for SQL Server CE.

Seeking on an Index

By using the Seek method of the SqlCeDataReader object, you can quickly find rows in a result set (or cursor). When seeking, you can specify both the range of the index over which to seek and the way in which rows are selected. To seek, the IndexName property must be specified on the SqlCeCommand object.

Setting the Index Range

The SetRange method of the SqlCeCommand object specifies the range of the index on which to seek. Ranges are typically specified with index start and end values and range options, which are defined by the DbRangeOptions enumeration. If no range options are specified, by default the range includes both the start and end values. If a range option of DbRangeOptions.Match is set, the range include only rows in which index values match the startData value. If a range option of DbRangeOptions.Prefix is set, the range includes all rows in which the index values begin with the startData value. When you use Match or Prefix, the end value must be set to NULL. For more information, see the "DbRangeOptions Enumeration" topic in the .NET Framework Class Library reference.

Seek Options

Seek options specify how to select rows on an index. Options, such as FirstEqual, LastEqual, BeforeEqual, and AfterEqual (that have Equal in their names) select rows that match the seek value. If no rows of the index match the seek value, a row either before (in the case of FirstEqual and BeforeEqual) or after (in the case of AfterEqual and LastEqual) is selected. For more information, see the "DbSeekOptions Enumeration" topic in the .NET Framework Class Library reference.

Examples

The following C# example shows the Seek method being executed on a three-column index in which the data types on the columns are integer, datetime, and money. The index range for the integer index is from 1 to 5, inclusive. The index ranges for the datetime and money columns start at 1/1/1996 and $10.00, respectively. This sample selects a row in which the integer column is 1, the datetime column is 1/1/1997, and the money column is $10.50. If an index that matches this criteria does not exist, the AfterEqual property causes the next row on the index to be selected.

// Example that seeks on a three-column index
public void CreateMySqlCeCommand(SqlCeConnection conn)
{
    SqlCeCommand cmd = conn.CreateCommand();
    cmd.CommandType  = CommandType.TableDirect;

    // This is the name of the base table.
    cmd.CommandText  = "Orders";

    //Assume: Index contains three columns [int, datetime, money]
    cmd.IndexName    = "SomeIndex";

    object[] start = new object[3];
    object[] end   = new object[1];

    start[0] = 1;
    start[1] = new SqlDateTime(1996, 1, 1);
    start[2] = new SqlMoney(10.00);

    end[0]   = 5;

    cmd.SetRange(DbRangeOptions.InclusiveStart |
        DbRangeOptions.InclusiveEnd, start, end);

    SqlCeDataReader rdr = cmd.ExecuteReader();
    rdr.Seek(DbSeekOptions.AfterEqual, 1, new SqlDateTime(1997, 1,1),
        new SqlMoney(10.50));

    while(rdr.Read())
    {
        // Read data in the usual way.
    }
    rdr.Close();
}


Data Provider for SQL Server (SqlClient)

You can develop Microsoft® Windows® CE-based applications that access databases in Microsoft SQL Server™ version 7.0 or later by using the System.Data.SqlClient namespace. System.Data.SqlClient is the .NET Compact Framework Data Provider for SQL Server. This data provider corresponds to the System.Data.SqlClient namespace of the Microsoft .NET Framework.

Like its counterpart, System.Data.SqlClient in the .NET Compact Framework is a collection of classes that can be used to access SQL Server databases with managed code from Windows CE .NET-based devices.

Unless otherwise noted, all objects in the System.Data.SqlClient namespace match the corresponding objects in the System.Data.SqlClient namespace in the .NET Framework. For more information about the classes in this namespace, see the .NET Compact Framework SDK in Microsoft Visual Studio .NET.

Provider Limitations

The following lists limitations and exceptions that apply to Windows CE .NET-based devices and the .NET Compact Framework:

  • Unsupported classes

    SqlClientPermission and SqlClientPermissionAttribute classes are not supported.

  • ConnectionString property

    Applications using System.Data.SqlClient on Windows CE-based devices may leverage the Windows authentication protocol, instead of using SQL Server authentication. To do this, the connection string must include the following properties:

    Property | Value
    Integrated Security | SSPI
    User ID | Domain\username
    Password | <password>

    In addition, the following ConnectionString properties are not supported: AttachDBFilename, Max Pool Size, Min Pool Size, Connection Lifetime, Connection Reset, Enlist, Pooling, Network Library, and Encrypt.

  • ANSI data

    ANSI data is supported only for SQL_Latin1_General_CP1_CI_AS collations from an English-based device. All strings in the .NET Framework are Unicode. System.Data.SqlClient converts ANSI data in SQL Server to Unicode using the .NET Framework Encoding classes. Although the Encoding classes are supported in the .NET Compact Framework, not all code pages are.

    Also, System.Data.SqlClient cannot read from or write to an ANSI column if the code page for the column is not available on the Windows CE-based device. System.Data.SqlClient generates an error when the code page for an ANSI-to-Unicode conversion is not available.

    For information about code pages that are available to a specific Windows CE-based device, contact the device manufacturer.

  • Connection pooling

    Connection pooling is not supported. A device can only have a small number of connections to an instance of SQL Server at any time.

  • Distributed transactions

    Distributed transactions are not supported. Transactions cannot span databases or servers. System.Data.SqlClient generates an InvalidOperationException exception during a distributed transaction.

  • Net-Library selection

    Only TCP/IP connections to an instance of SQL Server are supported. System.Data.SqlClient cannot connect to SQL Server through a device cradle.

  • Net-Library encryptions

    Encrypted connections to an instance of SQL Server are not supported. If the computer running SQL Server has a Secure Sockets Layer (SSL) certificate installed, the connection will fail.

  • Windows authentication

    Windows authentication is supported; however, the User ID and Password used for authentication within the Domain Controller must always be specified in the connection string.

For more information, see the System.Data.SqlClient namespace reference in the .NET Compact Framework SDK in Microsoft Visual Studio .NET.


Error Handling

An application you develop should explicitly trap and handle errors. By trapping and handling errors as they occur in the application, you can perform sophisticated error recovery and display meaningful error messages. Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides rich support for run-time errors generated by the SQL Server CE database engine.

In SQL Server CE-based applications, how errors are handled depends on whether the application is a Microsoft eMbedded Visual Tools application or a smart device application in Microsoft Visual Studio® .NET. The topics in the following sections describe error handling in these development environments:

  • Handling Errors in eMbedded Visual Tools Applications
  • Handling Errors in Smart Device Applications


Handling Errors in eMbedded Visual Tools Applications

For applications you develop using Microsoft® eMbedded Visual Tools, error information can be obtained from the application runtime, the data provider, or by using the Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) ActiveX® error control objects and collections. For eMbedded Visual Tools-based applications, using the SQL Server CE error control objects and collections is the method for handling Replication, RDA, and Engine object errors.

The following topics provide information about error handling in eMbedded Visual Tools-based applications:

  • Error Handling in eMbedded Visual Basic
  • Error Handling in eMbedded Visual C++
  • Programmer's Reference for SQL Server CE Error Control Objects and Collections

See Also

Handling Errors in Smart Device Applications


Error Handling in eMbedded Visual Basic

The application you develop should explicitly trap and handle errors. If the application does not trap errors, the Microsoft® eMbedded Visual Basic® runtime captures the highest-level error and displays a generic message describing the error. By trapping and handling errors in an application, you can perform more sophisticated error recovery and display more meaningful error messages.

The 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 you use the Microsoft ActiveX® Data Objects for Windows® CE (ADOCE) Error object or the SSCEError object instead. The Visual Basic Err object does not return extended information (such as the native error number or error parameters) from Microsoft SQL Server™ 2000 Windows CE Edition (SQL Server CE). For more information, see Using the eMbedded Visual Basic Err Object.

  • ADOCE Error object

    When accessing a SQL Server CE database through ADOCE, use the ADOCE Error object to retrieve the extensive list of errors. For more information, see Using the ADOCE Error Object.

  • SQL Server CE error control objects and collections

    When accessing a SQL Server CE database through the Replication, RDA, or Engine objects, use the SQL Server CE error objects and collections to retrieve the extensive list of errors. Microsoft eMbedded Visual Basic programs reference the SQL Server error objects and collections by adding the SQL Server CE Client Agent (Ssceca20.dll) to the project references. For more information, see Using the SQL Server CE Error Control Objects and Collections with eMbedded Visual Basic.


Using the eMbedded Visual Basic Err Object

The Microsoft® eMbedded Visual Basic® Err object contains information about the most recent run-time error. The application must specify On Error Resume Next to indicate that it explicitly handles errors; and then, each time it performs an operation that might generate an error, the application must examine the Err object to determine whether any error has occurred.

For more information about the Err object, see the Visual Basic 6.0 documentation in the MSDN® Library at this Microsoft Web site.


Using the ADOCE Error Object

When a data-related error occurs, the data source provider captures information about the error and stores it in the Microsoft® ActiveX® Data Objects for Windows® CE (ADOCE) Error collection. The application must specify On Error Resume Next to indicate that it explicitly handles errors; and then, each time it performs an ADOCE operation that might generate an error, the application must examine the Error collection.

For more information about the objects, methods, and properties that are supported by the ADOCE control, see the ADOCE documentation in the MSDN® Library at this Microsoft Web site.

Examples

The following example shows using the ADOCE Error object to display 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
  strErr = ""
  Err.Number = 0 ' This resets the VB error
End Sub


Using the SQL Server CE Error Control Objects and Collections with eMbedded Visual Basic

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), the Replication, RDA, and Engine object errors can be accessed directly in Microsoft eMbedded Visual Basic® by using SQL Server CE error control objects and collections.

The SSCEErrors collection contains an SSCEError object for each error that is generated. Each SSCEError object contains an SSCEParams collection. Descriptions of errors can be retrieved from SSCEParam objects in the SSCEParams collection. Unlike SQL Server, SQL Server CE returns detailed information about an error as a collection of six parameters. When building error messages, use a series of nested FOR loops to retrieve each SSCEParam object in the SSCEParams collection for each SSCEError object.

For eMbedded Visual Basic programs to use the SQL Server error objects and collections, the SQL Server CE Client Agent (Ssceca20.dll) must be added to the project references. For more information, see Programmer's Reference for SQL Server CE Error Control Objects and Collections.

Examples
A. Displaying Replication, RDA, and Engine object errors

The following Microsoft eMbedded Visual Basic example displays Replication, RDA, and Engine object errors.

' Sub routine used to display errors in a message box
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

For Each ErrRec In ErrColl
    strErr = ""
    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
    MsgBox strErr, vbOKOnly

Next ErrRec

Set ErrRec = Nothing
Set param = Nothing
End Sub
B. Handling errors in an RDA application

The following example demonstrates how to employ error handling in a remote data access (RDA) application. The example assumes that the InternetURL property has not been set; therefore, the Pull method fails and generates an RDA object error.

Dim ceRDA As SSCE.RemoteDataAccess
Set ceRDA = CreateObject("SSCE.RemoteDataAccess.2.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
C. Handling errors in a replication application

The following example demonstrates how to employ error handling in a replication application. The example 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.2.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


Error Handling in eMbedded Visual C++

Microsoft® eMbedded Visual C++® applications can receive much more detailed information from Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) than HRESULTs. How you retrieve this extended error information depends on which of the following methods the application uses to interact with SQL Server CE:

  • OLE DB error objects

    The OLE DB Provider for SQL Server CE returns a rich set of error objects that can be accessed using OLE DB error objects. The OLE DB error objects store multiple layers of errors and provide additional information beyond standard errors. For more information, see Using OLE DB Error Objects.

  • SQL Server CE error control objects and collections

    The Replication, RDA, and Engine objects expose error collections and parameters that can be accessed through eMbedded Visual C++. Microsoft eMbedded Visual C++ programs reference the SQL Server error objects and collections by adding Ca_mergex20.h and Ca_mergex20.lib to the project references and by referencing these files using the include directive. For more information, see Using the SQL Server CE Error Control Objects and Collections with eMbedded Visual C++.


Using OLE DB Error Objects

When errors occur during the execution of a Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE)-based application, the OLE DB Provider for SQL Server CE returns and stores an array of error objects. These objects can then be accessed using OLE DB in the customary manner. The OLE DB Provider for SQL Server CE returns errors for each interface supported by the provider. For more information, see Implemented OLE DB Interfaces. For information about the general mechanism for an OLE DB client to retrieve error information, see the Microsoft OLE DB section of the Microsoft Data Access Components (MDAC) SDK documentation in the MSDN® Library at this Microsoft Web site.

Examples

The following example shows how to retrieve the provider-specific error numbers when you use the OLE DB Provider for SQL Server CE.

/* 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 whether the interface even supports errors. If it does,
// 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 the description of the error.
        hr = pIErrorInfoRecord->GetDescription(&bstrDescriptionOfError);

        // Get the source of the error.
        hr = pIErrorInfoRecord->GetSource(&bstrSourceOfError);

        if(NULL != pIErrorInfoRecord)
        {
            pIErrorInfoRecord->Release(); // Release unneeded interface
        }

        // Print the native error number for this error. Error numbers are
        // are documented in the Troubleshooting section.
        wprintf(L"Native Error Code: %l\n", ErrorInfo.dwMinor);
    }

    pIErrorRecords->Release();  // Release unneeded interface.
    }
}


Using the SQL Server CE Error Control Objects and Collections with eMbedded Visual C++

In Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), Replication, RDA, and Engine object errors can be accessed directly in Microsoft eMbedded Visual C++® by using the SQL Server CE error control objects and collections.

The SSCEErrors collection contains an SSCEError object for each error generated. Each SSCEError object contains an SSCEParams collection. The descriptions of errors can be retrieved from SSCEParam objects in the SSCEParams collection. Unlike SQL Server, SQL Server CE returns detailed information about an error as a collection of six parameters. When building error messages, use a series of nested FOR loops to retrieve each SSCEParam object in the SSCEParams collection for each SSCEError object.

Microsoft eMbedded Visual C++ programs reference the SQL Server error objects and collections by adding Ca_mergex20.h and Ca_mergex20.lib to the project references and by referencing these files using the include directive. For more information, see Programmer's Reference for SQL Server CE Error Control Objects and Collections.

Examples

The following example shows how to display Replication, RDA, and Engine object errors using eMbedded VC++.

// Error handling example in eMbedded VC++
#include     "ca_mergex20.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 the variants.
VariantInit(&var);
VariantInit(&varParam);

// Get the 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 in a single message box.
// If there are too many errors, they may not all display properly.
// If so, you should perform logic based on the number of errors.
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 the 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 the variant.
        VariantClear(&varParam);

        // Release the parameter object.
        pISSCEParam->Release();
        pISSCEParam = NULL;
        }
    cbBuf = swprintf(pwszBuffPos, L"\r\n");
    pwszBuffPos += cbBuf;

    }

// Display the 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;
    }

// The Errors object is released in calling routine.
if (!fSuccess)
    {
    MessageBox(NULL, L"Error while processing errors!",L"ShowErrors", MB_OK);
    }
return;
}


Programmer's Reference for SQL Server CE Error Control Objects and Collections

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) provides error control objects and collections for handling Replication, RDA, and Engine object errors in Microsoft eMbedded Visual Tools-based applications. The topics in this section describe the error objects and collections and their properties.

This section is divided into two parts:

  • SQL Server CE Error Control Objects and Collections

    Describes the SQL Server CE error objects and collections.

  • SQL Server CE Error Control Objects and Collections Properties

    Describes the properties of the SQL Server CE error objects and collections that are used to retrieve error codes and error message information.

See Also

Error Handling in eMbedded Visual Basic

Error Handling in eMbedded Visual C++


SQL Server CE Error Control Objects and Collections

In the Microsoft® eMbedded Visual Tools development environment, applications use the following Microsoft ActiveX® error control objects and collections in Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) to retrieve error information about Replication, RDA, and Engine object errors.

Object/Collection | Description
SSCEError Object | Defines a Replication, RDA or Engine object error.
SSCEErrors Collection | Contains the error objects for Replication, RDA, and Engine object errors.
SSCEParam Object | Provides the descriptive element of an error.
SSCEParams Collection | Contains the descriptive elements for errors.


SSCEError Object

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) uses SSCEError objects to report Replication, RDA, or Engine object errors. SQL Server CE creates an SSCEErrors collection containing one or more SSCEError objects whenever a Replication, RDA, or Engine object method call fails.

Properties

Description Property

ErrorNumber Property

NativeError Property

Source Property

Remarks

The application can enumerate through the collection and examine each SSCEError object to identify the error.

Error objects and collections are retained until the next Replication, RDA, or Engine object method is called.

See Also

SSCEErrors Collection

Using Remote Data Access (RDA)

Using Replication


SSCEErrors Collection

The SSCEErrors collection is created when a Replication, RDA, or Engine object method call fails. The SSCEErrors collection contains a set of SSCEError objects that can be used to retrieve error information.

Properties

Count Property

Remarks

Error objects and collections are retained until the next Replication, RDA, or Engine object method is called.

See Also

SSCEError Object

Using Remote Data Access (RDA)

Using Replication


SSCEParam Object

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) uses SSCEParam objects to report detailed error parameters. SSCEParam objects are members of the SSCEParams collection.

Properties

Param Property

Remarks

SQL Server CE creates an SSCEParams collection containing six SSCEParam objects whenever a Replication, RDA, or Engine object method call fails.

Error objects and collections are retained until the next Replication, RDA, or Engine object method is called.

See Also

SSCEParams Collection

Using Remote Data Access (RDA)

Using Replication


SSCEParams Collection

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) uses the SSCEParams collection to report detailed information regarding a specific error.

Properties

Count Property

Remarks

Each SSCEError object contains the SSCEParams collection that in turn contains a set of six SSCEParam objects.

Error objects and collections are retained until the next Replication, RDA, or Engine object method is called.

See Also

SSCEError Object

Using Remote Data Access (RDA)

Using Replication


SQL Server CE Error Control Objects and Collections Properties

The following topics describe the properties for the error control objects and collections provided by Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE):

  • Count Property
  • Description Property
  • ErrorNumber Property
  • NativeError Property
  • Param Property
  • Source Property


Count Property

The Count property specifies the number of objects in the collection.

Applies To

SSCEErrors Collection

SSCEParams Collection

Syntax
object.Count [=value]
Part | Description
object | SSCEErrors collection
value | Number of SSCEError objects in the collection
Data Type

long

Modifiable

Read-only

Prototype eVC++
HRESULT get_Count(long *plCount);

See Also

SQL Server CE Error Control Objects and Collections Properties


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
Data Type

string

Modifiable

Read-only

Prototype eVC++
HRESULT get_Description(BSTR *pVal);
Remarks

The Description property provides a descriptive error message that is suitable for displaying to the user. Error messages can originate from Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) from replication, remote data access (RDA), OLE DB, or the query processor; and from Microsoft SQL Server. Only errors originating from SQL Server 2000 currently generate error strings.

See Also

SQL Server CE Error Control Objects and Collections Properties


ErrorNumber Property

The ErrorNumber property provides the OLE HRESULT error number reported by the error source.

Applies To

SSCEError Object

Syntax
object.ErrorNumber [=value]
Part | Description
object | SSCEError object
value | OLE HRESULT error number
Data Type

long

Modifiable

Read-only

Prototype eVC++
HRESULT get_ErrorNumber(long *pVal);
Remarks

SQL Server CE Books Online does not document specific HRESULTS returned by the ErrorNumber property because these are nonnative errors.

To find information about HRESULT values, see Oledberr.h in Microsoft® ActiveX® Data Objects for Windows® CE 3.1 (ADOCE), and Winerror.h and Wininet.h that are included in Microsoft eMbedded Visual Tools. For more information about HRESULT values, search the MSDN® Library at this Microsoft Web site or the Microsoft Knowledge Base at this Microsoft Web site.

See Also

SQL Server CE Error Control Objects and Collections Properties


NativeError Property

The NativeError property reports native error numbers reported by the error source.

Applies To

SSCEError Object

Syntax
object.NativeError [=value]
Part | Description
object | SSCEError object
value | Native error number
Data Type

long

Modifiable

Read-only

Prototype eVC++
HRESULT get_NativeError(long *pVal);
Remarks

When the NativeError property of the SSCEError object returns a value of 0, it means that a nonnative SQL Server CE Engine error has occurred. The OLE HRESULT code for this nonnative error can be obtained from the ErrorNumber property. For more information, see SQL Server CE Errors.

See Also

ErrorNumber Property

SQL Server CE Error Control Objects and Collections Properties


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
Data Type

Variant

Modifiable

Read-only

Prototype eVC++
HRESULT get_Param(BSTR *pVal);
Remarks

There are always six SSCEParam objects in an SSCEParams collection. The first three are integers and the last three are strings. Some properties 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 Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) from replication, remote data access (RDA), OLE DB, or the query processor; and from Microsoft SQL Server. Only errors originating from SQL Server 2000 currently generate error strings.

Note Although parameters might exist for an error, not all occurrences of the error will return parameters.

See Also

SQL Server CE Error Control Objects and Collections Properties


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
Data Type

string

Modifiable

Read-only

Prototype eVC++
HRESULT get_Source(BSTR *pVal);
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.

See Also

SQL Server CE Error Control Objects and Collections Properties

SSCEError Object


Handling Errors in Smart Device Applications

For smart device projects in the Microsoft® Visual Studio® .NET development environment, the .NET Compact Framework Data Provider for SQL Server CE supports rich error handling for errors generated by the Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) database engine, and the Microsoft ActiveX® controls for the SQL Server CE Replication object and the SQL Server CE Remote Data Access object (RDA). When an engine error occurs, an exception object is created that contains one or more error objects. When you use the .NET Compact Framework Data Provider, the exception object also contains an error collection object, which in turn contains one or more error objects.

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

For smart device projects that access Microsoft SQL Server 2000 using the .NET Framework Data Provider for SQL Server, rich error handling is provided by the SqlException object.

Properties of these error objects and collections can be accessed to obtain error code and error message text information.

Note Depending on the severity of the error, the connection to the database might be closed. In this case, recovering from such an error requires reopening the connection to the database.

The following topics provide information about handling errors in smart device applications by using the .NET Compact Framework Data Provider for SQL Server CE:

  • Error Handling in C#
  • Error Handling in Visual Basic .NET

For more information about the error objects supported by the .NET Framework data providers, see Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections

See Also

Handling Errors in eMbedded Visual Tools Applications


Error Handling in C#

This topic provides a C# example that shows how to use the error objects provided by the Microsoft® .NET Compact Framework Data Provider for SQL Server CE. These objects can be used to capture and display engine errors that occur in Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) when executing Replication, RDA, or Engine object methods.

When an engine error occurs, a SqlCeException object is created. This exception object contains the SqlCeErrorCollection object, which in turn contains a collection of SqlCeError objects, one for each error in the exception. The SqlCeErrorCollection object can be accessed directly using the SqlCeException.Errors property. Each SqlCeError object contains an array of error parameters that provide detailed information about the error. Unlike SQL Server, SQL Server CE returns detailed information about an error as a collection of parameters. When building error messages, you should use a series of nested FOR loops to retrieve each parameter in each SqlCeError object in the collection.

For more information, see Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections.

Examples

In the following example, the ShowSqlException method catches a SQL Server CE engine exception error. This SqlCeException object is passed to the ShowErrors method, which displays each of the SSCEError objects in the SqlCeErrorCollection object. This method loops through all of the error parameters for each error.

// Reference the .NET Compact Framework Data Provider for SQL Server CE.
using System.Data.SqlServerCe;

// Begin the method to generate a SQL Server CE engine exception.
public void ShowSqlCeException()
{
    string mySelectQuery = "SELECT column1 FROM table1";
    SqlCeConnection myConnection = new SqlCeConnection("Data Source=nonExistSource.sdf;");
    SqlCeCommand myCommand = new SqlCeCommand(mySelectQuery,myConnection);

    try
    {
        myCommand.Connection.Open();
    }

    // Catch the exception as e and pass it to the ShowErrors routine.
    catch (SqlCeException e)
    {
        ShowErrors(e);
    }

}

// Error handling routine that generates an error message
public static void ShowErrors(SqlCeException e)
{
    SqlCeErrorCollection errorCollection = e.Errors;

    StringBuilder bld = new StringBuilder();
    Exception inner = e.InnerException;

    if (null != inner)
    {
        MessageBox.Show("Inner Exception: " + inner.ToString());
    }
    // Enumerate the errors to a message box.
    foreach (SqlCeError err in errorCollection)
    {
        bld.Append("\n Error Code: " + err.HResult.ToString("X"));
        bld.Append("\n Message   : " + err.Message);
        bld.Append("\n Minor Err.: " + err.NativeError);
        bld.Append("\n Source    : " + err.Source);

        // Enumerate each numeric parameter for the error.
        foreach (int numPar in err.NumericErrorParameters)
        {
            if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
        }

        // Enumerate each string parameter for the error.
        foreach (string errPar in err.ErrorParameters)
        {
            if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
        }

        MessageBox.Show(bld.ToString());
        bld.Remove(0, bld.Length);
    }
}


Error Handling in Visual Basic .NET

This topic provides a Microsoft® Visual Basic® example that shows how to use the error objects provided by the Microsoft .NET Compact Framework Data Provider for SQL Server CE. These objects can be used to capture and display engine errors that occur in Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) executing Replication, RDA or Engine object methods.

When an engine error occurs, a SqlCeException object is created. This exception object contains the SqlCeErrorCollection object, which in turn contains a collection of SqlCeError objects, one for each error in the exception. The SqlCeErrorCollection object can be accessed directly using the SqlCeException.Errors property. Each SqlCeError object contains an array of error parameters that provide detailed information about the error. Unlike SQL Server, SQL Server CE returns detailed information about an error as a collection of parameters. When building error messages, you should use a series of nested FOR loops to retrieve each parameter in each SqlCeError object in the collection.

For more information, see Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections.

Examples

In the following example, the ShowSqlException method catches a SQL Server CE engine exception error. This SqlCeException object is passed to the ShowErrors method, which displays each of the SSCEError objects in the SqlCeErrorCollection object. This method loops through all of the error parameters for each error.

' Reference the  .NET Compact Framework Data Provider for SQL Server CE by using the Imports directive.
Imports System.Data.SqlServerCe

' Begin the method to generate a SQL Server CE engine exception.
Public Sub ShowSqlCeException()
    Dim mySelectQuery As String = "SELECT column1 FROM table1"
    Dim myConnection As New SqlCeConnection("Data Source=nonExistSource.sdf;")
    Dim myCommand As New SqlCeCommand(mySelectQuery, myConnection)

    Try
        myCommand.Connection.Open()

    ' Catch the exception as e and pass it to the ShowErrors routine.
    Catch e As SqlCeException

        ShowErrors(e)

    End Try
End Sub

' Error handling routine that generates an error message
Public Shared Sub ShowErrors(ByVal e As SqlCeException)
    Dim errorCollection As SqlCeErrorCollection = e.Errors

    Dim bld As New StringBuilder()
    Dim inner As Exception = e.InnerException

    If Not inner Is Nothing Then
        MessageBox.Show(("Inner Exception: " & inner.ToString()))
    End If

    Dim err As SqlCeError

    ' Enumerate each error to a message box.
    For Each err In errorCollection
        bld.Append((ControlChars.Cr & " Error Code: " & err.HResult.ToString("X")))
        bld.Append((ControlChars.Cr & " Message   : " & err.Message))
        bld.Append((ControlChars.Cr & " Minor Err.: " & err.NativeError))
        bld.Append((ControlChars.Cr & " Source    : " & err.Source))

        ' Retrieve the error parameter numbers for each error.
        Dim numPar As Integer
        For Each numPar In err.NumericErrorParameters
            If 0 <> numPar Then
                bld.Append((ControlChars.Cr & " Num. Par. : " & numPar))
            End If
        Next numPar

        ' Retrieve the error parameters for each error.
        Dim errPar As String
        For Each errPar In err.ErrorParameters
            If [String].Empty <> errPar Then
                bld.Append((ControlChars.Cr & " Err. Par. : " & errPar))
            End If
        Next errPar

        MessageBox.Show(bld.ToString())
        bld.Remove(0, bld.Length)
    Next err
End Sub


Programmer's Reference for the .NET Framework Data Providers Error Control Objects and Collections

Microsoft® Visual Studio® .NET supports the following data providers, each of which has its own set of objects and collections that are used when handling errors in a smart device applications:

  • .NET Compact Framework Data Provider for SQL Server CE

    This data provider belongs to the System.Data.SqlServerCe namespace, and stores Microsoft SQL Server™ 2000 Windows® CE (SQL Server CE) Replication, RDA, and Engine object error information in the following error objects and collections.

    Object/Collection | Description
    SqlCeException class | When an error occurs, an instance of the SqlCeException class is created that contains the collection of SqlCeError objects.
    SqlCeErrorCollection class | The SqlCeErrorCollection object contains one or more SqlCeError objects for a SqlCeException object. The collection can be accessed using the SqlCeException.Errors property.
    SqlCeError class | Each SqlCeError object contains an array of error parameters that provide detailed information about the error.

    The .NET Compact Framework Data Provider for SQL Server CE is included in the Microsoft .NET Compact Framework that ships with Visual Studio .NET. For more information, see .NET Compact Framework Data Providers.

  • .NET Framework Data Provider for SQL Server

    This data provider belongs to the System.Data.SqlClient namespace and stores exception errors in an instance of the SqlException class. This data provider can be used only when you remotely access a database in SQL Server using a tabular data stream (TDS) connection. When you use this provider, errors can be accessed as with any other SQL Server managed client application. For more information, see .NET Framework Data Provider for SQL Server in the Visual Studio .NET documentation.


Deploying Applications

Deploying a Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) application can require installing parts of the application on one or more of the following systems:

  • Microsoft Internet Information Services (IIS) systems
  • Microsoft ActiveSync® systems
  • Microsoft Windows CE-based devices
IIS Deployment

To use SQL Server CE replication or remote data access (RDA), each computer running IIS must be configured by installing the version of the SQL Server CE Server Tools appropriate to the version of Microsoft SQL Server you are running. For more information, see Installing SQL Server CE on an IIS System and Configuring Connectivity Support in IIS.

Note The SQL Server CE Server Tools installer that ships with SQL Server CE contains components compatible with Microsoft SQL Server 2000 Service Pack 1 and Service Pack 2. SQL Server CE Server Tools that are compatible with later SQL Server service packs are available at this Microsoft Web site.

ActiveSync Deployment

Microsoft Windows Powered Pocket PC 2002 can use ActiveSync 3.5 or later to synchronize SQL Server CE over a serial, infrared (IR), or USB connection. When you use Pocket PC 2000 or Handheld PC 2000 devices, you must use SQL Server CE Relay in conjunction with IIS to synchronize over these connections. If you require SQL Server CE Relay for SQL Server CE connectivity, SQL Server CE Relay must be deployed to each desktop system through which you intend to synchronize. For more information, see Using SQL Server CE Relay.

Windows CE Deployment

The two aspects to Windows CE deployment are:

  • Application deployment during development
  • Final application deployment

The following topics address these aspects of deployment and describe the processes for deploying a Windows CE-based application.

Topic | Description
Deployment Considerations | Provides information about deploying Windows CE-based applications.
Deploying Applications from Visual Studio .NET | Describes the process for deploying a Microsoft Visual Studio® .NET application.
Deploying Applications from eMbedded Visual Tools | Describes the process for deploying a Microsoft eMbedded Visual Tools application.
Deploying Applications Manually | Describes how to manually deploy SQL Server CE on a Windows CE-based device.
Deploying Applications with Platform Builder | Describes the process for deploying an application using Microsoft Platform Builder.


Deployment Considerations

The following topics describe the primary considerations for deploying Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) applications:

  • Upgrading from Earlier Versions of SQL Server CE
  • Prebuilding a SQL Server CE Database
  • Creating Secure Connections from Windows CE-based Devices
  • Ensuring Proper ANSI to Unicode Conversions


Prebuilding a SQL Server CE Database

If you have a large quantity of data in a Microsoft® SQL Server™ database that provides data for a Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) database, it can be expensive for every Windows CE-based device to download all of the data using a remote data access (RDA) or replication synchronization process. You can prebuild a copy of the SQL Server CE database and download it to each device together with the application.

To prebuild and download a copy of a SQL Server CE database

  1. Set up one Windows CE-based device with the application.
  2. Connect the application to the SQL Server database using RDA or replication. Create the SQL Server CE .sdf file on the device and synchronize the SQL Server CE database with the SQL Server database.
  3. Stop the application and use Microsoft ActiveSync® to connect to the device. Use the ActiveSync Explorer function to copy the .sdf file from the Windows CE-based device to the development environment, and then store the file with the rest of the application.

The .sdf file can now be copied to other devices using ActiveSync Explorer or installed from the application .cab file.

Note Because SQL Server CE databases that are involved in replication are uniquely identified by a Subscriber ID, SQL Server CE assigns a new Subscriber ID upon the next synchronization if the databases is moved or copied to a new location.


Creating Secure Connections from Windows CE-based Devices

To create a secure connection from a Microsoft® Windows® CE-based device to a computer running Microsoft Internet Information Services (IIS), ensure that:

  • The appropriate certificate is installed on the computer running IIS.
  • The Certificate Authority that issued the certificate is included in the Windows CE Certificate Authority database.

If you issued an IIS server certificate using your own stand-alone Certificate Authority, your root certificate is not present in the Windows CE Certificate Authority database. As a result, Windows CE does not trust your IIS server certificate. If you install such a server certificate in IIS and attempt to use Secure Sockets Layer (SSL) encryption, Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE) replication or remote data access (RDA) fails with the error: "ERROR_INTERNET_INVALID_CA (12045)".

To use server certificates that you issue yourself, you must either certify your stand-alone Certificate Authority through one of the trusted certificate authorities or add the root certificate of your stand-alone certificate authority to the Windows CE Certificate Authority database.

For more information about encryption and certificates, see Configuring SSL Encryption.


Ensuring Proper ANSI to Unicode Conversions

If the instance of Microsoft® SQL Server™ you are connecting to contains ANSI data, the data is converted to Unicode before being stored in the database in Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE). Depending on the code page of the computer running SQL Server and the computer running IIS, conversion errors may occur. The following information helps to ensure that the data is converted correctly.

ANSI to Unicode Conversions in the SQL Server CE Server Agent

The SQL Server CE Server Agent running on the computer running IIS converts ANSI data in SQL Server to or from Unicode for SQL Server CE. To ensure that it uses the correct translation, the SQL Server CE Server Agent determines which code page the ANSI data is stored in before performing ANSI to Unicode conversions. The following information is taken into consideration:

  • If no other settings are available, the ANSI code page of the computer running IIS and the SQL Server CE Server Agent is used.
  • If you are using an instance of SQL Server 2000, the SQL Server CE Server Agent uses the code page of the computer on which SQL Server is running. When each instance of SQL Server is set up to correctly identify the ANSI data that is being stored, the correct translation is selected automatically for each connection.

If the translation does not give the correct value for the data that is being stored, you can override the code page by setting the following registry key to a specific code page.

To create the registry key to override the code page

  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 the IIS virtual directory for SQL Server CE. For example, if the Sscesa20.dll is located in the folder C:\Inetpub\Sqlce\NorthWind, you must name the registry value C:\Inetpub\Sqlce\NorthWind\OVERRIDE_SERVER_CP. The data value of the DWORD key must be a value of the code page. For example, the following registry key value is for the English code page:

    HKLM\Software\Microsoft\MSSQLSERVERCE\Transport
    C:\Inetpub\Sqlce\NorthWind\OVERRIDE_SERVER_CP 1252

  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 SQL Server CE Server Agent (Sscesa20.dll) is first loaded by IIS. To restart IIS, in Internet Service Manager, right-click the server name and select Restart IIS.

This registry setting affects all of the ANSI to Unicode and Unicode to ANSI translations that the SQL Server CE Server Agent makes for any SQL Server connection; therefore, do not use this registry key unless you know that all of your instances of SQL Server are storing ANSI data with the same code page.

In all cases, after the correct code page translation is selected, the SQL Server CE Server Agent requires that the computer running IIS include the Microsoft Windows language support for that code page.

ANSI to Unicode Conversions Outside the SQL Server CE Server Agent

If the SQL Server CE Server Agent has been correctly configured but the ANSI data is still not being handled properly, you may need to make additional adjustments. To ensure that the correct settings have been made to allow the ANSI data to reach the SQL Server CE Server Agent, see the documentation for the provider.

For example, SQL Server defines the following property for configuring OEM/ANSI character translation in the OLE DB Provider for SQL Server as SSPROP_INIT_AUTOTRANSLATE.

When this property is VARIANT_TRUE, SQL Server data that is stored as a char, varchar, or text data type and sent to a client DBTYPE_STR variable is converted from character to Unicode by using the ANSI code page (ACP) on the computer running SQL Server, and then converted from Unicode to character by using the ACP on the client.

If the data is known to be of a different code page than that of either the computer running SQL Server or the computer running IIS, this property should be set to VARIANT_FALSE to force no translation to be performed on the data before reaching the SQL Server CE Server Agent.

A remote data access (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 SQL Server CE Server Agent.


Deploying Applications from Visual Studio .NET

This topic describes deployment during development and final application deployment in the Microsoft® Visual Studio® .NET development environment.

Note This feature has been designed to be used in conjunction with a prerelease version of an anticipated successor to Microsoft Visual Studio .NET. Check the documentation accompanying the commercially released version for any updates.

Deployment During Development

To include Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) in a project, add a reference to the System.Data.SqlServerCE assembly. For more information, see Installing SQL Server CE with Visual Studio .NET .

When this reference is added, two .cab files are deployed to the Windows CE-based device each time the application is compiled:

  • Sqlce.dev.platform.processor.cab

    This .cab file should be deployed only during application development. This .cab file contains Isqlw20.exe (SQL Server CE Query Analyzer), which installs in \Program Files\SQLCE 2.0; and two error string files: Ssceerror20en.dll and Msdaeren.dll, both of which install in \Program Files\SQLCE 2.0.

  • Sqlce.platform.processor.cab

    This .cab file includes all files needed for SQL Server CE: Ssce20.dll, Ssceca20.dll install in \Program Files\SQLCE 2.0, and Sscemw20.dll installs in \Windows.

Final Application Deployment

After you complete the application, create a .cab file for the application: On the Build menu, select Build CAB File. This .cab file does not include SQL Server CE or the .NET Compact Framework. To fully deploy the application, you must copy and extract the application .cab file as well as the SQL Server CE and .NET Compact Framework .cab files, which are included by default in \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Windows CE\platform\processor folders.


Deploying Applications from eMbedded Visual Tools

This topic describes deployment during development and final application deployment for applications developed using Microsoft® eMbedded Visual Basic® and Microsoft eMbedded Visual C++®.

Deployment During Development

During development, different deployment options are available depending upon the programming language you are using.

Using eMbedded Visual Basic

The Microsoft eMbedded Visual Basic development environment automates many of the debugging processes that you must use to develop a new application. Part of this process includes downloading the application to a Microsoft Windows® CE-based device on which the application can be run and debugged. The development environment uses Microsoft ActiveSync® on the development computer to download the files to the Windows CE-based device.

Microsoft eMbedded Visual Basic automatically monitors the executable files that are included in the application and the DLLs the application uses. During the download process, eMbedded Visual Basic downloads the latest version of these components: Ssce20.dll and Ssceca20.dll.

Note SQL Server CE Query Analyzer (Isqlw20.exe) and a DLL that provides error descriptions for use during development (Ssceerror20en.dll) must be manually copied to the Windows CE-based device.

To include SQL Server CE in your project, on the Project menu, click References, Microsoft CE SQL Server Control 2.0, and then Microsoft CE ADO Control 3.1. If you are using Microsoft ActiveX® Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE), you must also include Microsoft CE ADO Ext. 3.1 for DDL.

Using eMbedded Visual C++

Although eMbedded Visual C++ can deploy the application to the device, it cannot download SQL Server CE components. To install SQL Server CE components, there are two options:

  • Create an eMbedded Visual Basic application, as described previously, that references SQL Server CE. (Create a blank application because it is used only to install SQL Server CE.)
  • Manually install SQL Server CE components. For more information, see "Manual Installation Process" in Installing SQL Server CE on a Device Using eMbedded Visual Tools.
Final Application Deployment

Windows CE-based applications are typically distributed as .cab files. There are two ways to create .cab files for the eMbedded Visual Tools application:

  • If you have an eMbedded Visual Basic project, use the eMbedded Visual Basic Application Install Wizard. This tool creates an installation package for the application that includes Windows CE .cab files. It also leaves the .inf file that is used to create the .cab files in the directory to which the application is deployed. You can modify this .inf file if additional customization is needed. For more information, see "Using the Application Install Wizard" in the eMbedded Visual Basic documentation.
  • Create custom cab files using the CAB Wizard (Cabwiz.exe). For information about using the CAB Wizard, see "Installing Applications" in the Windows CE documentation in the MSDN® Library at this Microsoft Web site. For information about the files required to create a SQL Server CE .cab file see "Manual Installation Process" in Installing SQL Server CE on a Device Using eMbedded Visual Tools.


Deploying Applications Manually

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) and applications developed in the Microsoft eMbedded Visual Tools or Microsoft Visual Studio® .NET development environments can also be installed on a Windows CE-based device by manually copying and registering all the required files. For more information, see "Manual Installation Process" in Installing SQL Server CE on a Device Using eMbedded Visual Tools and Installing SQL Server CE with Visual Studio .NET.


Deploying Applications with Platform Builder

Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server SE) supports Microsoft Platform Builder for Microsoft Windows CE .NET version 4.1. Platform Builder is used to create a custom Windows CE operating system for use in a custom Windows CE-based device, such as an embedded controller for a piece of equipment.

You can incorporate SQL Server CE components in the new operating system by instructing Platform Builder to include SQL Server CE when it builds an operating system. If you included SQL Server CE in the new operating system, Platform Builder automatically configures the device for SQL Server CE, after which you can start building SQL Server CE applications for the device. For more information about deploying an application, see Deploying Applications from eMbedded Visual Tools or Deploying Applications from Visual Studio .NET.

See Also

Installing SQL Server CE with Platform Builder


Sample Applications

This section describes the sample applications that are included with Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Sample application | Description
IBuySpy Delivery .NET Framework Application | Uses Microsoft® Visual C#™ .NET and Microsoft Visual Basic® .NET to show best practices for writing replication and remote data access (RDA) applications in the .NET Framework.
Northwind Remote Salesforce Replication Sample Application | Uses Microsoft eMbedded Visual Tools to demonstrate how SQL Server CE can be combined with SQL Server 2000 merge replication to form a mobile sales route application.
Northwind Remote Salesforce RDA Sample Application | Uses Microsoft eMbedded Visual Tools to demonstrate how SQL Server CE and RDA can be combined with SQL Server 2000 or SQL Server version 7.0 to form a mobile sales route application.
Additional eMbedded Visual Tools Sample Applications | Uses Microsoft eMbedded Visual Tools to show additional uses of replication, RDA, and OLE DB.


IBuySpy Delivery .NET Framework Application

IBuySpy Delivery is a sample application developed in both Microsoft® Visual C#™ .NET and Microsoft Visual Basic® .NET using Microsoft Visual Studio® .NET. The application is robust, based on real-world scenarios, and demonstrates best practices for developing applications for Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) in the Microsoft .NET Framework and .NET Compact Framework. IBuySpy Delivery uses merge replication and remote data access (RDA) of SQL Server 2000, and highlights the new data access features of SQL Server CE: upload only and index pull capabilities, parameterized queries, and the ADO.NET framework for compact devices.

IBuySpy Delivery builds on the foundation provided by IBuySpy. IBuySpy, a fictitious producer of consumer espionage products, is showcased in the IBuySpy ASP.NET-based application at this Microsoft Web site. IBuySpy Delivery extends the IBuySpy business model of selling products over the Internet to delivering these products. The IBuySpy Delivery application assists delivery drivers in fulfilling their orders at remote sites. When you install IBuySpy Delivery, you install modified versions of the IBuySpy database and Web application, and the code specific to the IBuySpy Delivery application.

The following topics describe the setup procedure, design, and sample code for the IBuySpy Delivery sample application:

  • Setup Instructions for the IBuySpy Delivery Application
  • IBuySpy Delivery Application Design
  • IBuySpy Delivery Sample Code


Setup Instructions for the IBuySpy Delivery Application

Before you can run and examine the code for the IBuySpy Delivery sample application, several components and tools must be installed.

Important Existing installations of IBuySpy will be overwritten. IBuySpy Delivery only supports a single-server configuration; therefore, all components and tools must be installed on a single computer.

Following the installation and configuration of the items listed in the following prerequisites section, you can view the application on any device running Microsoft® Windows® Powered Pocket PC 2002 or by using a software emulator. The Pocket PC 2002 emulator comes with the installation of Microsoft Visual Studio® .NET. The emulator simulates the screens and behavior of a Pocket PC 2002-based device.

Important Sample applications should not be connected to or used with your production Microsoft SQL Server™ database without the permission of the system administrator. In fact, system administrator privileges are required for parts of this application installation.

Prerequisites for Viewing the IBuySpy Delivery Application

In addition to being familiar with Microsoft Visual Basic® .NET and Visual C#™, to use IBuySpy Delivery you must install or verify the installation of the following items on the development system:

  • Microsoft Visual Studio .NET
  • Microsoft Visual Studio .NET Compact Framework
  • Microsoft .NET Framework version v1.0.3705
  • Microsoft SQL Server 2000 with Service Pack 1 or higher
  • Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE). SQL Server CE is included with the .NET Compact Framework
  • Microsoft Internet Information Services (IIS) 4.0 or later
  • SQL Server CE Server Tools

For more information on installation, see Installing SQL Server CE.

Installing the IBuySpy Delivery Application

After the prerequisite components and tools are installed, you can begin the installation process for IBuySpy Delivery. After the installation is complete, you can begin using the IBuySpyDelivery application on the Windows CE-based device and browsing the IBuySpy Web site. The IBuySpy application is located on the device in \Program Files\IBuySpyDelivery\Client. The IBuySpy Web site is located on the computer running IIS at http://localhost/StoreCSVS/Default.aspx. (You can also use the computer name or IP address instead of localhost.)

There are two versions of the IBuySpy application: a Visual C# version and a Visual Basic .NET version. The Visual C# version of the Visual Studio .NET project for the device application is located in \Program Files\IBuySpyDelivery\Client\Cs; the Visual Basic .NET version is located in \Program Files\IBuySpyDelivery\Client\VB.

To install the IBuySpy Delivery sample application

  1. Run IBuySpyDelivery.exe. The default location of the file is \Program Files\Microsoft Visual Studio .NET 2003\CompactFrameworkSDK\v1.0.5000\Samples\PocketPC\VB\IBuySpyDelivery. IBuySpyDelivery.exe is a self-extracting executable that creates a directory tree at the default location of \Program Files\IBuySpyDelivery and copies into this tree the modified IBuySpy Store Web site source code and Visual Studio .NET project, and the IBuySpy Delivery source code and Visual Studio .NET project.
  2. After copying the files, IBuySpyDelivery.exe launches a configuration file (Install.hta) that starts Internet Explorer. Internet Explorer displays Web pages that configure the computer running IBuySpy Delivery. To manually start Install.hta (to reconfigure the system after installation, for example), navigate to the directory in which IBuySpyDelivery is installed and then double-click Install.bat.

    Note If the configuration file fails to open Internet Explorer, you might need to restart the computer.

  3. Follow the series of Web pages to complete the installation.

    To manually configure the system, on the configuration screen, select Skip (Configure Manually).

Configuring Manually

When you configure manually, you perform the following tasks that the installer carries out:

  • Add a virtual directory (StoreCSVS) in IIS for the Web site address.
  • Use a Transact-SQL script (StoreDB.sql) to install a new database in SQL Server with the updated IBuySpy Delivery schema. The Transact-SQL script also populates the database with sample data and adds settings necessary for replication to run.

    Note To install and configure the database, the installer (Install.hta) assumes the user has administrator access to the database server.

  • Set the ASP.NET user (created during the .NET Framework install) as an owner of the Store database.
  • Configure and start the SQL Server CE Server Agent (Sscesa20.dll) and the Replication Provider (Sscerp20.dll).
  • Configure the Distributor and the Publisher, and create a snapshot folder share and a merge replication publication (StoreSample).
Uninstalling
  1. Drop the StoreSample merge replication publication.
  2. Drop the Store database from SQL Server.
  3. Delete the StoreCSVS virtual directory from IIS.
  4. Delete the directory in which the IBuySpy Delivery Web site and Visual Studio .NET project are installed. The default installation path is \Program Files\IBuySpyDelivery. You might need to unregister the SQL Server CE Server Agent (Sscesa20.dll) and the Replication Provider (Sscerp20.dll).


IBuySpy Delivery Application Design

The IBuySpy Delivery application uses Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), Microsoft SQL Server, Microsoft Internet Information Services (IIS), and the Microsoft Visual Studio® .NET Compact Framework. The application on the Windows CE-based device provides a user interface for a delivery driver to enter and edit information; the application stores and retrieves this information from a local SQL Server CE database. The device communicates with SQL Server through IIS, allowing data from the local database to be synchronized with the server database through replication and remote data access (RDA). The IBuySpy Store Web site stores and retrieves information from the SQL Server database and allows a user to enter and view information that is synchronized with the device.

IBuySpy Delivery Scenario

IBuySpy distributes its wide variety of products directly to consumers with a company-owned fleet of delivery trucks. Handheld devices are used in the delivery process to tabulate delivery quantities and are a key component of the IBuySpy supply-chain process. The handheld systems run Microsoft Powered Windows Pocket PC 2002 and SQL Server CE. When delivering an order to a customer, an IBuySpy delivery driver unloads the merchandise and then records the customer's signature in the handheld device.

The IBuySpy Delivery application can download delivery data from a server onto a device, manipulate the data while disconnected from the server, and then synchronize the changes back up to the server when a connection is restored: all common real-world scenarios. Excess inventory in the delivery truck (due to an earlier missed delivery) can also be sold during the course of a delivery. Therefore, order-processing functionality is required on the handheld application in addition to inventory tracking and customer listings. At the distribution branch or wherever else a connection is available, the driver's device communicates with the computer running SQL Server, sending completed orders, and receiving updates.

IBuySpy Delivery Web Site

The IBuySpy Store Web site is included with the IBuySpy Delivery application. This Web site is almost identical to the ASP.NET-based IBuySpy Store shopping site. The main differences are in the database schema.

You can create orders at the Web site and these orders are then transferred onto the device in keeping with the delivery driver scenario. On the Web site you can also see the results of work performed on the device, such as viewing a signature submitted for an order or products added to an order.

IBuySpy Delivery Database Schema

The IBuySpy Delivery application uses a modified version of the IBuySpy database schema to support additional features of the application. In addition to the seven tables in the IBuySpy schema: Orders, OrderDetails, Customers, Products, Categories, ShoppingCart, and Reviews; the IBuySpy Delivery schema includes the Settings table.

The IBuySpy Delivery application also modifies two tables and adds a foreign key relationship:

  • The Signature column is added to the Orders table to store bitmap images of customer signatures recorded by delivery drivers through their handheld devices. The Status column is added for tracking the delivery status of orders. This status value is used to determine whether there is excess inventory for additional point of delivery sales. For more information, see Inventory Control.
  • Six columns are added to the Customers table: Address, City, State, Zip, Phone, and DriverID (which is used to determine which customer's orders a specific driver delivers).
  • A foreign key relationship is added between the OrderDetails table and the Products table to ensure that orders are not created for products that do not exist.

The Settings table is not synchronized with the SQL Server data store. This table exists only on the handheld device and contains information necessary for the device to connect to the server.

The Reviews table is not downloaded to the device to minimize the database size on the device (also, reading and entering reviews on products is of minimal relevance at the point of delivery). The ShoppingCart table is also excluded from the device because drivers cannot create new orders on the handheld application; they can only add items to existing orders.

The remaining five tables (Customers, Order, OrderDetails, Products, and Categories) are downloaded to the device. To keep database size on the device to a minimum and to ensure that drivers see only relevant data, each delivery driver receives information specific only to his or her customers. During synchronization between the device and the server database, the information is filtered by the DriverID column in the Customers table; therefore, the records in each of the tables on the local database contain a targeted subset of the records in the entire database.

See Also

IBuySpy Delivery Sample Code


IBuySpy Delivery Application Controls

The IBuySpy Delivery application consists of five custom controls embedded into a single Windows form for a smart device application. The single Windows form and multiple control architecture are used to modularize code. All controls use the new index pull capability when synchronizing with the Microsoft® SQL Server™ data store and take advantage of parameterized queries.

The controls are:

  • Configuration Control
  • Customers Control
  • Orders Control
  • Inventory Control
  • Signature Control

The form displays the following elements on all controls:

  • DriverID field

    This field indicates which delivery driver's data partition is currently loaded on the device.

  • A standard navigation menu

    This menu allows changing between the Customer, Inventory, and Configuration controls as well as exiting the application.

  • A set of buttons specific to each control

    These buttons dictate a preferred flow within the application. The navigation menu enables navigating freely among the controls, but the preferred flow must be followed to commit changes to an order.

  • A Microsoft .NET logo

See Also

IBuySpy Delivery Sample Code


Configuration Control

The Configuration control is used to initialize the device and is always loaded first; the standard navigation bar is unavailable until the steps on the configuration control are completed. To begin (as shown in the following illustration), in the Server Name field, enter the path to an instance of Microsoft® SQL Server™ 2000.

Screen shot: Configuration control that allows you to enter the name of the server with which the SQL Server CE-based application will synchronize.

Tap Next to direct the application to connect to the specified data store. The application retrieves all the unique driver ID records from the Customers table using remote data access (RDA). The data is stored in the temporary local database DriverIDs. This database contains only driver ID records and is not used to store any other data. As shown in the following illustration, the Server Name field is unavailable. To enable the Server Name field, tap Back. This allows you to specify another instance of SQL Server to connect to if, for example, the correct driver ID is not found.

Screen shot: Configuration control that allows you to enter a driver ID. The driver ID determines which subset of data is downloaded to the device.

As shown in the following illustration, after an instance of SQL Server and a driver ID are selected, the Sync Method combo box displays the two available synchronization methods: Replication and RDA. The Driver ID field is unavailable. To select a different driver ID, tap Back to enable the Driver ID field. Tap Finish to select one of the synchronization methods and to begin a communication session with the computer running SQL Server.

All data access code is contained in the class IBuySpyData, including the methods that perform replication and RDA synchronization with the SQL Server database: ReplSync() and RDASync(). The RDASync() and ReplySync() methods both perform bidirectional and upload-only data synchronization. The RDASync() method also downloads indexes along with data during bidirectional synchronization, demonstrating the new index pull capabilities. For more information about the IBuySpyData class and its methods, see IBuySpy Delivery Sample Code.

After synchronization occurs through replication or RDA, the database running on the handheld device (IBuySpyStore.sdf) contains a subset of the records in the SQL Server database. The SQL Server database is filtered on the DriverID column in the Customers table, and the device receives only those records that correspond to the driver ID specified during configuration.

The values specified during the configuration process (Server Name, Driver ID, and Sync Method) are stored in the local Settings table. When IBuySpy Delivery is first started, the application checks whether the local database exists and, if so, uses the values stored in the Settings table to provide default values for the configuration control.

Screen shot: Configuration control that allows you to select a synchronization method: either replication or RDA.

After synchronization is complete, as shown in the following illustration, four buttons are available: Reset, Change Driver, Quick Sync, and Full Sync. The Sync Method field is unavailable. The standard navigation buttons are active (except for Configuration because this control is currently loaded) and the value for the driver ID is displayed., Tapping Full Sync and Quick Sync result in different actions, depending on whether replication or RDA is being used. Before quick synchronization can be used for the first time, you must first perform a full synchronization.

Synchronization method | Quick synchronization action | Full synchronization action
RDA | Push | Push, drop, pull
Replication | Upload-only | Bidirectional sync

Screen shot: Configuration control that allows you to reset the application, select a different driver ID, and perform a full or quick synchronization.

To change the value for the driver ID, tap Change Driver. This results in the download of a new subset of data from the SQL Server database. Tapping Change Driver opens a message box with the warning: "You are about to change the Driver ID. Selecting a new Driver ID will cause a synchronization to occur." The Driver ID combo box is enabled and any change causes the subscription at the SQL Server CE database to be reinitialized after first conducting an upload-only transfer to SQL Server.

Tapping Reset also first opens a message box with the warning: "You are about to reset all configuration settings. Continuing will discard all changes." The local database in Microsoft SQL Server 2000 Windows® CE Edition (SQL Server CE) is then deleted, returning the device to an uninitialized state in which Server Name, Driver ID, and Sync Method are no longer set.

A sample copy of the IBuySpyStore.sdf SQL Server CE database is included with the IBuySpy Delivery Visual Studio® .NET project. When IBuySpyStore.sdf is copied onto the device, the configuration steps listed above do not have to be completed before you can begin using the IBuySpy Delivery application. All features of the IBuySpy Delivery application will be available except for synchronization using replication. To use replication, you must complete all configuration steps listed above.

The default location of the Visual Studio .NET project is \Program Files\IBuySpyDelivery\Client (and then \VB or \Cs, depending on which version is installed). IBuySpyStore.sdf can be copied onto the device by editing the properties of this file in Visual Studio .NET and changing the Build Action from None to Content. To change the Build Action, right click on the IBuySpyStore.sdf file in the Solutions Explorer and select Properties. In the Properties window, click on Build Action and select Content from the drop-down box.


Customers Control

The Customers control accesses the Customers database table. When the Customers control is first created, the LoadCustomer() method is executed to load the Customers database table into memory as a data set object. A similar method, LoadOrders(), is also called; it loads each customer's order information from the Orders table into a data table object. Use the Company drop-down box to navigate between customers assigned to delivery routes. Changing a company name triggers the cboCustomers_SelectedIndexChanged() method, which refreshes the screen with the appropriate address, orders, and status information for that company. The Address field is not editable. The application is designed so that a customer's address cannot be changed from the device. The Orders list box displays all records in the Orders table for the current customer. Selecting a specific order number updates the Status list box with the current status value: Pending, Delivered, or Failed. Marking an order Failed makes the products in that order available for point of delivery purchases (whereas other products are reserved for their designated customers). In the database, the Status value is stored as a small integer with 0 representing failed, 1 for delivered, and 2 for pending. Users can toggle the value of the Status field from Failed to Pending by tapping the Set Failed or Set Pending button, respectively. Orders are automatically set to a status of Delivered after a signature has been captured and saved for an order. Delivered orders cannot be modified in any way.

Screen shot: Customers control that allows you to select a company, view a company's orders, and view and edit the order status.

The names in the Company field are ordered by the value in the Status list box. Customers with orders pending are listed first, followed by delivered orders, and then customers with failed deliveries. Selecting an order in the Orders list box and tapping View Orders loads the Orders control and displays information for the selected order.

See Also

IBuySpy Delivery Sample Code


Orders Control

The Orders control accesses the Orders and Order Details database tables and displays order information for the customer. When the Orders control is first loaded, the LoadOrderDetails() method is executed to load the details for a selected order into memory as a data set object. For more information on LoadOrderDetails() and other methods, see IBuySpy Delivery Sample Code. The price displayed in Total does not change unless the customer purchases additional items at the point of delivery. The Quantity, Price, and Subtotal fields change based on which product is currently highlighted in the Products list box, which contains all the products in the current order. To navigate between different orders, select from the Order ID drop-down box. The name in the Customer field, which is dependent on the current order ID, and the date are displayed. Whereas all other fields (except for the date) are stored in the database, the values for Subtotal and Total are calculated based on quantities and prices of products.

Screen shot: Orders control that allows you to view detailed information about a customer's orders.

Tapping Add More loads the Inventory control to enable additional point-of-delivery purchases. Selecting Signature loads the Signature control so the customer can sign for the order, thus completing the delivery.


Inventory Control

The Inventory control accesses the Products and Categories database tables. By using this control, additional products can be purchased at the point of delivery. As shown in the following illustration, the Category, Product, and Quantity drop-down list boxes are populated based on available inventory. Products are considered available for purchase if they are referenced in an order record for which the Status list box is set to Failed.

The Quantity drop-down box displays the available amount of a given product. Quantity includes the total amount of a product across all the orders that have failed. The Product drop-down box shows the existing products in a given category that can be purchased; therefore, only products with quantities greater than 1 are shown. The Category drop-down box includes all categories that contain at least one product available for purchase.

Screen shot: Inventory control that allows you to add products to an existing order.

The Price field is stored in the database, but the value of Total is calculated based on the quantity and price of the selected product. In addition to the application's image-branding logo on every control, a different image, whose name is stored in the Products table, is displayed for each product. The actual product image is downloaded onto the device along with the smart device application.

Tapping Add Product adds the selected product to the order: The item is appended to the original order as a new record in the Order Details table, and then the Orders control is loaded. Tapping Cancel also loads the Orders control, but if no item is purchased, the original order record is unchanged.

If you arrive at the Inventory control by using the navigation buttons instead of first selecting a customer and an order, Add Product and Cancel are unavailable.

See Also

IBuySpy Delivery Sample Code


Signature Control

The Signature control accesses the Orders database table. After finalizing an order (verifying products and quantities are correct and making any point of delivery purchases), a customer can sign for the order using this control. The Signature field is the only input field on the control, and it operates by tracking stylus movements and then converting the recorded strokes into an integer array, which is stored in the database. This integer array is later converted into a bitmap and saved in a Web-safe image format for display on the IBuySpy Store Web site.

Because the signature cannot be changed, the integer array is converted to a bitmap file only once. The signature images are stored in a common directory (the default is \Program Files\IBuySpyDelivery\Server\StoreCSVS\StoreCSVS\images) and named using the OrderID value.

When you view the signature on the Web site (at the Orders Details page), the server first checks whether the bitmap file exists. If the file is not found, the server saves the array as a bitmap in the images\signatures directory, using the Order ID naming convention. The Order Details page dynamically creates a link to the image using the OrderID value.

Screen shot: Signature control that allows a customer to sign for an order.

Tapping Accept saves the customer's signature and then loads the Customers control. At this point, the delivery process for the customer is complete and the Status field for this order is set to Delivered. If the Status field is already marked Delivered, the existing signature is displayed, and the Accept box is unavailable. Tapping Clear erases all markings from the Signature field. Tapping Cancel loads the Orders control without saving the contents of the Signature field. An order cannot be completed without committing a signature.

See Also

IBuySpy Delivery Sample Code


IBuySpy Delivery Sample Code

The code for the IBuySpy Delivery application is available in both Microsoft® Visual C#™ and Microsoft Visual Basic® .NET at \Program Files\IBuySpyDelivery\Client\Cs and \Program Files\IBuySpyDelivery\Client\VB respectively. The samples in this topic show Visual C# code, but the Visual Basic .NET code is very similar.

The sample code focuses on two classes:

  • IBuySpyData

    This class handles all of the data access for the application, including synchronization through replication and remote data access (RDA); and includes the following methods: ReplSync(), RdaSync(), LoadCustomers(), LoadOrders(), and LoadOrderDetails().

  • Customers

    This class provides the user interface and databinding code for the Customers control, and includes the method cboCustomers_SelectedIndexChanged().

ReplSync() Method

The ReplSync() method creates a new Replication object, sets its properties, and synchronizes with the server database. Both upload-only and bidirectional replication are supported; the value of the exchangeType parameter determines which is used. With upload-only replication, changes made to the mobile database are sent to the server database without downloading any new data from the server.

Sample Code for the ReplSync() Method

private void ReplSync(SyncStatus syncStatus, ExchangeType exchangeType)
{
    SqlCeReplication repl = new SqlCeReplication();

    // Set Internet properties.
    //
    repl.InternetUrl            = this.internetUrl;
    repl.InternetLogin          = this.internetLogin;
    repl.InternetPassword       = this.internetPassword;

    // Set Publisher properties.
    //
    repl.Publisher              = this.serverName;
    repl.PublisherDatabase      = this.publisherDatabase;
    repl.Publication            = this.publication;

    // Set Publisher security properties.
    //
    repl.PublisherSecurityMode = this.publisherSecurityMode;
    repl.PublisherLogin         = this.publisherLogin;
    repl.PublisherPassword      = this.publisherPassword;

    // Set Subscriber properties.
    //
    repl.SubscriberConnectionString = this.localConnString;
    repl.Subscriber                 = this.subscriber;

    // Add dynamic filter (filter by driver IDs).
    //
    repl.HostName = this.driverID.ToString();

    // Bidirectional or upload-only?
    //
    repl.ExchangeType = exchangeType;

    try
    {
        if (SyncStatus.InitSync == syncStatus)
        {
            // Create the local database subscription.
            //
            repl.AddSubscription(AddOption.CreateDatabase);
        }

        if (SyncStatus.ReinitSync == syncStatus)
        {
            // If the driver ID has been changed, reinitialize the subscription.
            // Set the uploadBeforeReInit to true so that changes in the subscription database
            // are uploaded to the Publisher before the snapshot is applied to the subscription database.
            //
            repl.ReinitializeSubscription(true);
        }

        // Synchronize to the SQL Server 2000 database to populate the local subscription database.
        //
        repl.Synchronize();
    }
    finally
    {
        // Dispose of the Replication object.
        //
        repl.Dispose();
    }
}
RDASync() Method

Similar to replication, the RDASync() method creates a new RDA object, sets its properties, and synchronizes with the server database. Both upload-only and bidirectional RDA are supported; the value of the exchangeType parameter determines which is used. With upload-only RDA synchronization, changes made to the mobile database are sent to the server database without downloading any new information from the server. During bidirectional RDA synchronization, indexes are also downloaded along with data onto the device database demonstrating the new index pull functionality.

Sample Code for the RDASync() Method

private void RdaSync(SyncStatus syncStatus, ExchangeType exchangeType)
{
    string sqlCmd;

    SqlCeRemoteDataAccess rda = new SqlCeRemoteDataAccess();

    // Set RDA properties.
    //
    rda.LocalConnectionString = this.localConnString;
    rda.InternetUrl           = this.internetUrl;
    rda.InternetLogin         = this.internetLogin;
    rda.InternetPassword      = this.internetPassword;

    try
    {
        if (SyncStatus.InitSync == syncStatus)
        {
            // Create the local database.
            //
            SqlCeEngine en = new SqlCeEngine(this.localConnString);
            en.CreateDatabase();
        }
        else
        {
            // Push (upload) the Orders table.
            // Columns: All.
            //
            rda.Push("Orders", this.remoteConnString);

            // Push (upload) the OrderDetails table.
            // Columns: All.
            //
            rda.Push("OrderDetails", this.remoteConnString);

            // If this is upload-only (Quick Sync), then return.
            //
            if (ExchangeType.Upload == exchangeType)
            {
                return;
            }

            // Open the connection to the local database to drop the table.
            // To perform a pull (download), first drop the local database tables.
            //
            if (ConnectionState.Closed == cnIBuySpy.State)
            {
                cnIBuySpy.Open();
            }

            // Drop the Customers table if it exists.
            //
            if (DoesTableExist("Customers"))
            {
                DropTable("Customers");
            }

            // Drop the Orders table if it exists.
            //
            if (DoesTableExist("Orders"))
            {
                DropTable("Orders");
            }

            // Drop the OrderDetails table if it exists.
            //
            if (DoesTableExist("OrderDetails"))
            {
                DropTable("OrderDetails");
            }

            // Drop the Products table if it exists.
            //
            if (DoesTableExist("Products"))
            {
                DropTable("Products");
            }

            // Drop the Categories table if it exists.
            //
            if (DoesTableExist("Categories"))
            {
                DropTable("Categories");
            }

            // Close the database connection.
            //
            if (ConnectionState.Open == cnIBuySpy.State)
            {
                cnIBuySpy.Close();
            }
        }

        // Pull (download) the Customers table.
        // Columns: All.
        // Index: All. The RdaTrackOption.TrackingOffWIthIndexes parameter specifies that indexes are downloaded from the server to the device (index pull).
        // Tracking: off.
        //
        sqlCmd = String.Format(@"SELECT CustomerID, FullName, EmailAddress, Password, Address, City, Region, Zip, Phone, DriverID FROM Customers WHERE DriverID = {0}", this.driverID);
        rda.Pull("Customers", sqlCmd, this.remoteConnString, RdaTrackOption.TrackingOffWithIndexes);

        // Pull (download) the Orders table.
        // Columns: All.
        // Index: All.
        // Tracking: on.
        //
        sqlCmd = String.Format(@"SELECT OrderID, CustomerID, OrderDate, ShipDate, Status, Signature FROM Orders WHERE CustomerID IN (SELECT CustomerID FROM Customers WHERE DriverID = {0})", this.driverID);
        rda.Pull("Orders", sqlCmd, this.remoteConnString, RdaTrackOption.TrackingOnWithIndexes);

        // Pull (download) the OrderDetails table.
        // Columns: All.
        // Index: All.
        // Tracking: on.
        //
        sqlCmd = String.Format(@"SELECT OrderID, ProductID, Quantity, UnitCost FROM OrderDetails WHERE OrderID IN (SELECT OrderID FROM Orders AS O JOIN Customers AS C ON O.CustomerID = C.CustomerID WHERE C.DriverID = {0})", this.driverID);
        rda.Pull("OrderDetails", sqlCmd, this.remoteConnString, RdaTrackOption.TrackingOnWithIndexes);

        // Pull (download) the Products table.
        // Columns: All.
        // Index: All.
        // Tracking: off.
        //
        sqlCmd = @"SELECT ProductID, CategoryID, ModelNumber, ModelName, ProductImage, UnitCost, Description FROM Products";
        rda.Pull("Products", sqlCmd, this.remoteConnString, RdaTrackOption.TrackingOffWithIndexes);

        // Pull (download) the Categories table.
        // Columns: All.
        // Index: All.
        // Tracking: off.
        //
        sqlCmd = @"SELECT CategoryID, CategoryName FROM Categories";
        rda.Pull("Categories", sqlCmd, this.remoteConnString, RdaTrackOption.TrackingOffWithIndexes);
    }
    finally
    {
        // Dispose of the RemoteDataAccess object.
        //
        rda.Dispose();
    }
}
LoadCustomers(), LoadOrders(), and LoadOrderDetails() Methods

These methods load data tables with data from tables in the local database. The data table name matches the table name in the local database, for example, Customers. In addition to data sets and data tables, these methods demonstrate the use of data adapters in Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE). Parameterized queries are used in the LoadOrders() method.

Sample Code for the LoadCustomers() Method

internal DataTable LoadCustomers()
{
    if (null == this.dsCustomerOrders)
    {
        // Creates a new dataset if needed. The same dataset is also used to hold data from the Orders table.
        //
        this.dsCustomerOrders = new DataSet("CustomerOrders");
    }
    else
    {
        DataTable dtCustomers = dsCustomerOrders.Tables["Customers"];
        if (null != dtCustomers)
        {
            // Clear the Customers datatable if it already exists.
            //
            dtCustomers.Clear();
        }
    }

    if (null == this.daCustomers)
    {
        // Create a SqlCeDataAdapter to populate the Customers dataset.
        //
        this.daCustomers = new SqlCeDataAdapter(@"SELECT CustomerID, FullName, Address, City, Region, Zip, Phone " +
                                                @"FROM Customers " +
                                                @"ORDER BY FullName",
                                                cnIBuySpy);
    }

    // Populate the Customers dataset with data from the Customers table in the local database.
    //
    daCustomers.Fill(dsCustomerOrders, "Customers");

    return dsCustomerOrders.Tables["Customers"];
}

Sample Code for the LoadOrders() Method

internal DataTable LoadOrders()
{
    if (null == dsCustomerOrders)
    {
        // Creates a new dataset if needed. The same dataset is also used to hold data from the Customers table.
        //
        dsCustomerOrders = new DataSet("CustomerOrders");
    }
    else
    {
        DataTable dtOrders = dsCustomerOrders.Tables["Orders"];
        if (null != dtOrders)
        {
            // Clear the Orders datatable if it already exists.
            //
            dtOrders.Clear();
        }
    }

    if (null == daOrders)
    {
        // Create a SqlCeDataAdapter to populate the Orders dataset.
        //
        daOrders = new SqlCeDataAdapter(@"SELECT OrderID, CustomerID, Status, OrderDate, ShipDate " +
                                        @"FROM Orders " +
                                        @"ORDER BY OrderID",
                                        cnIBuySpy);

        daOrders.UpdateCommand = new SqlCeCommand();
        daOrders.UpdateCommand.Connection = cnIBuySpy;

        // Change the Status field.
        //
        daOrders.UpdateCommand.CommandText = @"UPDATE Orders SET Status = ?, ShipDate = ? WHERE (OrderID = ?)";

        // Set the UpdateCommand parameters for the Status field.
        //
        System.Data.SqlServerCe.SqlCeParameter paramStatus = new System.Data.SqlServerCe.SqlCeParameter();
        paramStatus.ParameterName = "@Status";
        paramStatus.SqlDbType     = System.Data.SqlDbType.TinyInt;
        paramStatus.Size          = 1;
        paramStatus.SourceColumn = "Status";
        daOrders.UpdateCommand.Parameters.Add(paramStatus);

        // Set the UpdateCommand parameters for the ShipDate field.
        //
        System.Data.SqlServerCe.SqlCeParameter paramShipDate = new System.Data.SqlServerCe.SqlCeParameter();
        paramShipDate.ParameterName = "@ShipDate";
        paramShipDate.SqlDbType     = System.Data.SqlDbType.DateTime;
        paramShipDate.Size          = 8;
        paramShipDate.SourceColumn = "ShipDate";
        daOrders.UpdateCommand.Parameters.Add(paramShipDate);

        // Set the UpdateCommand parameters for the OrderID field. To ensure that the search finds
      // the original record in the database, the Original data row version should be used
        // within the WHERE clause when performing a search.
        //
        System.Data.SqlServerCe.SqlCeParameter paramOrderID = new System.Data.SqlServerCe.SqlCeParameter();
        paramOrderID.ParameterName = "@Original_OrderID";
        paramOrderID.SqlDbType     = System.Data.SqlDbType.Int;
        paramOrderID.Size          = 4;
        paramOrderID.IsNullable    = false;
        paramOrderID.Precision     = 0;
        paramOrderID.Scale         = 0;
        paramOrderID.SourceColumn = "OrderID";
        paramOrderID.SourceVersion = System.Data.DataRowVersion.Original;
        daOrders.UpdateCommand.Parameters.Add(paramOrderID);
    }

    // Populate the Orders dataset with data from the Orders table in the local database.
    //
    daOrders.Fill(dsCustomerOrders, "Orders");

    return dsCustomerOrders.Tables["Orders"];
}

Sample Code for the LoadOrderDetails() Method

internal DataTable LoadOrderDetails(int orderID)
{
    if (null == dsCustomerOrders)
    {
        // Create a new dataset if needed.
        //
        dsCustomerOrders = new DataSet("CustomerOrders");
    }
    else
    {
        DataTable dtOrderDetails = dsCustomerOrders.Tables["OrderDetails"];
        if (null != dtOrderDetails)
        {
            // Clear the OrderDetails datatable if it already exists.
            //
            dtOrderDetails.Clear();
        }
    }

    if (null == daOrderDetails)
    {
        // Create a SqlCeDataAdapter to populate the OrderDetails dataset.
        //
        daOrderDetails = new SqlCeDataAdapter();

        // Create a select command to select order details information from the OrderDetails and
      // Products tables in the local database.
        //
        daOrderDetails.SelectCommand = this.cnIBuySpy.CreateCommand();
        daOrderDetails.SelectCommand.CommandText = @"SELECT O.OrderID, O.ProductID, P.ModelName, O.Quantity, O.UnitCost, O.Quantity*O.UnitCost AS Total " +
                                                    @"FROM OrderDetails AS O JOIN Products AS P " +
                                                    @"ON O.ProductID = P.ProductID " +
                                                    @"WHERE O.OrderID = ?";

        // Set the SelectCommand parameters for the OrderID field.
        //
        SqlCeParameter paramOrderID1 = new SqlCeParameter();
        paramOrderID1.ParameterName = "@Original_OrderID";
        paramOrderID1.SqlDbType     = System.Data.SqlDbType.Int;
        paramOrderID1.Size          = 4;
        paramOrderID1.SourceColumn = "OrderID";
        paramOrderID1.Value         = -1;
        paramOrderID1.SourceVersion = System.Data.DataRowVersion.Original;
        daOrderDetails.SelectCommand.Parameters.Add(paramOrderID1);

        // Create an UpdateCommand to update the OrderDetails table in the local database.
        //
        daOrderDetails.UpdateCommand = this.cnIBuySpy.CreateCommand();
        daOrderDetails.UpdateCommand.CommandText = @"UPDATE OrderDetails " +
                                                    @"SET Quantity = ?, UnitCost = ? " +
                                                    @"WHERE (OrderID = ? AND ProductID = ?)";

        // Set the UpdateCommand parameters for the Quantity field.
        //
        SqlCeParameter paramQuantity2 = new SqlCeParameter();
        paramQuantity2.ParameterName = "@Quantity";
        paramQuantity2.SqlDbType      = System.Data.SqlDbType.Int;
        paramQuantity2.Size           = 4;
        paramQuantity2.SourceColumn   = "Quantity";

        // Set the UpdateCommand parameters for the UnitCost field.
        //
        SqlCeParameter paramUnitCost2 = new SqlCeParameter();
        paramUnitCost2.ParameterName = "@UnitCost";
        paramUnitCost2.SqlDbType      = System.Data.SqlDbType.Money;
        paramUnitCost2.SourceColumn   = "UnitCost";

        // Set the UpdateCommand parameters for the OrderID field.
        //
        SqlCeParameter paramOrderID2 = new SqlCeParameter();
        paramOrderID2.ParameterName = "@Original_OrderID";
        paramOrderID2.SqlDbType      = System.Data.SqlDbType.Int;
        paramOrderID2.Size           = 4;
        paramOrderID2.SourceColumn   = "OrderID";
        paramOrderID2.SourceVersion = System.Data.DataRowVersion.Original;

        // Set the UpdateCommand parameters for the ProductID field.
        //
        SqlCeParameter paramProductID2 = new SqlCeParameter();
        paramProductID2.ParameterName = "@Original_ProductID";
        paramProductID2.SqlDbType      = System.Data.SqlDbType.Int;
        paramProductID2.Size           = 4;
        paramProductID2.SourceColumn   = "ProductID";
        paramProductID2.SourceVersion = System.Data.DataRowVersion.Original;

        daOrderDetails.UpdateCommand.Parameters.Add(paramQuantity2);
        daOrderDetails.UpdateCommand.Parameters.Add(paramUnitCost2);
        daOrderDetails.UpdateCommand.Parameters.Add(paramOrderID2);
        daOrderDetails.UpdateCommand.Parameters.Add(paramProductID2);

        // Create an InsertCommand to insert data into the OrderDetails table in the local database.
        //
        daOrderDetails.InsertCommand = this.cnIBuySpy.CreateCommand();
        daOrderDetails.InsertCommand.CommandText = @"INSERT INTO OrderDetails (OrderID, ProductID, Quantity, UnitCost) " +
                                                    @"VALUES (?, ?, ?, ?)";

        // Set the InsertCommand parameters for the OrderID field.
        //
        SqlCeParameter paramOrderID3 = new SqlCeParameter();
        paramOrderID3.ParameterName = "@OrderID";
        paramOrderID3.SqlDbType      = System.Data.SqlDbType.Int;
        paramOrderID3.Size           = 4;
        paramOrderID3.SourceColumn   = "OrderID";

        // Set the InsertCommand parameters for the ProductID field.
        //
        SqlCeParameter paramProductID3 = new SqlCeParameter();
        paramProductID3.ParameterName = "@ProductID";
        paramProductID3.SqlDbType      = System.Data.SqlDbType.Int;
        paramProductID3.Size           = 4;
        paramProductID3.SourceColumn   = "ProductID";

        // Set the InsertCommand parameters for the Quantity field.
        //
        SqlCeParameter paramQuantity3 = new SqlCeParameter();
        paramQuantity3.ParameterName = "@Quantity";
        paramQuantity3.SqlDbType      = System.Data.SqlDbType.Int;
        paramQuantity3.Size           = 4;
        paramQuantity3.SourceColumn   = "Quantity";

        // Set the InsertCommand parameters for the UnitCost field.
        //
        SqlCeParameter paramUnitCost3 = new SqlCeParameter();
        paramUnitCost3.ParameterName = "@UnitCost";
        paramUnitCost3.SqlDbType      = System.Data.SqlDbType.Money;
        paramUnitCost3.SourceColumn   = "UnitCost";

        daOrderDetails.InsertCommand.Parameters.Add(paramOrderID3);
        daOrderDetails.InsertCommand.Parameters.Add(paramProductID3);
        daOrderDetails.InsertCommand.Parameters.Add(paramQuantity3);
        daOrderDetails.InsertCommand.Parameters.Add(paramUnitCost3);
    }

    this.daOrderDetails.SelectCommand.Parameters["@Original_OrderID"].Value = orderID;

    // Populate the OrderDetails dataset with data from the OrderDetails table in the local database.
    //
    this.daOrderDetails.Fill(this.dsCustomerOrders, "OrderDetails");

    return this.dsCustomerOrders.Tables["OrderDetails"];
}
cboCustomers_SelectedIndexChanged() Method

The cboCustomers_SelectedIndexChanged() method populates a combo box that allows a driver to select different customers. If the driver changes customers, new customer data is displayed. This method demonstrates how to bind user controls (combo boxes, labels, and so on) to data objects (data tables and data views).

Sample Code for the cboCustomers_SelectedIndexChanged() Method

private void cboCustomers_SelectedIndexChanged(object sender, System.EventArgs e)
{
    if (0 <= this.cboCustomers.SelectedIndex &&
        this.customerID != Convert.ToInt32(this.cboCustomers.SelectedValue))
    {
        DataRowView row = null;

        // If the current order has been modified in any way and the user selects a different customer,
      // the user's changes are discarded: The CustomerOrders and Inventory datasets are reset.
        //
        if (this.dataIBuySpy.HasChanges())
        {
            if (DialogResult.OK == MessageBox.Show(String.Format("You have modified order {0}. Switching customers will discard all changes.", this.orderID),
                "IBuySpy Delivery",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Asterisk,
                MessageBoxDefaultButton.Button1))
            {
                this.dataIBuySpy.ResetOrderDetails();
            }
            else
            {
                this.cboCustomers.SelectedValue = this.customerID;

                return;
            }
        }

        // Set the current binding position.
        //
        BindingContext[dtCustomers].Position = this.cboCustomers.SelectedIndex;

        // Load the selected customer information from the Customer datatable.
        //
        row = (DataRowView)BindingContext[dtCustomers].Current;

        this.customerID = Convert.ToInt32(row["CustomerID"]);

        // Displays the customer's address information.
        //
        this.lblAddressValue1.Text = row["Address"].ToString();
        this.lblAddressValue2.Text = String.Format(@"{0}, {1} {2}", row["City"], row["Region"], row["Zip"]);
        this.lblAddressValue3.Text = row["Phone"].ToString();

        // Set the data viewer to filter by the selected customer.
        //
        this.dvOrders.RowFilter = String.Format("CustomerID = '{0}'", this.customerID);

        UpdateOrderStatus();
    }
}


eMbedded Visual Tools Applications

The Microsoft® eMbedded Visual Tools-based samples consist of two primary applications and four smaller applications for use with Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE). The sample applications are installed by selecting Development Tools during setup.

The primary applications are the Northwind Remote Salesforce applications. These larger applications are based on the Northwind sample database in SQL Server and demonstrate a range of development tasks in eMbedded Visual Tools, including the use of replication and remote data access (RDA), and interface development. The examples demonstrate differences in administration, coding, and functionality between RDA and replication. Replication tends to be server-code focused and includes automatic conflict handling and identity range management. RDA tends to be client-code focused, does not include conflict resolution, and requires manual identity range management.

The smaller applications focus on more specific areas of functionality, such as how to start replication and RDA or how to use OLE DB to create and interact with a SQL Server CE database. Before you use the sample applications, see Setup Instructions for eMbedded Visual Tools Applications.

The following table shows the sample applications and their locations.

Sample application | Location
Northwind Remote Salesforce Replication Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_Repl
Northwind Remote Salesforce RDA Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_Rda
Replication and Remote Data Access eMbedded Visual Basic Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\eVBReplRdaPPC
Replication and Remote Data Access eMbedded Visual C++ Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVC\eVCReplRdaHPC
Client Store and Remote Data Access Simple Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\SimpleRDA
OLE DB Sample Application | C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVC\NorthwindOleDb


Setup Instructions for eMbedded Visual Tools Applications

Before you can run and examine the code for any of the Microsoft® eMbedded Visual Tools sample applications for Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE), you must have several components and tools installed. All of the samples require Microsoft Internet Information Services (IIS) and Microsoft SQL Server with the exception of the OLE DB sample application (OLEDBSeek). For the samples that require IIS and SQL Server, the simplest configuration is to run instances of SQL Server and IIS on the same computer.

Important Sample applications 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.

Following the installation and configuration of the items listed below, you can view the sample applications on any Microsoft Windows Powered Pocket PC 2002-based device or by using an emulator with Microsoft eMbedded Visual Basic®. The Pocket PC 2002 emulator comes with the installation of the Microsoft Windows Powered Pocket PC 2002 SDK. The emulator simulates screens and behavior of a Pocket PC 2002-based device.

Prerequisites for Using the Sample Applications

Install or verify the installation of the following items on the development system:

  • Microsoft eMbedded Visual Basic 3.0, included with Microsoft eMbedded Visual Tools 3.0. For more information, see Setup Tips for eMbedded Visual Tools.
  • Microsoft Windows Powered Pocket PC 2002 SDK (Pocket PC 2002 SDK), available at this Microsoft Web site.
  • Microsoft SQL Server 2000 Service Pack 1 or higher.
  • Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE). For more information, see Setup Tips for SQL Server CE.
  • Microsoft Internet Information Services (IIS) 4.0 or later. Configuration of the SQL Server CE Server Agent (Sscesa20.dll) is required after IIS is installed. For more information, see Setup Tips for IIS and the SQL Server CE Server Agent (Sscesa20.dll).
  • The Northwind Remote Salesforce replication sample application requires that you configure the instance of Microsoft SQL Server 2000 by running the SetupRepl.bat file included with the sample application. For more information, see Setup Tips for Replication: SQL Server 2000 Configuration.
Setup Tips for eMbedded Visual Tools

To install Microsoft eMbedded Visual Tools 3.0, the Pocket PC 2002 SDK, and then Microsoft SQL Server 2000 Windows CE Edition (SQL Server CE), follow the directions in Installing SQL Server CE. The Pocket PC 2002 emulator for Microsoft eMbedded Visual Basic is included with the Pocket PC 2002 SDK, available at this Microsoft Web site.

Setup Tips for SQL Server CE

During the setup of Microsoft SQL Server™ 2000 Windows CE (SQL Server CE), select Development Tools and Server Tools. Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE) is installed with Development Tools. Installing Server Tools makes the SQL Server CE Server Agent (Sscesa20.dll), Sscerp20.dll, and MDAC 2.6 available for connectivity.

Setup Tips for IIS and the SQL Server CE Server Agent (Sscesa20.dll)

Pulling data from a Microsoft SQL Server database to a SQL Server CE database with replication or remote data access (RDA) requires:

  • Configuration of Microsoft Internet Information Services (IIS).
  • Creation of a virtual directory.
  • Configuration of NTFS access permissions for the SQL Server CE Server Agent (Sscesa20.dll) and IIS content folder.

You can perform these steps manually; however, it is strongly recommended that you use the SQL Server CE Connectivity Management utility to configure the computer running IIS, including NTFS access permissions.

You must install SQL Server CE Server Tools on the computer running IIS. After SQL Server CE Server Tools is installed, you are prompted to start the SQL Server CE Virtual Directory Creation Wizard. After you have successfully completed the wizard, the system is properly configured.

If you have installed SQL Server CE Server Tools but chose not to start the wizard, you can start the wizard manually.

To start the SQL Server CE Virtual Directory Creation Wizard

  1. On the Start menu, point to Programs/Microsoft SQL Server CE 2.0, and then click Configure Connectivity Support in IIS.
  2. In the right pane, double-click Create a Virtual Directory.

For more information about the SQL Server CE Virtual Directory Creation Wizard and the SQL Server CE Connectivity Management utility, see Using Connectivity Tools.

Note For applications using replication or RDA, the name of the server running IIS, the virtual directory, and the SQL Server CE Server Agent (Sscesa20.dll) must be specified as part of the InternetURL property for connectivity (for example, http://www.northwindtraders.com/sqlce20/sscesa20.dll). The Northwind Remote Salesforce sample applications include a text box on the first screen of each application in which to enter this information.

Setup Tips for Replication: SQL Server 2000 Configuration

After Microsoft® Internet Information Services (IIS) is properly configured, you can enable Microsoft SQL Server™ 2000 for replication. The replication sample application uses a duplicated Northwind database called Nwind_SQLCE. Running the setup script SetupRepl.bat on the computer running SQL Server 2000 creates the Nwind_SQLCE database, enables SQL Server for replication, and creates a publication named SQLCEReplDemo.

To configure the computer running SQL Server 2000

Note If the computer running SQL Server is already configured as a Publisher/Distributor for replication and has a snapshot folder defined with the appropriate permissions, skip Step 1 and Step 2.

  1. Create a shared directory on the computer running SQL Server 2000 that will become the Publisher/Distributor. Replication snapshot files are created in this directory by the replication process and are read by the SQL Server CE Subscriber.
  2. Ensure that the IIS user specified during synchronization has 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. Run SetupRepl.bat, located with the SQL Server CE files (C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_REPL), according to the following usage specifications:
    Usage: SetupRepl {required parms} {optional parms}

Required Arguments:
{snapshot share} - a share available for the storage of snapshot files. All subscribers (IIS user) must be able to read from this share.
{publisher login} - Publisher user ID.
{publisher password} - Publisher password.

Optional Arguments:
{publisher} - Publisher name. Defaults to local computer.
{snapshot server name} - Defaults to Publisher name (Must be set to support named instances).

Examples:
SetupRepl ReplSnapshot sa <password>
SetupRepl ReplSnapshot sa <password> Publisher
SetupRepl ReplSnapshot sa <password> Publisher\instance ServerName

    This step installs a Publisher with a local Distributor, creates a database named Nwind_SQLCE, and populates 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 is used as the replication snapshot folder. For example, if you call Setuprepl.bat and specify ReplSnapshot as the snapshot shared directory, the directory for all snapshot files is \\computername\ReplSnapshot.

  4. Grant the IIS user (NT_Authentication) or the SQL Server user (DB_Authentication) access to the publication access list. For more information, see Securing the Publication.


Northwind Remote Salesforce Replication Sample Application

This sample Microsoft® eMbedded Visual Basic® application helps you understand how Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) can be combined with Microsoft SQL Server 2000 and replication to form a useful mobile sales route application. The code for the application is commented, so you can easily and freely extrapolate it for your own use. When you select Development Tools during setup, the sample application is installed in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_Repl. Before you use the sample application, see Setup Instructions for eMbedded Visual Tools Applications.

The Northwind Remote Salesforce 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. The application demonstrates a limited set of features and functionality because the objective is to highlight the replication connectivity model and show some of the advanced storage engine features, such as referential integrity with cascading deletes, robust SQL DML support, and cursors.

Note To fully support both the replication and remote data access (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. Although both applications use separate server databases, the application data is identical.

In a typical scenario, a sales representative uses replication to synchronize customer and order information from the 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 copy of the Nwind_SQLCE database on the Pocket PC (called the subscription database). When connectivity becomes available, data in the SQL Server CE database can be synchronized with the SQL Server database by using the Replication object. Because replication 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).


Using the Northwind Remote Salesforce Replication Sample Application

You can run the Northwind Remote Salesforce replication sample application by using the emulator or directly on a Pocket PC if it is connected to the development system. The following subtopics describe using the sample application:

  • Using the Emulator
  • Using the Pocket PC
  • Initializing the Application
  • Adding a New Order
  • Pushing Data Back to SQL Server
  • Resetting the Application
Using the Emulator

The Northwind Remote Salesforce replication sample application is installed by default in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_Repl. To run the sample application, in Microsoft® eMbedded Visual Basic®, double-click the NWindRepl.ebp project file.

By default, Pocket PC 2002 Emulation has been chosen as the run mode for this sample. To begin the sample application, on the Run menu, click Start Debug. A Pocket PC 2002 emulator screen appears.

Screen shot: Application user interface that allows you to enter configuration information and initialize the application.

Using the Pocket PC

To specify a device instead of emulation for deployment, simply use the drop-down list in the toolbar in eMbedded Visual Basic, select Pocket PC 2002 (Default Device) rather than Pocket PC 2002 Emulation, and then run the project file.

Initializing the Application

To initialize the application

  1. In the SQLServer box, enter the name of the computer running Microsoft SQL Server™.
  2. Enter the sa password for the instance of 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 use Integrated Windows authentication. For information about alternate security mode, see Implementing Replication. To change the login information, you must first delete the NorthwindRepl.sdf database file that was created.

  3. In the Internet URL box, enter the path to the virtual directory you created in the SQL Server CE Virtual Directory Creation Wizard. Use the following syntax:

    http://yourserver/yourvirtualalias/sscesa20.dll

    yourserver is the name of the IIS server on which you created a virtual directory. This should be the same name as the computer running SQL Server if you are following the recommendations for using the sample applications. yourvirtualalias is the alias of the virtual directory you created.

  4. Click Initialize. A screen appears similar to the one shown in the following illustration. If you receive an error or the processing continues for more than about a minute, reset the application. For more information, see Resetting the Application.

Screen shot: Application user interface that allows you to synchronize the local database with the server database.

The Initialize button now reads Synchronize, and the Employee Info list now contains names from the Nwind_SQLCE sample database.

By successfully initializing the application, you created a SQL Server CE database named NorthwindRepl.sdf.

The SQLCEReplDemo publication is configured to automatically manage all identity ranges; therefore, the identity ranges for the OrderID column in the Order table are tracked and managed for each Pocket PC. While the Nwind_SQLCE database is open, make a note of the last OrderID number in the Orders table. You can enter new order information in Pocket PC 2002 emulation and synchronize this new order data back to SQL Server.

Adding a New Order

To add a new order into the application, identify which employee of the Northwind Trading Company you want to impersonate. In the Employee Info list, select a name, and then click OK. As shown in the preceding illustration, Steven Buchanan is selected. A screen similar to the one shown in the following illustration appears. By default, the first customer in the list is displayed in the Bill To box.

Screen shot: Application user interface that allows you to select a customer for whom a new order will be created.

You now have access to all customers in the Northwind sample database. The tables created in 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. A new order page, similar to the one shown in the following illustration, appears. In this example, the customer Around the Horn is selected.

Screen shot: Application user interface that allows you to select products to add to an order.

To add items to the order, select product names from the Product list. Enter a quantity for each item by using the keypad provided. Scroll to the right to see the extended price. To add an item in the row below the last current row displayed, click New Item. When you have built a satisfactory order, take note of the number in the Order ID box. This is the order number that is pushed back to SQL Server when you have a connection available. Because you are using emulation, as long as your developer computer has a network connection to the computer running IIS and SQL Server, you always have a connection. To store the order in the local SQL Server CE database (NorthwindRepl.sdf), click Enter Order.

Screen shot: Application user interface that allows you to select products to add to an order.

To see the order history for this customer, click the Review tab.

Screen shot: Application user interface that allows you to view order history for a customer.

To view order detail information, click Refresh. Scroll to the bottom of the Select Order for Detail section, and click the order number for which you want to see details.

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, on the Sync menu at the bottom of the emulator screen, select Sync with Host. You can verify that data was transferred to SQL Server by opening the Orders table in the Nwind_SQLCE sample database in SQL Server Enterprise Manager.

Resetting the Application

There are a number of reasons why you might want to reset the application. One, for example, is to configure alternative security schemes. To reset the application, use Windows CE File Explorer and delete the database file NorthwindRepl.sdf in the root directory of the device.


Northwind Remote Salesforce RDA Sample Application

This sample Microsoft® eMbedded Visual Basic® application helps you understand how Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) can be combined with Microsoft SQL Server 7.0 or SQL Server 2000 and remote data access (RDA) to form a useful mobile sales route application. The code for the application is commented so you can easily and freely extrapolate it. When you select Development Tools during setup, the sample application is installed in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_RDA. Before you use the sample application, see Setup Instructions for eMbedded Visual Tools Applications.

The Northwind Remote Salesforce 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. The application demonstrates a limited set of features and functionality because the objective is to highlight the replication connectivity model and show some of the advanced storage engine features, such as: referential integrity with cascading deletes, robust SQL DML support, and cursors.

In a typical scenario, the sales representative uses RDA to pull customer and order information from the Northwind sample database in either SQL Server 7.0 or SQL Server 2000 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 copy of the Northwind database on the Pocket PC. When connectivity becomes available, data on the SQL Server CE database can be pushed to the SQL Server database by using the RDA Object. Because 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).


Using the Northwind Remote Salesforce RDA Sample Application

You can run the Northwind Remote Salesforce remote data access (RDA) sample application by using the emulator or directly on a Pocket PC if it is connected to the development system. The following subtopics describe using the sample application:

  • Using the Emulator
  • Using the Pocket PC
  • Initializing the Application
  • Adding a New Order
  • Pushing Data Back to SQL Server
  • Resetting the Application
Using the Emulator

The Northwind Remote Salesforce RDA sample application is installed by default in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\Northwind_RDA. To run the sample application, in Microsoft® eMbedded Visual Basic®, double-click the NWindRDA.ebp project file.

By default, Pocket PC 2002 Emulation has been chosen as the run mode for this sample. To begin the sample application, on the Run menu, click Start Debug. A Pocket PC 2002 emulator screen appears.

Screen shot: Application user interface that allows you to enter configuration information and initialize the application.

Using the Pocket PC

To specify a device instead of emulation for deployment, use the drop-down list in the toolbar in eMbedded Visual Basic, select Pocket PC 2002 (Default Device) rather than Pocket PC 2002 Emulation, and then run the project file.

Initializing the Application

To initialize the application for your system

  1. In the SQLServer text box, enter the name of the computer running Microsoft SQL Server™.
  2. Enter the sa password for the instance of 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. For information about alternative security modes, see Implementing RDA. To change the login information, you must first delete the NorthwindRDA.sdf database file that was created.

  3. In the Internet URL text box, enter the path to the virtual directory you created with the SQL Server CE Virtual Directory Creation Wizard. Use the following syntax:

    http://yourserver/yourvirtualalias/sscesa20.dll

    yourserver is the name of the IIS server on which you created a virtual directory. This should be the same name as the computer running SQL Server if you are following the recommendations for using the sample applications. yourvirtualalias is the alias of the virtual directory you created.

  4. Click the Initialize button. A screen appears similar to the one shown in the following illustration. If you receive an error or the processing continues for more than about a minute, reset the application. For more information, see Resetting the Application.

Screen shot: Application user interface that allows you to synchronize the local database with the server database.

The Initialize button reads Synchronize, and the Employee Info list contains names from the Northwind sample database.

By successfully initializing the application, you created a SQL Server CE database named NorthwindRDA.sdf.

If you open the Northwind sample database in SQL Server Enterprise Manager on the computer running SQL Server, you 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 2002. 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 2002 emulation and synchronize this new order data with SQL Server.

Adding a New Order

To add a new order into the application, identify which employee of the Northwind Trading Company you want to impersonate. In the Employee Info list, select a name, and then click OK. As shown in the preceding illustration, Steven Buchanan is selected. A screen similar to the one shown in the following illustration appears. By default, the first customer in the list is displayed in the Bill To box.

Screen shot: Application user interface that allows you to select a customer for whom a new order will be created.

You now have access to all customers in the Northwind sample database. The tables created in 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. A new order page, similar to the one shown in the following illustration, appears. In this example, the customer Around the Horn is selected.

Screen shot: Application user interface that allows you to select products to add to an order.

To add items to the order, select product names from the Product list. Enter a quantity for each item by using the keypad provided. Scroll to the right to see the extended price. To add an item in the row below the last current row displayed, click New Item. After you have built a satisfactory order, take note of the number in the Order ID box. This is the order number pushed back to SQL Server when you have a connection available. Because you are using emulation, as long as the development system has a network connection to the computer running IIS and SQL Server, you always have a connection. To store the order in the local SQL Server CE database (NorthwindRDA.sdf), click Enter Order.

Screen shot: Application user interface that allows you to select products to add to an order.

To see the order history for this customer, click the Review tab.

Screen shot: Application user interface that allows you to view order history for a customer.

To view order detail information, click Refresh. Scroll to the bottom of the Select Order for Detail section, and click the order number for which you want to see details.

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, on the Sync menu at the bottom of the emulator screen, select Sync with Host. You can verify that data was transferred to SQL Server by opening the Orders table in the Northwind sample database in SQL Server Enterprise Manager.

Resetting the Application

There are a number of reasons why you might want to reset the application, for example, to configure alternative security schemes. To reset the application, use Windows CE File Explorer and delete the database file NorthwindRDA.sdf in the root directory of the device.


Additional eMbedded Visual Tools Sample Applications

The four smaller sample applications described in this topic were developed by using Microsoft® eMbedded Visual Tools. The applications are designed to demonstrate particular areas of functionality rather than representing a complete application such as the Northwind Remote Salesforce applications. Before you use these sample applications, see Setup Instructions for eMbedded Visual Tools Applications.

Replication and Remote Data Access Sample Applications

The Microsoft eMbedded Visual Basic® (evbReplRdaPPC) and Microsoft eMbedded Visual C++® (evcReplRdaHPC) sample applications show how to invoke Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE) replication and remote data access (RDA). These sample applications work essentially the same way. They display a menu that lists each of the replication and RDA method calls. When you select one of the method calls, the application displays a form containing the properties and parameters for that method. After you enter the values for the properties and parameters and click OK, the sample application calls the replication or RDA method with the values you specify. This provides a simple way for you to experiment with replication and RDA method calls.

The evbReplRdaPPC application is designed for Microsoft Windows Powered Pocket PC 2002-based devices and the Pocket PC 2002 emulator. The evcReplRdaHPC application is designed for Pocket PC 2000 and Handheld PC 2000 devices. For other devices, you can modify the user interface of the sample application.

For more information, see the Readme files in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\eVBReplRdaPPC and C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVC\ReplRdaHPC.

Client Store and Remote Data Access Simple Sample Application

The eMbedded Visual Basic sample application (evbSimpleRDA) shows how to use SQL Server CE as a local store and connect to SQL Server through the SQL Server CE remote data access (RDA) object model. This sample application also illustrates some basic features of creating databases by using Microsoft ActiveX® Data Objects Extensions for Data Definition Language (DDL) and Security (ADOXCE) and working with Microsoft ActiveX Data Objects for Windows CE 3.1 (ADOCE) recordset objects.

The sample focuses on property initialization, data synchronization, and local store querying with each activity on a separate tab in the application window. Using this application, you can create and populate local tables based on synchronization commands involving server objects. The newly created tables can then be inspected using local query processing and data navigation. In addition, the application can work in a completely local mode and allows native SQL Server CE DDL and DML commands. By using both the local and RDA synchronization functionality, you can explore the capabilities of the SQL Server CE local client engine and RDA connectivity object.

For more information, see the Readme file in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVB\SimpleRDA.

OLE DB Sample Application

The eMbedded Visual C++ sample application (NorthwindOleDb) shows the use of OLE DB to create and interact with a SQL Server CE database. The application creates a database through OLE DB, creates a table, inserts data using SQL statements, and retrieves data from the database by using IRowsetSeek.

For more information, see the Readme file in C:\Program Files\Microsoft SQL Server CE 2.0\Samples\eVC\NorthwindOleDb.


Troubleshooting

The following topics in this section provide troubleshooting information for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Topic | Description
Connectivity Troubleshooting | Identifies the steps to take when you encounter connectivity issues.
SQL Server CE Errors | Lists the descriptions of all SQL Server CE errors.
Finding Answers by Using Web-based Resources | Identifies Web-based resources you can refer to find additional troubleshooting information.


Connectivity Troubleshooting

The following table lists the tools and techniques you can use for troubleshooting connectivity issues with Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Topic | Description
SQL Server Security Flowchart | Presents a decision-tree flowchart to help resolve problems in SQL Server.
Windows Security Flowchart | Presents a decision-tree flowchart to help resolve problems in Windows.
Internet Information Services Security Flowchart | Presents a decision-tree flowchart to help resolve problems in Microsoft Internet Information Services (IIS).
Enabling Logging by the SQL Server CE Server Agent | Describes how to enable logging by the SQL Server CE Server Agent for use in diagnosing remote data access (RDA) and replication problems.
Using Internet Explorer to Check the IIS Configuration | Describes how to use Microsoft Internet Explorer to verify the configuration of IIS security or the SQL Server CE Server Agent.
Understanding Common Errors | Lists common errors and their probable causes.


SQL Server Security Flowchart

Assumption:

You have verified that you entered the correct password.

Decision-tree flowchart to help troubleshoot connectivity problems with an instance of Microsoft SQL Server.

See Also

Internet Information Services Security Flowchart

Windows Security Flowchart

Configuring Database Access

Configuring the Publication Access List


Windows Security Flowchart

Decision-tree flowchart to help troubleshoot connectivity problems with Microsoft Windows.

See Also

Internet Information Services Security Flowchart

SQL Server Security Flowchart

Modifying an Existing Virtual Directory

Configuring IIS and NTFS Permissions Manually

Configuring the Snapshot Folder


Internet Information Services Security Flowchart

Assumptions:

  • You have verified that you entered the correct password.
  • You are not using a proxy server. If you are using a proxy server, see the Remote Data Access (RDA) or Replication object properties.
  • If you are using Anonymous access, Microsoft® SQL Server™ and Microsoft Internet Information Services (IIS) are on the same computer. If not, see Anonymous access on Microsoft Windows® 2000 or Anonymous access on Microsoft Windows NT® 4.0.

    Decision-tree flowchart to help troubleshoot connectivity problems with Microsoft Internet Information Services.

See Also

Windows Security Flowchart

Updating the Database of Trusted Certificate Authorities on a Windows CE-based Device

Configuring Security for Connectivity


Enabling Logging by the SQL Server CE Server Agent

The SQL Server CE Server Agent is capable of logging errors, warnings, and informational messages to a log file on the computer running Microsoft® Internet Information Services (IIS) server. By default, logging is not available. When logging is enabled, the Sscerepl.log file is written to the IIS virtual directory for Microsoft SQL Server™ 2000 Windows® CE Edition (SQL Server CE). The information recorded in the log can be useful for diagnosing remote data access (RDA) or replication problems.

To enable logging by the SQL Server CE Server Agent

  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 the IIS virtual directory for SQL Server CE. For example, if Sscesa20.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 reads only the registry key when the SQL Server CE Server Agent (Sscesa20.dll) is first loaded by IIS. To restart IIS, in Internet Service Manager, right-click the server name and select Restart IIS. If you are using IIS 4.0 on Microsoft Windows NT® 4.0, 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 not available.
1 | Log errors.
2 | Log errors and warnings.
3 | Log errors, warnings, and informational messages. SQL Server CE Server Agent generates very large log files when you specify LOGGING_LEVEL 3. You should not use this logging level under usual circumstances; however, it is useful when you are attempting to diagnose a problem.

For example, if the Sscesa20.dll is located in the NTFS file directory C:\Inetpub\SSCE\NorthWind, create the following registry key value:

HKLM\Software\Microsoft\MSSQLSERVERCE\Transport
C:\Inetpub\sqlce\NorthWind\LOGGING_LEVEL 3

The key value 3 causes errors, warnings, and informational messages to be logged.


Understanding the SQL Server CE Server Agent Log

The SQL Server CE Server Agent log file contains information about each replication synchronization, and remote data access (RDA) Push, Pull, or SubmitSQL operation. The log file, always called Sscerepl.log, uses the following abbreviations to represent actions in replication and RDA operations:

Replication Session Control Block (RSCB)
An automatically incremented structure that uniquely identifies each client's operation.

When Sscesa20.dll is loaded, the RSCB begins at 1. Sscesa20.dll is unloaded only when Microsoft® Internet Information Services (IIS) restarts or the computer running IIS is restarted.

Command
The following table describes the commands executed in the operation.
Command | Description
OPNW | Open and write to the .in/.out file (without close)
OPWC | Open, write, and close the .in/.out file
OPNR | Open and read the .in/.out file
PUT | Write to the .in/.out file
FTCH | Read data from the .in/.out file
CLOS | Close the .in/.out file
SYNC | Reconcile the data between the Subscriber and the Publisher
SCHK | Check for the completion of the SYNC command
PULL | RDA Pull operation
PUSH | RDA Push operation
SQL RDA | SubmitSQL operation
Thread
Is the ordinal of the active thread.
HRESULT (HR)
Is the error for the particular command.


Reading the SQL Server CE Server Agent Log Statistics

The SQL Server CE Server Agent log contains statistics when LOGGING_LEVEL 3 is specified. The statistics portion of the log is located between the opening tag (<STATS) and the closing tag (/>) of the log. Each block of statistic data reports the Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE) connectivity operations that occurred during the last 15 minutes.

Statistics is generated whenever an active request (RSCB) recognizes that 15 minutes have passed since the last report. At times of low volume, this report may be generated less often. Statistics is generated only when an active request occurs. The statistics report is useful in monitoring performance.

The following statistical report shows a single synchronization (merge replication):

<STATS Period_Start="2002/07/13 15:27:32" Period_Duration="954" Syncs="1" SubmitSQLs="0" RDAPushes="0" RDAPulls="0" AVG_IN_File_Size="332" AVG_OUT_File_Size="90203" Completed_Operations="1" Incomplete_Operations="0" Total_Sync_Thread_Time="3" Total_Pool_Thread_Time_IN="0" Total_Pool_Thread_Time_OUT="0" Total_Sync_Queue_Time="0" Total_Pool_Queue_Time_IN="0" Total_Pool_Queue_Time_OUT="0" />

The following table lists and describes the statistics log attributes.

Attribute | Description
Period_Start | Start of the STATS period (in datetime format).
Period_Duration | Time that this report covers (in seconds).
Syncs | Number of bidirectional replication merges performed during this report period.
SubmitSQLs | Number of remote data access (RDA) SubmitSQL() calls during this report period.
RDAPushes | Number of RDA Push() calls during this report period.
RDAPulls | Number of RDA Pull() calls during this report period.
AVG_IN_File_Size | Average size of the .in files (in bytes). Files with an .in extension are physical files created from the message data sent by the client.
AVG_OUT_File_Size | Average size of the .out files (in bytes). Files with an .out extension are physical files created from the message data sent from the server.
Completed_Operations | Number of Sync, SubmitSQL, RDA Push, and RDA Pull calls that were completed during this time period.
Incomplete_Operations | Number of Sync, SubmitSQL, RDA Push, and RDA Pull calls that started but were not completed during this time period.
Total_Sync_Thread_Time | Time that all synchronization threads (sync) took to complete synchronization operations (in seconds). Sync threads are members of a pool of threads that process messages from SQL Server CE. This statistic does not include the time it took to transfer the messages to and from the SQL Server CE clients.
Total_Pool_Thread_Time_IN | Time required to send all data to the server (in seconds). Comparing this attribute to Total_Pool_Thread_Time_OUT reveals where the greatest amount of time is spent, either sending data to the server or sending data to the device.
Total_Sync_Queue_Time | Time that sync requests wait in the sync queue before being processed by the server (in seconds).
Total_Pool_Queue_Time_IN | Time that messages from clients wait in the queue before being processed by the SQL Server CE Server Agent (in seconds).
Total_Pool_Queue_Time_OUT | Time that messages from SQL Server wait before being processed by the SQL Server CE Server Agent (in seconds).


Using Internet Explorer to Check the IIS Configuration

You can use Microsoft® Internet Explorer to verify that you have configured the SQL Server CE Server Agent (Sscesa20.dll) correctly. In Internet Explorer, enter the URL for the SQL Server CE Agent (for example, http://myserver/sqlce/sscesa20.dll). If the SQL Server CE Server Agent is configured correctly, Internet Explorer displays the string: "SQL Server CE Server Agent".

You can also use Internet Explorer to verify that Microsoft Internet Information Services (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 Secure Sockets Layer (SSL) encryption, the URL must specify HTTPS rather than HTTP (for example, https://myserver/sqlce/sscesa20.dll).

When you use Internet Explorer to verify IIS security, you must close and reopen Internet Explorer each time you change any IIS security setting. Opening a new instance of Internet Explorer ensures that a new connection to IIS is established, rather than reusing an existing connection.


Understanding Common Errors

This table lists common errors (and suggested solutions) that you might encounter when you use Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE).

Native error | Error numbers | Solution
28037 80072EFD The user's device must have network connectivity. For example, the device might not have a working modem, network card, or universal serial bus (USB) connection.

Or

Ensure that the computer running Microsoft Internet Information Services (IIS) is available, and that the ISP or network is functioning properly.
28017 80004005 Ensure that the virtual directory is specified correctly.
For example, the URL might be incorrectly listed as http://server/ssqlce/sscesa20.dll instead of http://server/sqlce/sscesa20.dll.

Or

The string "sscesa20.dll" must be included in the URL.
For example, the URL might be incorrectly listed as http://server/sqlce instead of http://server/sqlce/sscesa20.dll.
0 80045017 The SQL Server CE Replication Provider must have read permissions to the snapshot folder. Read permission is needed so the SQL Server CE Replication Provider can download the initial subscription to the Windows CE-based device.

The identity under which the SQL Server CE Replication Provider runs depends upon how IIS authentication is configured.
0 80045020 Ensure that the data type length of the column supplied by the client is supported.

SQL Server CE supports only Unicode data types. It converts all ANSI character data types to their Unicode equivalent.

For example, if you subscribe to a table with a char column of 256 characters, SQL Server CE maps that table to a SQL Server CE ntext column. Then, if a user inserts into the ntext column a record that has a value larger than 256 characters, the user gets an error because the data cannot fit into the char column at the Publisher.

To correct this error, if you cannot change the schema of the Publisher to avoid this type of data type mapping, add application-level logic to limit the number of characters that users can enter on their devices.
28560 | 80040E14 | The snapshot format must be set to character mode for the publication.
25016 Ensure that no duplicate key violations have occurred.

Such violations may occur when users insert records into a table with an identity column. SQL Server CE remote data access (RDA) does not manage identity columns when a table is pulled.

Or

Ensure that a replication publication is configured to manage identity columns for a table(s) in the publication.
4060 | 80004005 | Ensure that the user ID, password, and Initial Catalog to the OLEDBConnectionString parameter of your RDA Pull method are correct.


SQL Server CE Errors

The following categories of errors can be generated from Microsoft® SQL Server™ for Microsoft SQL Server 2000 Windows® CE Edition (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, and the last three parameters (P3,P4,P5) are strings.

Note Although parameters might exist for an error, not all occurrences of the error will return parameters.

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 Errors | 39500-39999

Note If you are looking for other HRESULTs, see Oledberr.h in Microsoft ActiveX® Data Objects for Windows CE 3.1 (ADOCE), or Winerror.h and Wininet.h that are included with Microsoft Visual Studio .NET and in Microsoft eMbedded Visual Tools. For more information about HRESULT values, search the MSDN® Library at this Microsoft Web site or the Microsoft Knowledge Base at this Microsoft Web site.


Engine Errors

Value | Description | Parameters | Error
25001 | Either the cursor is not on a row or there are no rows left. | Not applicable | SSCE_M_NOCURRENTRECORD
25002 | The specified buffer size is not valid. | P0: Buffer size specified | SSCE_M_INVALIDBUFFERSIZE
25003 | The specified length is too long for the column type. | P0: Specified length P1: Column data type | SSCE_M_COLUMNLENGTHTOOBIG
25004 | The column cannot be modified. | P3: Column name | SSCE_M_COLUMNNOTUPDATEABLE
25005 | The column cannot contain null values. | Not applicable | SSCE_M_NULLINVALID
25006 | The operation cannot be performed on the object. | Not applicable | SSCE_M_INVALIDOPERATION
25007 | The operation cannot be performed in a transaction. | Not applicable | SSCE_M_INTRANSACTION
25008 | The parameter is not valid. | P0: Numeric parameter P3: String parameter | SSCE_M_INVALIDPARAMETER
25009 | The path is not valid. Check the directory for the database. | P3: Path | SSCE_M_INVALIDPATH
25010 | The file name is not valid. Check the file name for the database. | P3: File name | SSCE_M_INVALIDFILENAME
25011 | The file is not a valid database file. An internal error has occurred. | P3:Databasename | SSCE_M_INVALIDDATABASE
25012 | An internal error has occurred. | Not applicable | SSCE_M_UPDATENOTPREPARED
25013 | The operation is supported only on tables with exclusive locks. | P3: Table name | SSCE_M_TABLENOTLOCKED
25014 | Access to the system column is denied. | Not applicable | SSCE_M_SYSCOLACCESSDENIED
25015 | A page cannot be allocated. There might not be enough memory on the device. | Not applicable | SSCE_M_CANTALLOCATEPAGE
25016 | A duplicate value cannot be inserted into a unique index. | Not applicable | SSCE_M_KEYDUPLICATE
25017 | The database file is corrupted. | P3: Database name | SSCE_M_DATABASECORRUPTED
25018 | Failed to obtain a lock for a write operation. | Not applicable | SSCE_M_WRITECONFLICT
25019 | Failed to obtain a lock for a read operation. | Not applicable | SSCE_M_READCONFLICT
25020 | Failed to obtain a lock for a commit. | Not applicable | SSCE_M_COMMITCONFLICT
25021 | Failed to obtain lock for a read or write operation. | Not applicable | SSCE_M_SESSIONWRITECONFLICT
25022 | Null keys are not allowed on indexes. | Not applicable | SSCE_M_NULLKEYDISALLOWED
25025 | The primary key value cannot be deleted because references to this key still exist. | P3: Foreign key constraint name | SSCE_M_INTEGRITYVIOLATION_MSTR
25026 | A foreign key value cannot be inserted because a corresponding primary key value does not exist. | P3: Primary key constraint name | SSCE_M_INTEGRITYVIOLATION_SLV
25027 | The row being created exceeds the maximum size allowed. | Not applicable | SSCE_M_RECORDTOOBIG
25028 | The specified password does not match the database password. | Not applicable | SSCE_M_INVALIDPASSWORD
25029 | An attempt was made to update a field in a record twice. | Not applicable | SSCE_M_RI_UPDATETWICE
25030 | A duplicate key value was found as a result of referential integrity action. | P3: Foreign table name | SSCE_M_RI_DUPLICATEKEY
25031 | A referential cascade action is setting a nonnull column to NULL. | P3: Foreign table name | SSCE_M_RI_KEYNULLDISALLOWED
25032 | A write conflict occurred because a referential integrity action is not allowed. | P3: Foreign table name | SSCE_M_RI_SESSIONWRITECONFLICT
25033 | The sort sequence is not valid. | Not applicable | SSCE_M_ILLEGALCOLLATINGSEQ
25034 | There is a file locking violation. | Not applicable | SSCE_M_FILELOCKVIOLATION
25035 | There is a file sharing violation. A different process might be using the file. | Not applicable | SSCE_M_FILESHAREVIOLATION
25036 | File locking is not available. | Not applicable | SSCE_M_FILELOCKINGUNAVAILABLE
25037 | There is not enough disk space left for the database. | Not applicable | SSCE_M_DISKFULL
25038 | There is not enough disk space left for the temp database. | Not applicable | SSCE_M_TEMPDISKFULL
25039 | Access to the database file is not allowed. | P3: File name | SSCE_M_FILEACCESSDENIED
25042 | The language required for this database file is not fully installed on this operating system. | Not applicable | SSCE_M_INVALIDSORTDLL
25044 | Too many files are open. | Not applicable | SSCE_M_TOOMANYOPENFILES
25045 | The database file format is obsolete. | Not applicable | SSCE_M_OBSOLETEDATABASEFORMAT
25046 | The database file cannot be found. Check the path to the database. | P3: File name | SSCE_M_FILENOTFOUND
25047 | Error occurred when reading from the database file. | Not applicable | SSCE_M_READVERIFYERROR
25048 | No more file handles can be created. | Not applicable | SSCE_M_NOMOREFILEHANDLES
25049 | The disk is not ready. | Not applicable | SSCE_M_DISKNOTREADY
25050 | Too many files are open for sharing. | Not applicable | SSCE_M_SHARINGBUFFEREXCEEDED
25051 | An internal error occurred. Unable to successfully execute disk IO on the file system. | Not applicable | SSCE_M_DISKIO
25052 | The operating system does not support threads. | Not applicable | SSCE_M_THREADSNOTSUPPORTED
25054 | Too many columns were specified for the index. | Not applicable | SSCE_M_TOOMANYKEYS
25056 | The size of the Unicode text column is not even. | P0: Column size P3: Column name | SSCE_M_COLUMNWIDTHNOTEVEN
25059 | The column data type cannot be indexed. | Not applicable | SSCE_M_ILLEGALINDEXCOLUMN
25060 | The reference does not exist. | Not applicable | SSCE_M_REFERENCENOTFOUND
25062 | The object is not replicable. | P3: Object name | SSCE_M_OBJECTNOTREPLICABLE
25064 | Only one ROWGUID, autoincrement and version are allowed for each column in a table. | P3: Object name | SSCE_M_ONLYONESPECIALCOLUMN
25065 | Too many indexes were created for the table. | P3: Table name | SSCE_M_TOOMANYINDEXES
25066 | Too many columns were specified for the table. | P0: Column count P3: Column name | SSCE_M_TOOMANYCOLUMNS
25067 | The transactions are nested too deeply. | Not applicable | SSCE_M_TRANSTOODEEP
25068 | A column in an index cannot reference itself. | Not applicable | SSCE_M_SELFREFERENCE
25069 | The referenced table must have a primary index. | Not applicable | SSCE_M_NOPRIMARYINDEX
25070 | The definition of referring columns (such as number of columns or data types) in referential relationships must match the referred columns. | Not applicable | SSCE_M_DIFFNUMRELCOLUMNS
25071 | A reference to this column already exists. | P3: Index name | SSCE_M_CONFLICTINGREFERENCE
25072 | Primary keys cannot be created on columns that support null values. | Not applicable | SSCE_M_PRIMARYKEYNULLCONFLICT
25073 | Tables must contain at least one column. | Not applicable | SSCE_M_TABLEMUSTHAVECOLUMNS
25074 | The expression string for the default value cannot be longer than 255 characters. | P0: Length of expression string | SSCE_M_DEFAULTEXPRTOOLONG
25075 | Nullable columns cannot be identity columns. | Not applicable | SSCE_M_DISALLOWIDENTITYNULL
25077 | The constraint cannot be removed because it is referenced by another constraint. | P3: Constraint name | SSCE_M_CONSTRAINTINUSE
25078 | The index cannot be removed because it is being used to enforce a constraint. | P3: Index name | SSCE_M_INDEXINUSE
25079 | A password must be specified when a database is created using encryption. | Not applicable | SSCE_M_ENCRYPTEDDBMUSTHAVEPWD
25080 | The operating system does not support encryption. | Not applicable | SSCE_M_NOOSENCRYPTIONSUPPORT
25081 | The new value generated for the inserted row does not fall within the allowable range. | P0: Generated value | SSCE_M_VIOLATEDAUTOINCRANGE
25082 | Unique indexes and constraints cannot be created on columns that allow null values. | Not applicable | SSCE_M_UNIQUENULLCONFLICT
25083 | The referential relationship will result in a cyclical reference that is not allowed. | Not applicable | SSCE_M_CYCLEDETECTED
25084 | The data types of the columns in the relationship do not match. | Not applicable | SSCE_M_RELCOLUMNSTYPEMISMATCH
25085 | The table already has a primary key. | Not applicable | SSCE_M_PKDUPLICATE
25086 | The identity column contains an increment value that is not valid. | P3: Column name | SSCE_M_INVALIDINCREMENT
25087 | A new GUID cannot be generated for the new row. | Not applicable | SSCE_M_GENERATEGUIDFAILED
25088 | The key size exceeded the maximum allowed. | Not applicable | SSCE_M_KEYTOOLARGE
25089 | The lock failed due to conflict. | Not applicable | SSCE_M_LOCKCONFLICT
25090 | The system timed out waiting for a lock. | Not applicable | SSCE_M_LOCKTIMEOUT
25091 | The lock manager has no more space for locks. | Not applicable | SSCE_M_OUTOFLOCKS
25092 | The path specified for the temp database is not valid. | Not applicable | SSCE_M_INVALIDTEMPPATH
25200 | The column cannot be NULL. | Not applicable | SSCE_WRN_COLUMNNULL
25201 | The data was truncated. | Not applicable | SSCE_WRN_BUFFERTRUNCATED
25202 | Seek was not able to find an exact match. | Not applicable | SSCE_WRN_SEEKNOTEQUAL
25203 | Some specified options were ignored for this operation. | Not applicable | SSCE_WRN_OPTIONSIGNORED
25204 | The data was truncated. | Not applicable | SSCE_WRN_COLUMNDATATRUNCATED
25205 | The database is encrypted. A password is necessary to access the database. | Not applicable | SSCE_WRN_DATABASEENCRYPTED
25206 | Additional records were updated as a result of referential integrity actions. | Not applicable | SSCE_WRN_RI_RECORDSUPDATED
25207 | Additional records were deleted as a result of referential integrity actions. | Not applicable | SSCE_WRN_RI_RECORDSDELETED
25208 | The request for a row-level lock was denied. | Not applicable | SSCE_WRN_ROWLOCKCONNECTFAILED
25209 | The request for a page-level lock was denied. | Not applicable | SSCE_WRN_PAGELOCKCONNECTFAILED
25500 | The execution plan cannot be generated. | Not applicable | SSCE_M_QP_BADOPT
25501 | There was an error parsing the query. | P0: Token line number P1: Token line offset P3: Token in error | SSCE_M_QP_BADPARSE
25502 | The count of column names and source expressions do not match. | P0: Column name count P1: Source expression count | SSCE_M_QP_SETLISTCOUNT
25503 | The column name is not valid. | P3: Node name (if any) P4: Column name | SSCE_M_QP_BAD_COLNAME
25505 | The constraint specified is not valid. | Not applicable | SSCE_M_QP_BADCNSTS
25506 | There is not enough memory to complete the operation. | Not applicable | SSCE_M_QP_NOMEMORY
25507 | The comment block is not complete. | Not applicable | SSCE_M_QP_UNCLOSEDCOMMENT
25508 | The token specified is too long. The maximum length is 128 characters | P0: Maximum size of token (if known) P3: Token (if known) | SSCE_M_QP_TOKTOOLONG
25509 | A conversion from string to float data failed. | P3: String | SSCE_M_QP_ATOF_OVERFLOW
25510 | A conversion from string to numeric data failed. | P3: String value | SSCE_M_QP_NUME_OUTOFRANGE
25511 | A quotation mark delimiter is missing from the end of the query. | P3: Query string | SSCE_M_QP_UNCLOSEDQUOTE
25512 | Conversion from string to money data failed. | P3: Bad value | SSCE_M_QP_BADMONEY
25513 | Null values are not valid identifiers. | P3: Identifier | SSCE_M_QP_IDENTWITHNULL
25514 | The identifier cannot be an empty string. | Not applicable | SSCE_M_QP_NAME_EMPTY
25515 | In aggregate and grouping expressions, the SELECT clause can contain only aggregates and grouping expressions. | P3: Select clause | SSCE_M_QP_NO_SCALAR_IN_SELECT
25516 | Nested aggregate expressions are not allowed. | P3: Query string | SSCE_M_QP_NO_AGG_IN_AGG
25517 | In aggregate and grouping expressions, the HAVING clause can contain only aggregate functions and grouping expressions. | P3: Having clause | SSCE_M_QP_NO_SCALAR_IN_HAVING
25518 | In aggregate and grouping expressions, the ORDER BY clause can contain only aggregate functions and grouping expressions. | P3: Order by clause | SSCE_M_QP_NO_SCALAR_IN_AGGRORDERBY
25519 | Expressions in the GROUP BY list cannot contain aggregate functions. | P3: Group by list | SSCE_M_QP_NO_AGG_IN_GROUPBY
25520 | Expressions in the ORDER BY list cannot contain aggregate functions. | P3: Order by list | SSCE_M_QP_NO_AGG_IN_ORDERBY
25521 | The ORDER BY list cannot have duplicate expressions. | P3: Order by list P4: Duplicate expression | SSCE_M_QP_NO_DUPEXPR_IN_ORDERBY
25522 | The table aliases must be unique. | P3: Name of duplicate alias | SSCE_M_QP_DUP_TABLE_ALIAS
25523 | The column aliases must be unique. | P3: Name of duplicate alias | SSCE_M_QP_DUP_COLUMN_ALIAS
25524 | A HAVING clause must have a GROUP BY clause (implicit or explicit). | P3: Having clause | SSCE_M_QP_HAVING_WITHOUT_GROUPBY
25525 | The WHERE clause cannot refer to aggregate expressions . | P3: Where clause | SSCE_M_QP_NO_AGG_IN_WHERE
25526 | Duplicate constraints cannot be specified. | P3: Constraint | SSCE_M_QP_DUP_CNST
25527 | A function with the same signature already exists. | P3: Name of function | SSCE_M_QP_AMBIGUOUS_FUNC
25529 | The OLE DB provider cannot be instantiated. | Not applicable | SSCE_M_QP_CANT_COCREATE
25530 | A column with the same name has already been specified. | P3: Name of duplicate column | SSCE_M_QP_SETLIST_DUPCOLNAME
25531 | The column name cannot be resolved to a table. Specify the table to which the column belongs. | P3: Name of ambiguous column | SSCE_M_QP_AMBIGUOUS_COLNAME
25532 | The float precision is not valid. | Not applicable | SSCE_M_QP_BAD_FLOAT_PRECISION
25533 | The identifier name is too long. | P3: Name of column (if known) | SSCE_M_QP_LONGIDNAME
25534 | Large objects (ntext and image) cannot be used in ORDER BY clauses. | P3: Order by clause | SSCE_M_QP_LOB_IN_ORDERBY
25536 | The meta data for the large object is not valid. | Not applicable | SSCE_M_QP_INVALIDMETA_FOR_LOB
25537 | The columns in the subquery do not match. | P3: Column name | SSCE_M_QP_SUBQUERY_COLUMN_MISMATCH
25538 | The database is encrypted. A password must be specified. | Not applicable | SSCE_M_QP_ENCRYPTION_NO_DBPASSWORD
25539 | The escape character for the LIKE predicate is not valid. | P3: Escape character | SSCE_M_QP_BADLIKEESCCHAR
25540 | The datepart is not valid. | P3: Portion of data in error | SSCE_M_QP_BADDATEOPTION
25541 | The identifier is not valid. | P3: Identifier | SSCE_M_QP_INVALID_IDENTIFIER
25542 | Data cannot be inserted into a read-only table. | P3: Name of read-only table | SSCE_M_QP_READONLYINSERT
25543 | Data cannot be updated in a read-only table. | P3: Name of read-only table | SSCE_M_QP_READONLYUPDATE
25544 | Data cannot be deleted from a read-only table. | P3: Name of read-only table | SSCE_M_QP_READONLYDELETE
25545 | A value must be provided for the INSERT statement into <table_name>. | P3: Table name | SSCE_M_QP_NOINSERTCOLUMNS
25546 | The column is read-only and cannot be modified. | P3: Column name | SSCE_M_QP_MODIFYPROTECTEDCOL
25547 | ORDER BY <column number> is not supported. | Not applicable | SSCE_M_QP_SCALARORDERBYNOTSUPPORTED
25548 | DISTINCT cannot be used with ntext and image data. | Not applicable | SSCE_M_QP_LOB_IN_DISTINCT
25549 | GROUP BY cannot be used with ntext and image data. | Not applicable | SSCE_M_QP_LOB_IN_GROUPBY
25550 | Too many identity columns are specified for the table. Only one identity column for each table is allowed. | P3: SQL statement | SSCE_M_QP_MULTI_IDENTITY_COLUMNS
25551 | The identity column must be an integer data type and cannot be NULL. | Not applicable | SSCE_M_QP_BAD_IDENTITY_TYPE
25552 | Elements in the GROUP BY clause must reference columns in the select list. | P3: SQL statement | SSCE_M_QP_GROUPBY_MUST_REFERENCE_COLS
25553 | A foreign key constraint that has an UPDATE or a DELETE CASCADE rule and self-references a column in the same table, is not allowed. | Not applicable | SSCE_M_QP_CASCADEONSELFREFFK
25554 | Defaults cannot be created on identity columns. | P3: Name of table P5: Name of column | SSCE_M_QP_NODEFAULTONIDENTITYCOL
25555 | Subquery columns cannot be ntext or image data types. | Not applicable | SSCE_M_QP_SUBQUERY_NOLOBCOLUMNS
25556 | The number sign (#) is reserved and cannot be used as the first character of an identifier. | P3: Invalid name | SSCE_M_QP_INVALID_CHARACTER_IN_IDENTIFIER
25557 | Expressions combined by a UNION operator must have the same number of columns. | Not applicable | SSCE_M_UNIONCOLUMNCOUNT
25558 | The number of columns in the query and the table must match. | Not applicable | SSCE_M_DIFFERENTCOLUMNCOUNT
25900 | The query processor encountered an error evaluating the expression. | Not applicable | SSCE_M_QP_BADEXPR
25901 | Expression evaluation caused an overflow. | P3: Expression | SSCE_M_QP_OVFLO
25902 | The data types in the IN expression do not match. | P3: Expression | SSCE_M_QP_EXPRTYPECHECK
25903 | There is an error in the datepart format. | P3: Expression | SSCE_M_QP_DATEPART
25904 | There is an error in the date format. | P3: Expression | SSCE_M_QP_DATEABORT
25905 | A syntax error occurred. | P3: Expression | SSCE_M_QP_SYNTAX
25906 | Conversion failed due to a syntax error | P3: Expression | SSCE_M_QP_CONVSYNTAX
25907 | An overflow occurred while converting the string data type to money. | P3: String | SSCE_M_QP_MONEYOVERFLOW
25909 | Default values cannot have column references. | P3: Expression | SSCE_M_QP_NOCOLUMNREFINDEFAULT
25910 | Default values cannot have aggregate functions. | P3: Expression | SSCE_M_QP_NOAGGRINDEFAULT
25911 | Aggregate value expressions cannot have ntext or image data. | P3: Expression | SSCE_M_QP_NOAGGRONLOB
25912 | The original data is truncated and cannot be converted. | P3: Expression | SSCE_M_QP_NOCONVDUETOTRUNC
25913 | The arithmetic operator is not supported for the data type. | P3: Expression | SSCE_M_QP_ARITHOPNOTSUPPORTED
25914 | Modulo is not supported on real, float, money, and numeric data types. | P3: Data type | SSCE_M_QP_NOMODULOSUPPORT
25916 | An operator on the result data type from a subquery is not valid. | P3: Operator P4: Subquery expression | SSCE_M_QP_SUBQUERYINVALIDOP
25917 | Bit operators (&,|,^,~) are not supported on real, float, money, and numeric data types. | P3: Data type | SSCE_M_QP_NOBITOPSUPPORT
25918 | The data type is not valid for the arithmetic operation. | P0: Data type P3: Expression | SSCE_M_QP_BADARITHTYPE
25919 | The arithmetic operator is not recognized by SQL Server CE. | P3: Operator | SSCE_M_QP_BADARITHOP
25920 | The data is truncated. | Not applicable | SSCE_M_QP_TRUNCATION
25921 | The function is not recognized by SQL Server CE. | P3: Name of function P5: Data type | SSCE_M_QP_INVALIDFUNCTIONNAME
25922 | The arguments for <func_name> function are not valid. | P3: Name of function (if known) | SSCE_M_QP_INVALIDFUNCTIONARGS
25923 | The ntext and image data types cannot be used in WHERE, HAVING, GROUP BY, ON, or IN clauses, except when these data types are used with the LIKE or IS NULL predicates. | P3: Expression | SSCE_M_QP_NOSUPPORTFORLOB
25924 | An overflow might have occurred while converting binary to datetime. | P0: Binary value | SSCE_M_QP_BINDTSYNTAX
25925 | An overflow might have occurred while converting numeric to datetime. | P0: Numeric value | SSCE_M_QP_NUMDTSYNTAX
25926 | An overflow might have occurred while converting money to datetime. | P0: Money value | SSCE_M_QP_MONDTSYNTAX
25927 | An overflow might have occurred while converting bigint to datetime. | P0: bigint value | SSCE_M_QP_BIGINTDTSYNTAX
25928 | There are too many arguments specified for the function. | P0: Count of arguments | SSCE_M_QP_TOOMANYARGS
25929 | A unary minus can be performed only on tinyint, smallint, int, bigint, money, and numeric data types. | P3: Expression | SSCE_M_QP_UMINUSNUMONLY
25930 | The operation cannot be performed because the precision of the numeric data types do not match. | P3: Expression | SSCE_M_QP_PRECISIONMISMATCH
25931 | The operation cannot be performed because the scale of the numeric data types do not match. | P3: Expression | SSCE_M_QP_SCALEMISMATCH
25932 | The data types cannot be converted implicitly. | P0: Source data type P1: Destination data type | SSCE_M_QP_NOIMPLICITCONVALLOWED
25933 | An overflow occurred while converting to datetime. | P3: Expression | SSCE_M_QP_DATETIMEOVFLO
25935 | Dividing by zero is not allowed. | P3: Expression | SSCE_M_QP_DIVBYZERO
25937 | A time datepart must be specified to convert a string to datetime. | P3: String | SSCE_M_QP_NOTIMEPARTSPECIFIED
25938 | The specified hour in the time datepart is not valid. | P3: String | SSCE_M_QP_INVALIDHOURTIMEPARTSPECIFIED
25939 | The specified minute in the time datepart is not valid. | P3: String | SSCE_M_QP_INVALIDMINUTETIMEPARTSPECIFIED
25940 | The specified second in the time datepart is not valid. | P3: String | SSCE_M_QP_INVALIDSECONDIMEPARTSPECIFIED
25941 | The specified millisecond in the time datepart is not valid. | P3: String | SSCE_M_QP_INVALIDMSEDCONDIMEPARTSPECIFIED
25942 | The specified date or time datepart is not valid. | P3: String | SSCE_M_QP_SYNTAXERRORINDATETIMESTRING
25943 | The format of the specified date or time datepart is not valid. | P3: String | SSCE_M_QP_FORMATERRORINDATETIMESTRING
25944 | The order of the specified date or time datepart is not valid. | P3: String | SSCE_M_QP_INVALIDORDERINDATETIMESTRING
25945 | The escape sequence used in the LIKE predicate is not valid. | P3: Escape sequence P4: Like predicate | SSCE_M_QP_INVALID_ESCAPE_SEQUENCE
25946 | The number of arguments specified for function <func_name> is not correct. | Not applicable | SSCE_M_QP_INVALIDFUNCTIONARGNUM
25947 | The conversion is not supported. | Not applicable | SSCE_M_QP_INVALIDCONVERSION
25948 | The specified argument value for the function is not valid. | Not applicable | SSCE_M_QP_INVALIDFUNCTIONARGVALUE
25949 | The expressions in UNION are not compatible. | Not applicable | SSCE_M_QP_INCOMPATIBLE_TYPES
25950 | A parameter is missing. | Not applicable | SSCE_M_QP_MISSINGPARAMETER
25951 | A parameter is not allowed in this location. | Not applicable | SSCE_M_QP_PARAMETERNOTALLOWED
25952 | At least one input table is required. | Not applicable | SSCE_M_QP_EMPTYFROMLIST
26100 | The table name is not valid. | P3: Table name | SSCE_M_QP_BADTABLE
26101 | An error occurred while accessing the schema rowset. | Not applicable | SSCE_M_QP_BADSCHEMAROWSET
26102 | An error occurred while accessing the table schema rowset. | P3: Table name | SSCE_M_QP_TBLSCHEMAROWSET
26300 | OLE DB returned an error. | Not applicable | SSCE_M_QP_OLEDBERR
26302 | The specified data type is not valid. | P0: Data type | SSCE_M_QP_BADTYPE
26303 | An internal query processor error occurred. | Not applicable | SSCE_M_QP_INTERNAL
26305 | The meta data is not valid. | Not applicable | SSCE_M_QP_BADADTMETAINFO
26306 | Data conversion failed. | P0: OLE DB status value | SSCE_M_QP_COERSIONERROR
26307 | Syntax error in query. | Not applicable | SSCE_M_QP_BADQUERY
26308 | Zero-length binary constants are not supported in SQL Server CE. | Not applicable | SSCE_M_QP_ZEROLENGTHBINARYCONST
27000 | Too many sessions are open. | Not applicable | SSCE_M_TOOMANYSESSIONSOUTSTANDING
27001 | The new column cannot be set as the PRIMARY KEY constraint. Create a table-level constraint instead. | P3: Table name P4: Column name | SSCE_M_PRIMARYKEYPROPERTYNOTSETTABLE
27002 | The new column cannot be set as a UNIQUE constraint. Create a table-level constraint instead. | P3: Table name P4: Column name | SSCE_M_UNIQUEKEYPROPERTYNOTSETTABLE
27003 | Column nullability cannot be changed after the column is created. | P3: Table name P4: Column name | SSCE_M_COLUMNNULLABILITYNOTALTERABLE
27004 | The column cannot become an identity column after it is created. | P3: Table name P4: Column name | SSCE_M_CANTMODIFYIDENTITYATTRIBUTE
27005 | The column property is not valid. | P3: Table name P4: Column name P5: Property | SSCE_M_INVALIDCOLUMNPROPERTY
27006 | An attempt to set the SQLServer CE DBINIT property is not valid. | Not applicable | SSCE_M_INVALIDSSCEDBINITPROPERTY
27500 | An overflow occurred while setting decimal data. | Not applicable | SSCE_M_DECIMALOVERFLOW
27501 | Decimal data was truncated. | Not applicable | SSCE_M_DECIMALTRUNCATED
27502 | The parameter is not valid. | Not applicable | SSCE_M_CMN_INVALIDPARAMETER
27700 | Decimal data was truncated. | Not applicable | SSC_WRN_DECIMALTRUNCATED
27750 | Cannot load sscemw20.dll or ssceca20.dll is missing or not registered. | Not applicable | SSCE_M_SSCEMWFAILURE


Replication Transport Errors

Value | Description | Parameters | Error
28000 | An internal error has occurred. | Not applicable | SSCE_M_OPENTWICE
28001 | A read operation from the Internet returned an incorrect number of bytes. | Not applicable | SSCE_M_INTERNETREADERROR
28002 | A write operation to the Internet wrote an incorrect number of bytes. | Not applicable | SSCE_M_INTERNETWRITEERROR
28003 | Either the computer running IIS is out of memory or an incorrect RSCBID was sent in a request. | P0: RSCBID | SSCE_M_INVALIDRSCBID
28004 | A SQL Server CE Server Agent queue is full and can take no further requests. Try again later. | Not applicable | SSCE_M_TOOMANYPENDINGREQUESTS
28005 | A thread to host the SQL Server Reconciler cannot be started. Check system resources. | Not applicable | SSCE_M_COULDNTSTARTRECTHREAD
28006 | The SQL Server Reconciler resource DLL cannot be loaded. | Not applicable | SSCE_M_CANTLOADRECRESOURCEDLL
28007 | An internal error has occurred. | Not applicable | SSCE_M_INVALIDRECONCILERPARAM
28008 | The transport failed due to incorrect message format or content. | P0: Command number | SSCE_M_INVALIDTRNSPTCOMMAND
28009 | An instance of the SQL Server Reconciler cannot be created. | Not applicable | SSCE_M_CANTCOCREATERECONCILER
28010 | An instance of the SQL Server Reconciler error object cannot be created. | Not applicable | SSCE_M_CANTCOCREATERECONERROR
28011 | Authentication failed on the computer running IIS. | Not applicable | SSCE_M_HTTPSTATUSDENIED
28012 | Authentication failed on the proxy server. | Not applicable | SSCE_M_HTTPSTATUSPROXYAUTHREQ
28013 | The HTTP request failed due to incorrect format or content. | Not applicable | SSCE_M_HTTPSTATUSBADREQUEST
28014 | This site requires payment before it can be accessed. | Not applicable | SSCE_M_HTTPSTATUSPAYMENTREQ
28015 | A Secure Sockets Layer (SSL) connection is required to access this site. | Not applicable | SSCE_M_HTTPSTATUSFORBIDDEN
28016 | The URL cannot be found. | Not applicable | SSCE_M_HTTPSTATUSNOTFOUND
28017 | An incorrect or unsupported HTTP function call was made. | Not applicable | SSCE_M_HTTPSTATUSBADMETHOD
28018 | An HTTP function failed to establish a connection to the computer running IIS. | Not applicable | SSCE_M_HTTPSTATUSNONEACCEPT
28019 | The request timed out on the computer running IIS. | Not applicable | SSCE_M_HTTPSTATUSREQTIMEOUT
28020 | The computer running IIS returned a Conflict status. | Not applicable | SSCE_M_HTTPSTATUSCONFLICT
28021 | The computer running IIS returned a Gone status. | Not applicable | SSCE_M_HTTPSTATUSGONE
28022 | An error has occurred on the computer running IIS. | Not applicable | SSCE_M_HTTPSTATUSSERVERERROR
28023 | The computer running IIS returned a Not Supported status. | Not applicable | SSCE_M_HTTPSTATUSNOTSUPPORTED
28024 | A gateway error has occurred. | Not applicable | SSCE_M_HTTPSTATUSBADGATEWAY
28025 | The IIS service is not available. | Not applicable | SSCE_M_HTTPSTATUSSVCUNAVAIL
28026 | The gateway has timed out. | Not applicable | SSCE_M_HTTPSTATUSGATTIMEOUT
28027 | HTTPS is not supported on Windows CE 1.1-based devices. | Not applicable | SSCE_M_HTTPSNOTSUPPORTED
28028 | Replication is prohibited for this SQL Server CE Server Agent on the computer running IIS. | Not applicable | SSCE_M_REPLPROHIBITED
28029 | RDA is prohibited for this SQL Server CE Server Agent on the computer running IIS. | Not applicable | SSCE_M_RDAPROHIBITED
28030 | Internal error: Compression failed. | Not applicable | SSCE_M_COMPRESSIONFAILED
28031 | Internal error: Decompression failed. | Not applicable | SSCE_M_DECOMPRESSIONFAILED
28032 | Internet Open failed at the client. | Not applicable | SSCE_M_FAILUREINITIALIZINGINTERNET
28033 | The URL syntax is not valid. | P3: URL | SSCE_M_INVALIDURLSYNTAX
28034 | An Internet connection cannot be established. | Not applicable | SSCE_M_INTERNETCONNECTFAILURE
28035 | Header information is either corrupted or missing. | P3: Header name | SSCE_M_FAILUREQUERYINGHEADER
28036 | An internal or network problem was encountered while trying to close an Internet handle. | Not applicable | SSCE_M_CLOSEINTERNETHANDLEFAILED
28037 | A request to send data to the computer running IIS has failed. For more information, see HRESULT. | Not applicable | SSCE_M_HTTPSENDREQUESTFAILED
28038 | The connection was refused by the computer running IIS because the maximum number of RSCBs has been exceeded. Try connecting later. | Not applicable | SSCE_M_MAXIMUMRSCBSEXCEEDED
28039 | The request was superseded by a subsequent request. | Not applicable | SSCE_M_REQUESTSUPERSEDED
28040 | The command has been completed. The resent command was ignored. | Not applicable | M_RESENTCOMMANDIGNORED
28041 | An internal error occurred. | Not applicable | M_RESENDREQUEST


Client Agent Errors

Value | Description | Parameters | Error
28500 | An instance of the SSCEErrors collection object cannot be created. | Not applicable | SSCE_M_CANTCOCREATESSCEERRORS
28501 | The SubscriberConnectionString property is not specified. | Not applicable | SSCE_M_SUBSCRIBERDATABASEPATHMISSING
28502 | The InternetURL property is not specified. | Not applicable | SSCE_M_INTERNETURLPROPERTYMISSING
28503 | The Publisher property is not specified. | Not applicable | SSCE_M_PUBLISHERPROPERTYMISSING
28504 | The PublisherDatabase property is not specified. | Not applicable | SSCE_M_PUBLISHERDATABASEPROPERTYMISSING
28505 | The Publication property is not specified. | Not applicable | SSCE_M_PUBLICATIONPROPERTYMISSING
28506 | The Subscriber property is not specified. | Not applicable | SSCE_M_SUBSCRIBERPROPERTYMISSING
28507 | Some Distributor properties are not specified. | Not applicable | SSCE_M_MISSINGDISTRIBUTORPROPERTIES
28508 | The DistributorAddress property is not specified. | Not applicable | SSCE_M_MISSINGDISTRIBUTORADDRESS
28509 | The PublisherAddress property is not specified. | Not applicable | SSCE_M_MISSINGPUBLISHERADDRESS
28510 | The value specified for the PublisherSecurityMode property is not valid. | P0: Publisher security mode | SSCE_M_INVALIDPUBLISHERSECURITYMODE
28511 | The value specified for the DistributorSecurityMode property is not valid. | P0: Distributor security mode | SSCE_M_INVALIDDISTRIBUTORSECURITYMODE
28512 | The value specified for the QueryTimeout property is not valid. | P0: Query timeout value | SSCE_M_INVALIDQUERYTIMEOUTVALUE
28513 | The value specified for the LoginTimeout property is not valid. | P0: Login timeout value | SSCE_M_INVALIDLOGINTIMEOUTVALUE
28514 | The value specified for the DistributorNetwork property is not valid. | P0: Distributor network | SSCE_M_INVALIDDISTRIBUTORNETWORK
28515 | The value specified for the ExchangeType property is not valid. | P0: Exchange type | SSCE_M_INVALIDEXCHANGETYPE
28516 | The value specified for the ValidateType property is not valid. | P0: Validation type | SSCE_M_INVALIDVALIDATIONTYPE
28517 | The Initialize method failed. | Not applicable | SSCE_M_INITIALIZEFAILED
28518 | The AddSubscription method failed. | Not applicable | SSCE_M_ADDSUBSCRIPTIONFAILED
28519 | The value specified for DBDROPOPTION is not valid. | Not applicable | SSCE_M_UNSUPPORTEDDBDROPOPTION
28520 | The DropSubscription method failed. | Not applicable | SSCE_M_DROPSUBSCRIPTIONFAILED
28521 | The SQL Server CE database is already enabled for replication. | Not applicable | SSCE_M_DBALREADYREPLICABLE
28522 | The Run method failed. | Not applicable | SSCE_M_RUNFAILED
28523 | Internal error: Initializing an internal object failed. | Not applicable | SSCE_M_INITIALIZATIONFAILED
28524 | The Terminate method failed. | Not applicable | SSCE_M_TERMINATEFAILED
28525 | The ReinitializeSubscription method failed. | Not applicable | SSCE_M_REINITIALIZESUBSCRIPTIONFAILED
28526 | The message contains an unexpected replication operation code. | P0: ROC | SSCE_M_UNEXPECTEDROCENCOUNTERED
28527 | Internal error: The column ordinal cannot be found. | P0: Column ordinal P3: Table name | SSCE_M_COLUMNORDINALNOTFOUND
28528 | A nickname was not generated. | Not applicable | SSCE_M_NICKNAMEGENERATIONFAILED
28529 | The SQL Server CE database is not enabled for replication. | Not applicable | SSCE_M_DBNOTREPLICABLE
28530 | Reading the registry failed. | Not applicable | SSCE_M_FAILUREREADINGREGISTRY
28531 | Writing to the registry failed. | Not applicable | SSCE_M_FAILUREWRITINGREGISTRY
28532 | A read operation from the transport returned no data. | Not applicable | SSCE_M_TRANSPORTREADRETURNEDNODATA
28533 | Another instance of SQL Server CE cannot be created. | Not applicable | SSCE_M_CANTCOCREATESQLSERVERCE
28534 | The Pull method failed. | Not applicable | SSCE_M_RDAPULLFAILED
28535 | The Push method failed. | Not applicable | SSCE_M_RDAPUSHFAILED
28536 | The SubmitSQL method failed. | Not applicable | SSCE_M_RDASUBMITSQLFAILED
28537 | The identity range was not established. | Not applicable | SSCE_M_IDENTITYRANGE
28538 | An article in the message is not valid. | P0: Article nickname | SSCE_M_INVALIDARTICLE
28539 | The object is already initialized. | P3: Connection string | SSCE_M_OBJECTALREADYINITIALIZED
28540 | The object is not initialized. | P3: Connection string | SSCE_M_OBJECTNOTINITIALIZED
28541 | The value for the LocalTableName parameter is not specified for the Push call. | Not applicable | SSCE_M_LOCALTABLENAMEMISSING
28542 | Some parameters were not specified for the Pull method. | Not applicable | SSCE_M_NOTALLPARAMSSETFORPULL
28543 | The table is not a tracked table. | P3: Table name | SSCE_M_TABLENOTTRACKED
28544 | The Push method returned one or more error rows. See the specified error table. | P3: Error table name | SSCE_M_RDAERRORROWSRETURNED
28545 | The OLE DB connection string is not valid. | Not applicable | SSCE_M_SUBSCRIBERCONNECTIONSTRINGMISSING
28546 | The specified OLE DB for SQL Server CE connection string is not valid. | P3: Connection string | SSCE_M_INVALIDCONNECTIONSTRING
28547 | The SQL Server CE database cannot be compacted because it is open. | Not applicable | SSCE_M_DATABASEALREADYOPEN
28548 | A specified parameter is too large. | P0: Size of parameter P1: Max size P3: Parameter value | SSCE_M_PARAMETERTOOLARGE
28549 | The row update or insert cannot be reapplied due to an integrity violation. | Not applicable | SSCE_M_FAILEDRETRIES
28550 | The SQL Server CE database cannot be compacted. | Not applicable | SSCE_M_COMPACTFAILED
28551 | The LocalConnectionString parameter is not specified for either a Push or Pull method. | Not applicable | SSCE_M_MISSINGCONNECTSTRING
28552 | This table does not have a ROWGUID column. | Not applicable | SSCE_M_ROW_RUID
28553 | This table does not have a ROWGUID column nor an Identity range. | Not applicable | SSCE_M_SPECIAL_COLUMN
28554 | The number of rows at the client does not match the number of rows at the server. | P0: SQL Server Count P1: SQL Server CE Count | SSCE_M_VALIDATEFAILED
28555 | The SQL Server CE database cannot be replicated. The subscription must be reinitialized. | Not applicable | SSCE_M_FAILEDMAKEDBREP
28556 | The LocalTableName parameter is not specified. | Not applicable | SSCE_M_TABLENAMEMISSING
28557 | The SQL Server CE database cannot be used for replication. Delete and then re-create the database. | P3: Connection string | SSCE_M_UNUSABLEDATABASE
28558 | SQL Server CE encountered problems in creating the SQL Server CE database. | P3: Connection string | SSCE_M_CREATEDATABASE
28559 | SQL Server CE encountered problems in opening the SQL Server CE database. | P3: Database name | SSCE_M_OPENDATABASE
28560 | The OLE DB Execute method failed. The SQL statement is not valid. | P3: SQL statement | SSCE_M_EXECUTEFAILED
28561 | Internal error: Failed to roll back changes. | Not applicable | SSCE_M_ROLLBACKFAILED
28562 | The delete message for the server was not created. | Not applicable | SSCE_M_PROCESSDELETEFAILED
28563 | The device does not have sufficient memory. | Not applicable | SSCE_M_CLIENTAGENT_NOMEMORY
28564 | The delete action failed. | P3: Table name | SSCE_M_DELETEFAILED
28565 | The insert action failed. | P3: Table name | SSCE_M_INSERTFAILED
28566 | The update action failed. | P3: Table name | SSCE_M_UPDATEFAILED
28567 | The table cannot be opened. | P3: Table name | SSCE_M_OPENTABLEFAILED
28568 | The table cannot be closed. | P3: Table name | SSCE_M_CLOSETABLEFAILED
28569 | The index cannot be set on the ROWGUID column. | Not applicable | SSCE_M_INVALIDINDEX
28570 | The data row cannot be accessed. | Not applicable | SSCE_M_ERRORFETCHINGDATA
28571 | The column data for a row cannot be accessed. | Not applicable | SSCE_M_ERRORFETCHINGCOLUMNDATA
28572 | Row data cannot be set. | Not applicable | SSCE_M_ERRORSETTINGDATA
28573 | The LocalTableName parameter is already specified. | P3: Table name | SSCE_M_TABLEALREADYEXISTS
28574 | An internal error occurred. | P0:ID | SSCE_M_INTERNALERROR
28575 | There is not enough space for lineage in a row. | Not applicable | SSCE_M_INSUFFICIENTLINEAGESPACE
28577 | The schema has changed since the table was pulled. | Not applicable | SSCE_M_SCHEMAHASCHANGED
28578 | The data type is not valid. | Not applicable | SSCE_M_UNSUPPORTEDDATATYPE
28579 | The move to the next row failed. | Not applicable | SSCE_M_MOVENEXTFAILED
28580 | The specified parameter is not valid. | Not applicable | SSCE_M_INVALIDCOMPACTPARAMETER
28581 | The message cannot be built. The Make Message failed. | Not applicable | SSCE_M_FAILUREMAKINGMESSAGE
28582 | The parameter is either not specified or not valid. | Not applicable | SSCE_M_INVALIDRDAPARAMETER
28583 | The Publisher login property is not specified. | Not applicable | SSCE_M_PUBLISHERLOGINMISSING


Client Agent Warnings

Value | Description | Parameters | Error
28800 | The Push returned one or more error rows. See the specified error table. | Not applicable | SSCE_WRN_RDAERRORROWSRETURNED
28801 | A data error occurred and was fixed. Call the Run method again to merge data. | Not applicable | SSCE_WRN_SUBWINSERRORSFIXED


Server Agent Errors

Value | Description | Parameters | Error
29000 | An unexpected state was found when reading generation information. | Not applicable | SSCE_M_UNEXPECTEDSTATEREADINGGENINFO
29001 | An unexpected state was encountered when processing inserts. | Not applicable | SSCE_M_EXPECTEDINSERTSONLY
29002 | The identity seed or range is too large. | P0: Seed or low range P1: High range | SSCE_M_IDENTITYSEEDORRANGETOOLARGE
29003 | An unexpected state was encountered when processing deletes. | Not applicable | SSCE_M_UNEXPECTEDSTATEPROCESSINGTOMBSTONES
29004 | The OLE DB provider for SQL Server CE cannot be initialized. | Not applicable | SSCE_M_CANTCOCREATEMSDAINITIALIZE
29005 | A replication session control block already exists. | Not applicable | SSCE_M_RSCBWITHSAMEEXCHANGEID
29006 | A call to SQL Server Reconciler failed. | Not applicable | SSCE_M_SQLRECONCILERFAILED
29007 | The query cannot be tracked. There might not be a primary key, or the query may involve multiple tables. | P3: Query string | SSCE_M_QUERYCANNOTBETRACKED
29008 | The prepare/update command process failed. | Not applicable | SSCE_M_PREPAREUPDATECMDFAILED
29009 | The expression or literal cannot be processed without an alias. | Not applicable | SSCE_M_EXPRESSIONWITHOUTALIAS
29010 | The table does not have a primary key. | P3: Table name | SSCE_M_NOPRIMARYKEY
29011 | The table contains a timestamp or another row versioning column. | P3: Table name | SSCE_M_ROWVERCOLUMN
29012 | An internal error occurred during the push operation in the SQL Server CE Server Agent. | Not applicable | SSCE_M_INVALIDPUSHSEQUENCE
29013 | The attempt to replace an existing parameter value in the push operation failed. | Not applicable | SSCE_M_PUSHPARAMSETONVALUE
29014 | Incomplete parameters were set for the push operation. | Not applicable | SSCE_M_NOTALLPARAMSETFORPUSH
29015 | The expected column count does not match the data column specified. | P0: Supplied count P1: Expected count | SSCE_M_PUSHPKCOLCOUNTMISMATCH
29016 | Client-side and server-side columns for the RDA table do not match. | P3: Table name | SSCE_M_VF_MISSINGSERVERCOLUMN
29017 | The OLE DB data type information in the SQL Server CE columns does not match the information in the SQL Server columns for the RDA table. | P0: SQL Server CE data type P1: SQL Server data type P3: Table name | SSCE_M_VF_MISMATCHEDTYPES
29018 | No columns were found. Either the table name is missing or the permissions are not valid. | Not applicable | SSCE_M_VF_MISSINGTABLE
29020 | A row cannot be updated or deleted in the SQL Server using RDA. | Not applicable | SSCE_M_NOROWSAFFECTED
29021 | More than one row was affected by an update or delete operation in the SQL Server using RDA. | Not applicable | SSCE_M_TOOMANYROWSAFFECTED
29022 | The version of the Microsoft OLE DB Provider for SQL Server is not correct. | P3: Version | SSCE_M_INCORRECTPROVIDERVERSION
29023 | The OLE DB Provider for SQL Server on the computer running IIS is not compatible with SQL Server CE. | P3: Provider | SSCE_M_INCORRECTPROVIDER
29024 | The push operation cannot match the orders of the client-side and server-side primary key columns. | Not applicable | SSCE_M_VF_PRIMARYKEYCHANGE
29025 | The push operation cannot find a primary key column on the SQL Server table. | Not applicable | SSCE_M_VF_MISSINGSERVERPKCOLUMN
29026 | The push operation has found an extra primary key column on the SQL Server table. | Not applicable | SSCE_M_VF_EXTRASERVERPKCOLUMN
29027 | The current OLE DB provider is not supported. | Not applicable | SSCE_M_MISSINGCOLUMNSCHEMACOLS
29028 | The OLE DB data type is not supported by the Microsoft OLE DB Provider for SQL Server. | P0: Data type | SSCE_M_UNSUPPORTEDOLEDBTYPE
29029 | The SQL Server CE and SQL Server column meta data information does not match. | Not applicable | SSCE_M_VF_NONLOBIUNKNOWN
29030 | The query cannot be tracked because one or more columns of the primary key are missing. | Not applicable | SSCE_M_NOTRACKPKCOLMISSING
29031 | The query cannot be tracked because the table includes a computed column that cannot be pulled. | Not applicable | SSCE_M_NOTRACKCOMPUTEDCOLUMN
29032 | The query cannot be tracked because it is a multi-table query. | Not applicable | SSCE_M_NOTRACKMULTITABLE
29033 | The server code page, or the override code page, is either not valid or not installed on the computer running IIS. | P0: Code page | SSCE_M_INVALIDCODEPAGE
29034 | The SQL Server CE Client Agent and SQL Server CE Server Agent component versions do not match. | P0: Client version P1: Server version P3: SQL Server CE Client Agent version P4: SQL Server CE Server Agent version | SSCE_M_MISMATCHEDCOMPONENTS
29042 | The replication session control block was inactive for longer than the cleanup interval. | Not applicable | SSCE_M_RSCBTIMEDOUT
29043 | The operating system on the Windows CE-based device does not support authenticated proxy servers. | Not applicable | SSCE_M_NOPROXYSERVERSUPPORT
29044 | SQL Server CE failed in renaming an .IN file to .OUT. | Not applicable | SSCE_M_FILERENAMEFAILED
29045 | Initializing SQL Server Reconciler has failed. | Not applicable | SSCE_M_INITIALIZERECONCILERFAILED
29046 | This cursor is read-only. | Not applicable | SSCE_M_READONLY
29047 | Row processing resulted in an error. | Not applicable | SSCE_M_PROCESSINGROWS
29048 | The Windows user account could not be impersonated at the computer running IIS. | Not applicable | SSCE_M_IMPERSONATIONFAILED


Message Protocol Errors

Value | Description | Parameters | Error
29500 | The transport read operation returned an incorrect data length. | P0: Returned length P1: Expected length | SSCE_M_TRANSPORTREADWRONGSIZE
29501 | Internal error: The write message failed. | Not applicable | SSCE_M_UNEXPECTEDSTATEWRITINGMESSAGE
29502 | The column number is not valid. | P0: Column number P3: Table name | SSCE_M_INVALIDCOLUMNNUMBER
29503 | The column cannot be found. | P3: Column name P4: Table name | SSCE_M_CANTFINDCOLUMNBYNAME
29504 | Internal error: The names buffer is too small. | Not applicable | SSCE_M_NAMESBUFFERTOOSMALL
29506 | Internal error: The get column failed. | Not applicable | SSCE_M_UNEXPECTEDSTATEGETTINGCOLUMNS
29507 | Internal error: The get column length failed. | Not applicable | SSCE_M_UNEXPECTEDSTATEGETCOLLENGTH
29508 | Internal error: The get column data failed. | Not applicable | SSCE_M_UNEXPECTEDSTATEGETCOLDATA
29509 | Internal error: The set column failed. | Not applicable | SSCE_M_UNEXPECTEDSTATESETCOLUMN
29510 | The ISequentialStream interface detects that the BLOB data stream is not empty. | Not applicable | SSCE_M_STREAMNOTEXHAUSTED
29511 | The message received from the server cannot be decoded. | Not applicable | SSCE_M_GARBLEDMESSAGEFROMSERVER
29512 | The message received from the client cannot be decoded. | Not applicable | SSCE_M_GARBLEDMESSAGEFROMCLIENT


SQL Server CE Relay Errors

Value | Description | Parameters | Error
30000 | The socket cannot be initialized/uninitialized. | Not applicable | SSCE_M_WSANOTINITIALISED
30001 | The network was unavailable, and the initialization/uninitialization of the socket failed. | Not applicable | SSCE_M_WSAENETDOWN
30002 | The socket cannot be initialized/uninitialized. A blocking operation is currently executing. | Not applicable | SSCE_M_WSAEINPROGRESS
30003 | The socket caninitialized/uninitialized. Either a driver is missing or multiple implementations are being used. | Not applicable | SSCE_M_WSASYSNOTREADY
30004 | The socket cannot be initialized/uninitialized. The current version is not supported. | Not applicable | SSCE_M_WSAVERNOTSUPPORTED
30005 | The socket cannot be initialized/uninitialized. The limit on the number of processes using Windows Sockets has been reached. | Not applicable | SSCE_M_WSAEPROCLIM
30006 | An address passed to the function is not valid. | Not applicable | SSCE_M_WSAEFAULT
30007 | A create event failed. For more information, see HRESULT. | Not applicable | SSCE_M_CREATEEVENTFAILED
30008 | A set event failed. For more information, see HRESULT. | Not applicable | SSCE_M_SETEVENTFAILED
30009 | A WAITFOR event failed. For more information, see HRESULT. | Not applicable | SSCE_M_WAITFAILED
30010 | The specified desktop computer port is not valid. | Not applicable | SSCE_M_INVALIDCLIENTPORT
30011 | The conversion of the server name to Unicode failed. | Not applicable | SSCE_M_CONVERSIONTOUNICODEFAILED
30012 | The server port specified is not valid. | Not applicable | SSCE_M_INVALIDSERVERPORT
30013 | The system menu cannot be accessed. | Not applicable | SSCE_M_FAILUREACCESSINGSYSTEMMENU
30014 | The registry keys cannot be set or created. | Not applicable | SSCE_M_FAILURESETTINGREGISTRY
30015 | A parameter passed to SQL Server CE Relay is not valid. | Not applicable | SSCE_M_INVALIDARGUMENT
30016 | The combination of arguments is not valid. | Not applicable | SSCE_M_INVALIDARGUMENTS
30017 | Either a port number is not valid or the server name is missing. | Not applicable | SSCE_M_MISSINGPORTORSERVER
30018 | The socket call failed. | Not applicable | SSCE_M_SOCKETCALLFAILED
30019 | The socket port is already in use on this device. | Not applicable | SSCE_M_PORTALREADYINUSE
30020 | The bind failed. | Not applicable | SSCE_M_BINDFAILED
30021 | The server address cannot be resolved. | Not applicable | SSCE_M_CANTRESOLVESERVERADDRESS
30022 | The Listen function failed on a socket. | Not applicable | SSCE_M_LISTENFAILED
30023 | An accept from the server failed. | Not applicable | SSCE_M_ACCEPTFAILED
30024 | A connection request to the server has failed. | Not applicable | SSCE_M_CONNECTFAILED
30025 | A thread cannot be created due to system problems or lack of resources. | Not applicable | SSCE_M_CANTCREATETHREAD
30026 | Internal error: Setting a socket option for keep alive failed. | Not applicable | SSCE_M_SETKEEPALIVEFAILED
30027 | Internal error: Setting a socket option for the Nagle algorithm failed. | Not applicable | SSCE_M_SETNAGLEFAILED
30028 | The receive operation from the socket failed. | Not applicable | SSCE_M_RECEIVEFAILED
30029 | The send operation to the socket failed. | Not applicable | SSCE_M_SENDFAILED
30030 | The initialization of arguments failed. | Not applicable | SSCE_M_INITARGSFAILED
30031 | The WSAStartup function failed during socket initialization. | Not applicable | SSCE_M_WSASTARTUPFAILED
30032 | The WSACleanup function failed during a cleanup operation. | Not applicable | SSCE_M_WSACLEANUPFAILED
30033 | The server name is either not valid or not specified. | Not applicable | SSCE_M_INVALIDSERVERNAME
30034 | The socket connection was reset. | Not applicable | SSCE_M_CONNECTIONRESET


Miscellaneous Errors

Value | Description | Parameters | Error
39999 | The evaluation copy has expired. | Not applicable | SSCE_M_EVALUATIONCOPYEXPIRED


Finding Answers by Using Web-based Resources

To find additional troubleshooting assistance for Microsoft® SQL Server™ 2000 Windows® CE Edition (SQL Server CE), you can refer to the following Web-based resources:

  • SQL Server Support Center

    Microsoft Product Support Services (PSS) support for SQL Server CE and SQL Server is available at this Microsoft Web site.

  • SQL Server CE FAQs

    PSS maintains an up-to-date list of frequently asked questions about SQL Server CE at this Microsoft Web site.

  • Knowledge Base Articles

    A database of SQL Server CE-specific articles written by support professionals is maintained by PSS at this Microsoft Web site. To find SQL Server CE-specific articles, in Search the Knowledge Base, select SQL Server CE.

  • MSDN Online

    For developers who are using Microsoft products, the Microsoft Developer Network (MSDN®) provides online resources at this Microsoft Web site.

  • White Papers

    White papers about SQL Server CE-related issues are available from PSS at this Microsoft Web site.