Introducing Microsoft Visual Database Tools

You can access Microsoft® Visual Database Tools from your development environment to help create and manage data-driven applications that rely on live connections to Microsoft® SQL Server™ databases. The Query Designer enables you to use visual tools to build SQL statements that retrieve data or modify the contents of tables. The Database Designer graphically represents tables and their relationships and enables you to create and modify the database objects that your application relies on. All this can be done while you’re connected to the underlying database. Thus, you can design, query, and populate your databases from within the design environment that you use to build your application.

With Microsoft Visual Database Tools, you can:

  • Connect to and explore any ODBC-compliant database.

  • Create and modify SQL Server databases using database diagrams.

  • Design, execute, and save complex queries.

  • Add, update, and delete data stored in database tables.

  • Design objects, such as tables, triggers, and stored procedures, in Microsoft SQL Server and Oracle databases.

  • Drag database objects onto a design surface, such as an HTML template form, and then drop to bind controls to those objects.

Microsoft Visual Database Tools are available in Microsoft® Visual InterDev™ 6.0, Microsoft® Visual J++™ 6.0, Microsoft® Visual C++® 6.0, and Microsoft® Visual Basic® 6.0 Enterprise Editions. To use Visual Database Tools, you first create a Web project or database project, and then add a database connection to that project.

For details about creating a database project, see Creating a Database Project.

For information about creating a Web project in Microsoft Visual InterDev, see the section "Creating Web Projects" in the Microsoft Visual InterDev online help.

Visual Database Tools Components

Microsoft Visual Database Tools is made up of four components:

  • Data View

  • Database Designer

  • Query Designer

  • Source Code Editor for stored procedures and triggers

This combination of database design tools provides a complete, tightly integrated database-development and administration tool for developers.

The specific functionality available in each component depends on the database server you are using. For more information about the differences between database servers, see Database Server Considerations.

Data View

The Data View component provides a visual interface in which you can view:

  • Live connections to the databases in each project

  • Objects available in each database, organized into folders, including:
    • Database diagrams

    • Tables

    • Triggers

    • Views

    • Stored procedures

For more information, see Managing Databases in Data View.

Database Designer

The Database Designer provides a graphical environment in which you can:

  • Create and modify the structure of Microsoft SQL Server and Oracle databases.

  • Create, modify, or delete database objects such as tables, relationships, indexes, and constraints.

  • Experiment with the design of your database without affecting the database until you choose to save your new design.

  • Carry out complex DDL operations using a simple interface. For example, you can change a column’s data type by selecting a different data type from a drop-down list.

  • View and save change scripts of the SQL code for the changes you made in a database diagram. You can submit change scripts to database administrators for review and execution in controlled database environments.

For more information, see Database Designer.

Query Designer

The Query Designer provides four different ways for you to construct and execute queries against any ODBC-compliant database. You can:

  • Use a visual query diagram to drag tables into the query and use graphical controls to manipulate the query definition.

  • Use a criteria grid to specify search criteria, sort order, output columns, and so on.

  • Use an SQL pane to type ANSI-SQL statements — or let the Query Designer generate the SQL for you — for Select, Insert, Update, and Delete queries.

  • Browse and edit live views of data in your database tables.

For more information, see Query Designer.

Source Code Editor

The Source Code Editor enables you to:

  • Edit stored procedures and triggers.

  • Execute stored procedures and view their results.

  • Debug stored procedures (if Microsoft Visual C++® Enterprise Edition is installed).

For more information about editing stored procedures and triggers, see Stored Procedures and Triggers.


What's New in Visual Database Tools

This version of the Microsoft® Visual Database Tools gives you more power and flexibility when working with databases. The Database Designer and Query Designer work with the latest versions of Microsoft® SQL Server™, Oracle, and Microsoft® Access databases.

The following new features and expanded functionality make database design and management faster, easier, and more powerful.

  • Microsoft SQL Server Support

  • Oracle Support

  • Design Enhancements

Microsoft SQL Server Support

The following SQL Server functionality has been added or improved:

Database Designer

  • Improved editing of the database structure

  • Improved support for triggers

  • Support for new data types

  • Support for SQL Server objects in Microsoft Access 98 client/server databases, specifically the database, table, and view designers

Query Designer

  • Improved support for SQL statements, syntax, grammar, and database object identifiers

  • Ability to view and edit binary data, such as Memo fields

For more information about features specific to Microsoft SQL Server, see Working with SQL Server Databases.

Oracle Support

With this release, Oracle database support has been added to the Visual Database Tools. Now you can use the powerful visual design tools to manage your Oracle databases. Specifically, the following functionality has been added for Oracle databases:

Database Designer

  • Ability to manage and edit Oracle database objects, including database tables, indexes, and constraints

  • Code generation and error handling for Oracle database objects

  • Ability to set properties for Oracle database objects

Query Designer

  • Support for Oracle 7.x databases

  • Improved support for Oracle SQL statements, syntax, grammar, and database object identifiers

  • Trapping of query operations that aren't allowed in Oracle (such as full outer joins and wrapping SQL statements in transactions)

For more information about features specific to Oracle, see Working with Oracle Databases.

Design Enhancements

Several design enhancements make it easier to use the database tools, and give you more control over your database diagrams and queries. This version of the Visual Database Tools offers the following new or improved features:

Print and Preview Database Diagrams

Printing, previewing page breaks, and displaying database diagrams is much easier with the addition of new formatting features and custom diagram views that show just the information you want to see.

For more information, see Printing and Previewing Database Diagrams.

Table Views in Database Designer

In a database diagram, you can expand tables to show more properties or collapse them to save space on the diagram. There are five defined views available, including a Custom View, which give you greater flexibility in displaying your tables in the diagram.

For more information, see Changing a Table View.

Automatic Layout in Database Diagrams

In a database diagram, you can use new features to automatically rearrange the tables in the diagram window. With the press of a button, Database Designer will analyze the relationships between your tables and determine the best layout of the tables for easy viewing.

For more information, see Arranging Tables Automatically.

Zoom-to-Selection in Database Diagrams

In a database diagram, the new zooming features allow you to select specific items and size them to fit in the diagram window. This makes it easy to arrange your database diagram for printing.

For more information, see Zooming a Database Diagram.

Add Relationship Line Labels in Database Designer

You can easily add labels to the relationship lines between tables identifying the relationship between the tables. The relationship lines can be customized in the Property Pages of the relationship.

For more information, see Adding Labels to Relationship Lines.

Annotate a Database Diagram

You can easily add text annotations to your diagrams. Text headings or notes can enhance the presentation of your database diagram.

For more information, see Annotating Diagrams.

Single Table Design in Database Designer

In addition to modifying tables in a database diagram, you can use the Database Designer to modify the structure of a single table in your database. You can create a new table in design mode, or you can edit the properties of existing tables to update the database.

For more information, see Tables.

View Designer Creates Database Views

You can use the View Designer to create special views to extract and combine just the information you need from one or more existing database tables.

For more information, see Working with Database Views in Data View.

Manipulate Dates Arithmetically

With this release of the Visual Database Tools, the Query Designer can now work with dates as mathematical expressions.

For more information, see Operators for Expressions.

New Query Types Supported by the Query Designer

In Query Designer, you can now create Make Table and Insert Values queries. With an Insert Values query, you can create new rows and insert values into specified columns. The Make Table query creates a new table and creates rows in the table by copying the results of a query into the table.

For more information, see Supported Query Types, Creating Insert Values Queries and Creating Make Table Queries.


The Visual Database Tools in Microsoft Visual Studio

The Microsoft® Visual Database Tools are included in the Microsoft® Visual Studio™ suite of products to provide a visual tool for integrating database access in your applications.

For information about | See
The features available in the different versions of the Visual Studio suite products | Differences Between Visual Studio Enterprise and Professional Edition
Creating and using a data connection | Working with Database Projects
Using the Data View window to access the Visual Database Tools | Managing Databases in Data View
Using the Project Explorer (FileView in Microsoft® Visual C++®) to create and manage queries and SQL scripts | Working in the Project Explorer
How to create and work with database diagrams | Database Designer
How to create and manage queries | Query Designer


Differences Between Visual Studio Enterprise and Professional Edition

The Microsoft® Visual Database Tools are available as a component in many of the Microsoft Visual Studio™ applications, including Microsoft® Visual InterDev™, Visual Basic®, and Visual C++®. The Visual Studio suite is available in two editions: Professional and Enterprise.

The Professional version of Visual Studio 6.0 offers developers a great solution for accessing data. The Enterprise version builds on the Professional box by offering the ability to manipulate the structure of the database using the full features of the Visual Database Tools.

What's available in each Visual Studio product edition:

Capability | Professional Edition | Enterprise Edition
Create Queries | X | X
Edit Queries | X | X
Execute Stored Procedures | X | X
Create New Views |  | X
Create New Tables |  | X
Edit Table Structures |  | X
Create New Stored Procedures |  | X
Edit Stored Procedures |  | X
Debug Stored Procedures |  | X
Source Control for Stored Procedures and Triggers |  | X
Create New Triggers |  | X
Create New Database Diagrams |  | X
Edit Database Diagrams |  | X


Working with Database Projects

A database project is a collection of one or more data connections that enable you to access your server database. When you create a database project, you can connect to one or more databases through ODBC or OLE DB. You can view their components through a visual user interface.

You can use database projects in Microsoft® Visual InterDev™, Microsoft® Visual C++®, and Microsoft® Visual J++™ with the Visual Database Tools, as described below.

Note In Microsoft® Visual Basic®, database projects are not used. You can use the Data Project template to create a new project, which adds default controls and objects, including the data environment. To use the Visual Database Tools in Visual Basic, you can either add a data connection to the data environment, or make a data connection directly from the Data View window. Also, in Visual Basic, all data connections are made through OLE DB, although you can still use ODBC data source names (DSNs) to define your connections.

In Visual InterDev, you can use database projects to create and manage databases and database objects using SQL script files. You can put these files under source control. You also don't need to create a data connection for a database project until you want to execute an SQL script. For more information on using database projects in Visual InterDev, see Managing Database Projects.

By creating a database project, you can:

  • Create, edit, or delete database objects in the Database Designer for Microsoft® SQL Server™ 6.5 databases and Oracle databases while you are directly connected to the database in which those objects are stored.

  • Interact with Microsoft SQL Server and Oracle server databases using database diagrams. Database diagrams graphically represent tables, the columns they contain, and the relationships between them. You can use database diagrams to:
    • View the tables in your database and their relationships.

    • Perform complex operations to alter the structure of your database, such as changing table definitions, column names, and data types.
  • Create, modify, execute, and save queries with the Query Designer, which includes a visual query tool, an interactive SQL window, and an output window for viewing and updating result sets.

  • Share queries between applications. You can:
    • Drag a saved query file into any editor in your development environment to insert the query's SQL statement into that editor. For example, you can drag a query file onto the Visual Database Tools stored procedure editor to add the SQL statement to a stored procedure, or drag a saved query into the Visual C++ or Visual J++ editor to add the SQL statement to your ODBC code.

    • Drag a query into any OLE container, such as a Microsoft® Excel spreadsheet, or paste it into an application or component that isn't an OLE container. For example, you can paste the SQL statement into Microsoft® Access as a pass-through query without having to test it again.

    Note This drag-and-drop feature is not available in Visual Basic. You can, however, paste the SQL statement into your code in a Visual Basic project to set the SQL property of a Remote Data Objects (RDO) Command object.

  • Create and execute stored procedures.

Note If you have installed Visual C++ Enterprise Edition, you can also debug stored procedures. To do so, you must first create a database project; you can then debug the stored procedure within the database project. Stored procedure debugging is also available in Microsoft Visual Basic, Microsoft Visual InterDev, and Microsoft Visual J++ Enterprise Editions. For more information, see Debugging Stored Procedures in Working with Stored Procedures in Data View.


Creating a Database Project

You can create a database project when you want to create, modify, or delete database objects using the Database Designer, or create and execute queries using the Query Designer. For more information about using these design tools, see the Database Designer and Query Designer topics.

To create a database project in Microsoft® Visual InterDev™ and Visual J++™

  1. From the File menu, choose New Project.

  2. On the New tab, click the Visual Studio folder

  3. Click the Database Projects folder.

  4. Select New Database Project.

  5. In the Name box, type a name for this database project. This project will be stored in the location shown in the Location box. If you want to store your project in a different location, type or choose a new location in the Location box.

  6. To create the new database project in a new solution, select Close current solution.

    -or-

    To add the new database project to the current solution, select Add to current solution.

  7. Choose OK.

  8. From the Select Data Source dialog box, select a data connection. For details, see Adding a Data Connection to a Database Project.

After you add a data connection, the database project is created in the location you specified and the Data View window is added to the project workspace. The Data View window displays the database objects for the database associated with this data connection. The database project is displayed in the Project Explorer.

To create a database project in Microsoft® Visual C++®

  1. From the File menu, choose New.

  2. In the New dialog box, choose the Projects tab.

  3. Select Database Project.

  4. In the Project Name box, type a name for this database project. This project will be stored in the location shown in the Location box. If you want to store your project in a different location, type or choose a new location in the Location box.

  5. From the Select Data Source dialog box, select a data connection. For details, see Adding a Data Connection to a Database Project.

After you add a data connection, the database project is created with a .dsp extension in the location you specified and the Data View tab is added to the project workspace. The database project is displayed in the FileView tab.


Adding a Data Connection to a Database Project

When you create a new database project, you choose a data source name (DSN) that specifies the location and type (ODBC driver) of the database you want to access. After you have selected a DSN, Microsoft® Visual Database Tools adds a data connection to your project that stores the connection information from the DSN used to connect to a database server. For details about choosing a DSN, see Choosing a Data Source Name.

Note In Microsoft® Visual Basic® you can either add a data connection to the data environment, or make a data connection directly from the Data View window. In Visual Basic, all data connections are made through OLE DB, although you can still use ODBC data source names (DSNs) to define your connections.

A database project can contain multiple data connections. You must add one data connection when you create a database project (except in Microsoft® Visual InterDev™ and Visual J++™, for which you can add the data connection later). You can also add more data connections later if your project requires you to access multiple databases.

Note When specifying a database to use in a project, it is important to specify a location that will work not just in the development environment you are using, but in your final project. If your project involves a database that is accessed from a Web server, use a Universal Naming Code (UNC) to be sure that the database location you specify is accessible from the Web server.

To add a data connection to a database project

  1. In the Project Explorer, right-click the database project you want to add a data connection to, and then select Add Data Connection.

    Note In Microsoft® Visual C++®, right-click the database project in FileView.

  2. In the Select Data Source dialog box, choose the File Data Source tab to select or create a file DSN, or the Machine Data Source tab to select or create a DSN stored in the Windows® Registry of your computer. For more information, see Choosing a Data Source Name.

  3. Choose an existing DSN or create a new DSN for the database server you want to connect to.

    For more information about creating a file DSN, see Creating a File DSN.

    For more information about creating a machine DSN, see Creating a Machine DSN.

After you have successfully added a data connection, the name of the new data connection is displayed as a node under the project name in the Project Explorer (FileView in Microsoft Visual C++).


Choosing a Data Source Name

You must choose a data source name (DSN) to connect to a database within a database project or a Web project. A DSN stores information about how to connect to a particular ODBC database. The ODBC driver manager uses the information in the DSN to establish and manage the connection.

There are two types of DSNs. Both types store information needed to make a connection to a database server, but they store it in different locations. The two types are:

  • File DSN Connection information is stored in a file that can be read by any application (such as Microsoft® Visual InterDev™), a feature which makes the project more easily portable between computers. As a general rule, you should always use file DSNs, especially when using the data connection in a Web application. For details, see Creating a File DSN.

  • Machine DSN Connection information is stored in the Windows® Registry of the computer on which the data connection is created. For details, see Creating a Machine DSN.

You can choose either a file DSN or a machine DSN from the Select Data Source dialog box, which opens when you choose to create a new data connection. You can also either select an existing data source name or create a new one. If you click the New button to create a new DSN, the Create New Data Source wizard opens to assist you.

In order to connect to a particular database server, you must have an ODBC driver for that database server. If the ODBC driver you need doesn't appear in the Create New Data Source wizard, you might not have the correct ODBC driver installed on your computer. Check your database's documentation to determine whether there's an ODBC driver available for it.

If you're developing a client-server application in Microsoft® Visual C++®, or Microsoft® Visual J++™, you can use either a file DSN or a machine DSN to add a data connection. When you build the setup program for your application using the setup wizard, you must set up a machine DSN on the user’s computer. You do this by modifying the user’s registry to contain the information needed to make the connection.


Creating a File DSN

A file data source name (DSN) stores information about a database connection in a file. The file has the extension .dsn and by default is stored in the $\Program Files\Common Files\ODBC\Data Sources directory.

To create a new file DSN

  1. In the Project Explorer, right-click the database project you want to add a data connection to, and then select Add Data Connection.

    Note In Microsoft® Visual C++®, right-click the database project in FileView.

  2. Select the File Data Source tab.

  3. Choose New.

  4. Select the driver for which you want to set up a data source, and then choose Next.

  5. Type a name for the file that will contain the connection information. Once created, this name will appear in the Select Data Source dialog box. The extension .dsn is automatically appended to the name that you type. When you have finished typing the name, choose Next.

  6. Review the information you have entered. If everything is correct, choose Finish. If you want to make changes, choose Back.

  7. Follow the instructions for the Create a New Data Source wizard or the dialog box that is displayed. For help with these dialog boxes, choose the Help button.

    For SQL Server data sources, you use the Create a New Data Source wizard. For other data sources, you use various dialog boxes. For example, for Microsoft® Access data sources, you use the ODBC Microsoft Access 97 Setup dialog box, and for Microsoft® FoxPro® data sources, you use the ODBC Visual FoxPro Setup dialog box.

    Tip When you specify a database, enter a location that will work not only in the development environment you are using, but also in your final project. For example, if your project involves a database that is accessed from a Web server, use a Universal Naming Code (UNC) to be sure that the database location you specify is accessible from the Web server.

If you've created a file DSN for a server-based database, you will be prompted with the login dialog box for the database server. The values you enter into the login dialog box are used to build the connection string stored in the file DSN. If you specify a password in the login dialog box, you will be prompted for the password every time you log on to the database. If the account you use to log on to the database doesn’t have a password, you won't be prompted for a password when you log on again.

After you enter the necessary information in the login dialog box, the new file DSN is created. You are then returned to the File Data Source tab of the Select Data Source dialog box, which now includes the file DSN you've just created. You can then select a DSN and connect to the data source. The values you have already entered appear as the default values in the login dialog box.

Note If you are developing a Web application in Microsoft® Visual InterDev™, you should create a file DSN to store the information needed to connect to your database. After you select or create a file DSN, you can add a data connection to the Web project or database project.

After you have added a data connection to your project, you no longer need the file DSN, because all of the necessary connection information is copied from the file DSN and stored with the Web application in the Global.asa file. This type of connection, which derives from a DSN but no longer relies upon it, is called a DSN-less connection. DSN-less connections are especially useful for Web applications because they enable you to move the application from one server to another without recreating the DSN on the new server.


Creating a Machine DSN

A machine data source name (DSN) stores information about a data connection in the Windows® Registry of the computer on which the DSN was created.

Note The information stored in the registry is the same information that is stored in a file DSN. However, you cannot use a machine DSN to create a DSN-less connection as you can a file DSN. For more information about the DSN-less connection, see Creating a File DSN.

In a file DSN, connection information is stored in the Global.asa file. In a machine DSN, the Global.asa file contains a pointer to the information stored in the Windows Registry. Therefore, every computer that uses the project (including the Web server) must have the connection information in exactly the same Registry address. This makes a machine DSN less portable than a file DSN.

However, if you use a machine DSN during development, it is easy to change the database you are working with simply by changing the entry in the Windows Registry; you do not have to change the Global.asa file each time. In addition, machine DSNs are useful if you need to use the same DSN in many different applications on your computer.

To create a new machine DSN

  1. In the Project Explorer, right-click the database project you want to add a data connection to, and then select Add Data Connection.

    Note In Microsoft® Visual C++®, right-click the database project in FileView.

  2. Select the Machine Data Source tab.

  3. Choose New, and then choose whether you want to create a User Data Source or a System Data Source. A user data source is available only to the user who created it. A system data source is available to any user who logs onto the computer. When you have chosen the data source type, choose Next.

  4. Select the driver for which you want to set up a data source, and then choose Next.

  5. Review the information you have entered. If everything is as you want it, choose Finish. If you want to make changes, choose Back.

  6. Follow the instructions for the Create a New Data Source wizard or the dialog box that is displayed. For help with these dialog boxes, choose the Help button.

    For SQL Server data sources, you use the Create a New Data Source wizard. For other data sources, you use various dialog boxes. For example, for Microsoft® Access data sources, you use the ODBC Microsoft Access 97 Setup dialog box, and for Microsoft® FoxPro® data sources, you use the ODBC Visual FoxPro Setup dialog box.

    Note When you specify a database, enter a location that will work not only in the development environment you are using, but also in your final project. For example, if your project involves a database that is accessed from a Web server, use a Universal Naming Code (UNC) to be sure that the database location you specify is accessible from the Web server.

If you've created a machine DSN for a server-based database, you will be prompted with the login dialog box for the database server. You will be prompted again each time you connect to the database using the DSN.


Specifying DSN Parameters

A data source name (DSN) consists of a number of parameters that supply information about the database server to which you're connecting and the ODBC driver you are using. Depending on the type of data connection you are creating, you do not necessarily need to supply a value for every parameter.

The following table describes some common parameters and their values.

Note Individual ODBC drivers may have their own additional parameters which appear in the connection string. For information about specific ODBC driver parameters, see the documentation for that ODBC driver.

Parameter | Description
DRIVER | The type of ODBC driver.
DSN or FileDSN | The name of the data source. The DSN parameter denotes a machine data source. The FileDSN parameter denotes a file data source. However, if the DSN parameter is present in a Web application, the connection is a DSN connection. If this parameter is absent, then the connection is a DSN-less connection.
SERVER | The name of the server or the default directory in which the database resides.
UID | The user ID to use when connecting to the database server at design time.
PWD | The password to use when connecting to the database server at design time. The PWD parameter does not appear in the DSN.
APP | Optional. The name of the software application.
WSID | Optional. The workstation ID of the computer you are working on.
DATABASE | The name of the database you are connecting to.

Note If you’re connecting to a Microsoft® SQL Server™ database, make sure that the DATABASE parameter is present in the DSN. Otherwise you’ll automatically connect to the master database on the server.


Opening a Database Project

You can open a database project when you want to resume your connections to a server database so that you can design database objects or query the database. Before you can open a database project, that project must already exist in the directory where you last saved it.

To open a database project in Microsoft® Visual InterDev™ and Visual J++™

  1. From the File menu, choose Open Project.

  2. In the Open Project dialog box, choose the Existing tab.

  3. Select the database project you want to open and choose OK.

To open a database project in Microsoft® Visual C++®

  1. From the File menu, choose Open Workspace.

    Note In Visual C++, you cannot open a project without first opening the associated workspace.

  2. In the Open dialog box, choose Workspaces (.dsw; .mdp) from the Files of type box.

  3. Select the workspace for the database project you want to open and choose OK.

When you open a database project, the Data View window is added to the project workspace to display the names of database diagrams and database objects, such as tables, views, and stored procedures. You can access and manage database objects in Data View. For more information about using Data View, see Managing Databases in Data View.

You create and open queries in the Project Explorer (FileView in Microsoft Visual C++). For details, see Managing Queries in the Project Explorer.


Removing a Database Project

You can remove a database project from your solution when you want to disconnect from the server database. Removing a database project does not delete the database, but only the connection for the local machine.

To remove a database project from a solution

  1. In the Project Explorer, select the database project you want to remove.

  2. From the File menu, select Remove Project.

    A message box will ask you to confirm this action.

  3. To save changes you have made to the database project, choose Yes. To remove the project without saving changes, choose No.

The database project is removed from the current solution. Neither the database itself nor the database project is deleted. The database project is still available as an existing project and can be added to the solution again or to another solution.

To remove a database project in Microsoft® Visual C++®

  • Select the project in FileView and press the DELETE key.

A message box will ask you to confirm this action.


Managing Databases in Data View

In Microsoft® Visual InterDev™, Visual J++™, Visual C++®, and Visual Basic®, the Data View window displays live editable data from any databases to which you've made a data connection. For each data connection, the Data View window displays the database objects for that database under the database connection node as shown in the figure below.

Data View provides a graphical means of organizing your database objects, including database diagrams, tables, views, triggers, and stored procedures. By double-clicking, dragging and dropping, and using the right-click features, you can open, create, and edit your database objects.

Note Some databases have objects different from those identified here. For more information about the database objects available in your database, see Database Server Considerations and consult your database documentation.

In addition, there are some differences between the Visual Basic, Visual C++, and Visual InterDev, and Visual J++ environments. These have been noted when significant throughout the Visual Database Tools documentation.

The following table provides links to topics specific to the Data View window as well as more detailed topics for each task listed.

To | See
Create, edit, and display database diagrams showing the structure of your database Managing Database Diagrams in Data View

Working in Database Diagrams
Create and edit database tables Managing Database Tables in Data View

Tables
Create and edit views of your database | Working with Database Views in Data View
Create and edit stored procedures using the Visual Database Tools Working with Stored Procedures in Data View

Stored Procedures
Create and edit triggers using the Visual Database Tools Working with Triggers in Data View

Triggers
Create and edit Oracle synonyms, functions, and packages | Working with Oracle Databases


Managing Database Diagrams in Data View

You can open, save, copy, rename, and delete database diagrams from Data View. For each data connection, Data View displays any database diagrams that have been created for the database associated with the data connection. You can expand the Database Diagrams folder and see the tables included in each diagram.

Double-clicking a database diagram icon in Data View opens the diagram. Once you've opened a new or existing database diagram, you can drag tables and columns from Data View to add them to the diagram. You can then change the table's column properties, and define table relationships, indexes, and constraints.

To work with a database diagram in Data View

  1. Expand the Database Diagrams folder and select a diagram to work with or create a new diagram by right-clicking the Database Diagrams folder and choosing New Diagram from the shortcut menu.

  2. Right-click the name of the diagram and choose one of the following options.
    To | Choose
    Open the selected diagram to view or edit it | Open
    Create a new diagram and add it to your project | New Diagram
    Create a duplicate of the selected diagram

    Note Copying a diagram does not create a duplicate of the database objects in the diagram; it merely duplicates the references to those database objects.

    Microsoft® Visual Basic® does not support copying and pasting of database diagrams.

             Copy and Paste
    Remove the selected diagram from Data View and delete it from the dtproperties or MicrosoftDTProperties table in the database

    Note Deleting a diagram does not affect the database objects or data that were contained in the deleted diagram; only the references to those objects are deleted.

             Delete
    Change the name of a diagram in Data View and in the dtproperties or MicrosoftDTProperties table in the database | Rename. Type a new name for the diagram and press ENTER.

For more information about how you can use database diagrams, see Working in Database Diagrams.


Managing Database Tables in Data View

You can use Data View to open, design, edit, copy, and delete tables in your database. For each data connection, Data View displays any tables in the database associated with the data connection. You can expand the Tables folder to see the columns and triggers included in the table.

Double-clicking a table icon in Data View opens the table and displays its data, which you can edit. You can drag a table from Data View to add it to an open database diagram, where you can edit the table's column properties. You can also drag a table to a query in the Query Designer, to add the table to the query definition.

To work with tables in Data View

  1. Expand the Tables folder and select a table to work with or create a new table by right-clicking the Tables folder and choosing New Table from the shortcut menu.

  2. Right-click the name of the table and choose one of the following options.
    To | Choose
    Open the selected table to view or modify the data stored in a table in your database | Open
    Open a table in single-table design mode to view or modify the table definition

    Note This allows you to change the structure of the table: the columns it contains and the column properties

             Design
    Add a new table to the database | New Table. Then define the table in single-table design mode and save it.
    Create a new trigger for the selected table | New Trigger
    Copy a table to the Clipboard as an alternative to dragging the table from Data View into a database diagram or query | Copy
    Remove the selected table from the database

    Note When you delete a table, the table definition, as well as any data stored in that table, is deleted from your database. Delete a table only when you are certain that you no longer need the data that is stored in it.

             Delete

For more information about designing and using tables in the Database Designer, see Tables.

For more information about how you can edit your table data using queries, see Editing Rows in the Results Pane.

For more information about copying and pasting a table into diagrams and queries, see Adding Tables to a Database Diagram and Adding Input Sources.


Working with Triggers in Data View

You can use Data View to create, open, copy, and delete triggers in your database. Because triggers are associated with specific tables, each trigger can be found in the Tables folder with the table the trigger belongs to.

You can expand the Tables folder to see the triggers included in the table. In Data View a special icon [image] indicates a trigger. For example, in the figure below employee_insupd is a trigger associated with the employee table. (For Microsoft® Visual C++®, the trigger icon is different [image].) Double-clicking a trigger icon in Data View opens the trigger in the editor.

To work with triggers in Data View

  1. In the Tables folder, expand the table that contains the trigger or create a new trigger by right-clicking the table and choosing New Trigger from the shortcut menu.

  2. Right-click the trigger and choose one of the following options.
    To | Choose
    Open the selected trigger in the editor | Open
    Remove the selected trigger from Data View and delete it from the database | Delete

For more information about working with triggers, see Triggers.


Working with Database Views in Data View

A view is a virtual table whose contents are defined by a pre-compiled query that is stored and maintained on the database server. A view looks like a real table, with a set of named columns and rows of data. However, a view does not exist as a stored set of data values in a database. Instead, it is a query result set that is maintained on the server and updated each time you open the view. You can use a view to extract and combine just the information you need from one or more existing tables.

Views can be created in most ODBC-compliant databases. The data that you view is stored in the database tables. You can open a view and modify the data that appears inside it. When you modify the data you see in a view, you are actually changing data in the underlying database tables. Changes to data in those tables are automatically reflected in the views derived from them.

For Microsoft® SQL Server™ databases, views are created, edited, and deleted in Microsoft SQL Enterprise Manager. For more information about creating and managing views, see "Creating Views" in SQL Server Books Online. You can also create a view using the View Designer, a tool available with the Microsoft® Visual Database Tools. For details, see Creating Views with the View Designer.

You can use Data View to open, design, edit, and delete views in your database. For each data connection, Data View displays any views in the database associated with the data connection. You can expand the Views folder to see the columns in the views.

Double-clicking a view icon in Data View opens the view and displays its data, which you can edit. You can also use the View Designer to modify a view's definition. The View Designer looks just like the Query Designer, but it creates a view rather than a query when you save your definition.

To work with database views in Data View

  1. Expand the Views folder to select the view you want to work with, or create a new view by right-clicking the Views folder and choosing New View from the shortcut menu.

  2. Right-click the view and choose one of the following options.
    To | Choose
    Open the selected view to display the data in the view as a table, where you can edit it | Open
    Modify the selected view in the View Designer | Design
    Create a new view

    Note In Microsoft® Visual C++®, you can also create a new view using the New Database Item command on the Insert menu

             New View
    Remove the selected view from Data View and delete it from the database | Delete

For more information about views, see Creating Views with the View Designer. For more information about creating queries, see Query Designer.


Creating Views with the View Designer

You can use the View Designer to create a view, which is a virtual table generated by a query. For example, a view might be designed to contain three out of five available columns in a table, created to limit access to certain information.

To create a view

  1. To start the View Designer, right-click the Views node in Data View, and then choose New View.

    The View Designer opens with a blank view with a temporary name.

Note In Microsoft® Visual C++®, you can also create a new view using the New Database Item command on the Insert menu.

  2. Create the query you want to base the view on as you would create any query. Include all the search conditions information that will become part of your view.

    Note Because a view is based on a Select query, you cannot change the query type. For details about creating the query, see Creating Queries.

  3. To save the view and assign it a name, choose Save <new view name> from the File menu. (In Microsoft Visual C++, choose the Save command.) In the Save New View dialog box, type the name for your view, following the naming conventions for your database.

    The new view is added to the list under the Views node in Data View.

If you are working with Microsoft® SQL Server™, you can encrypt a view, which prevents people from viewing or editing it.

To encrypt a view

Caution After you encrypt a view and close it, you will not be able to open and edit it again.

  4. Open the view to encrypt.

    Note In Microsoft Visual C++, open the view in design mode by right-clicking the view and selecting Design. If you open the view with the Open command, the property page will not display the encryption option.

  5. Right-click anywhere in the View Designer except on an input source window in the Diagram pane, and then choose Properties.

  6. Choose Encrypt view, and then choose OK.

The View Designer encrypts your view the next time you save it. You can continue to work with the view until you close the View Designer. After that, you will no longer be able to edit the view, although you will be able to use it as an input source.


Working with Stored Procedures in Data View

You can use Data View to open, execute, debug, copy, delete, and rename stored procedures in your database. For each data connection, Data View displays any stored procedures in the database associated with the data connection. You can expand the Stored Procedures folder to see the parameters for the stored procedures.

Double-clicking a stored procedure icon in Data View opens the stored procedure in the editor.

To work with stored procedures in Data View

  1. Expand the Stored Procedures folder and select the stored procedure you want to work with or create a new stored procedure by right-clicking the Stored Procedures folder and choosing New Stored Procedure from the shortcut menu.

  2. Right-click the stored procedure and choose one of the following options.
    To | Choose
    Open the selected stored procedure in the editor | Open
    Run the stored procedure against the database

    Note Visual Basic does not support executing stored procedures from the Data View window

             Execute (in Microsoft® Visual C++®, choose Run)
    Use the SQL debugger to debug the stored procedure | Debug
    Create a new stored procedure | New Stored Procedure
    Copy the stored procedure to the Clipboard, so you use it to create another stored procedure | Copy
    Remove the selected stored procedure from Data View and delete it from the database | Delete
    Rename the stored procedure | Rename. Type a new name for the stored procedure and press ENTER.

For more information about working with stored procedures, see Stored Procedures.

Debugging Stored Procedures

Many of the applications in the Microsoft® Visual Studio™ collection allow you to debug your stored procedures.

To debug stored procedures in | See
Microsoft® Visual Basic® | The T-SQL Debugger in the Visual Basic documentation.
Microsoft® Visual C++® Enterprise Edition | Debugging SQL in the Visual C++ Enterprise Edition documentation.
Microsoft® Visual InterDev™ | Debugging Stored Procedures and Triggers in the Visual InterDev documentation.


Adding a Stored Procedure to Source Control in Data View

In Microsoft® Visual InterDev™ and Microsoft® Visual J++™, you can add stored procedures to source control from the Data View window. This allows you to manage the stored procedures in your SQL Server database, and ensure that multiple developers can make changes to the stored procedures without losing changes due to overwritten files.

For this release we are supporting only Microsoft® SQL Server™ version 6.5 databases (with at least Service Pack 3) and Microsoft® Visual SourceSafe™.

The following information applies generally to the source control feature for stored procedures:

  • All users work against the same database.

  • When you open a stored procedure, the text is read from the database.

  • The source control library and database should be in synch unless someone has a stored procedure checked out.

  • You are prompted to log in to the source control library whenever you refresh the data connection or refresh the Stored Procedures folder in the Data View window. If your log in fails or if you cancel the dialog box, then Visual InterDev or Visual J++ will treat the stored procedures as if they were not under source control.

  • You are allowed to view a stored procedure in the editor without checking it out from source control. However, the stored procedure is read-only. To edit the stored procedure, you must check it out.

  • The settings on the Source Control tab of the Options dialog box do not affect using source control with stored procedures in the Data View window.

For stored procedures in the Data View window, a subset of the full source control features is available, as described in the procedures below.

In order to utilize any source control features you must place the database under source code control. When you select this option all stored procedures in the database are added to the source control library.

Note You must also have the Visual SourceSafe client files installed on the SQL Server computer. For more information, see "Setup Issues" below.

To add a database to source control

  1. Right-click on the data connection in the Data View window.

  2. Choose the Add to Source Control command.

    The Enable Source Control dialog box is displayed.

  3. Enter the location of your source control database, a project name for your source control project, and a comment if desired.

    Note The source control database location (the Srcsafe.ini file) is relative to your SQL Server database, not to your local computer. In the figure, the C: drive and the path shown are on the computer containing the SQL Server database.

  4. A lock icon is displayed next to each stored procedure in the database, indicating that it is under source control.

  5. New stored procedures added to a database under source control must be manually added to the source control library.

To add a new stored procedure to source control

  1. Right-click the stored procedure in the Data View window.

  2. Choose the Add to Source Control command.

    The lock icon is displayed next to the stored procedure. The stored procedure is read from the database and placed in the source control library.

You can check out any of the stored procedures from the database and edit them in your project.

To check out a stored procedure

  1. Right-click the stored procedure in the Data View window.

  2. Choose the Check Out command.

    A check icon is displayed next to the stored procedure.

When you attempt to check out a stored procedure from source control, both the source control version and the database version are retrieved. These versions are then compared. If they are different, you are prompted for which version to use. You can select the database version (and choose to update the source control version), just use the database version, or just use the source control version.

If you select the source control version, the stored procedure is compiled on the database. If the compile fails, the stored procedure is opened in the editor and marked for editing.

You can also click on the View Differences button and see a window displaying the different text for the source control and database versions of the stored procedure.

After you have checked out and edited a stored procedure, you will want to check the changes back into the source control library. When this is done, the stored procedure is read from the database and updated in the source control library. If the stored procedure is open in an editor and marked for editing (as discussed above, the database compile failed when you tried to check the file out), the Check In command is disabled.

To check in a stored procedure

  1. Right-click the stored procedure in the Data View window.

  2. Choose the Check In command.

  3. Enter a comment for this version of the stored procedure in the source control library if you want.

    The check icon next to the stored procedure is removed.

    Note You always are working against the database. When you check in a file, the latest database version goes into source control.

You can undo a check out if you decide you don't want to save your changes.

To undo a check out

  1. Right-click the stored procedure in the Data View window.

  2. Choose the Undo Check Out command.

    The check icon next to the stored procedure is removed. The lock icon is displayed.

When you elect to undo a check out, an attempt is made to re-synchronize the source control library and the database. The previous version from the source control library is compiled on the database. If an error occurs in compiling, no further action is taken and the lock on source control is cleared.

Note In this case, you're getting the source control version, and replacing the version that you have been modifying, because you decided to undo the check out.

Setup issues

Microsoft Visual InterDev and Microsoft Visual J++ setup will automatically install Visual SourceSafe on your client computer. However, for the source control feature to work, you must install the Visual SourceSafe client software on the computer containing your SQL server.

When you're installing Visual InterDev, make sure to select Visual InterDev Server Setup when this option is offered. This will install the Visual SourceSafe client software on your SQL server.

In addition, the following procedure will help you set up your SQL server to use Visual SourceSafe with stored procedures.

Setting Up Your Computer for Stored Procedure Source Control Through Microsoft Visual SourceSafe

When using source control with stored procedures, the SQL server will be logging into Visual SourceSafe and making the necessary operations on the Visual SourceSafe database. Therefore, it will require appropriate permissions to perform these actions. It is recommended to reduce the security issues by setting the SQL server service to run as a logged on user.

To set the SQL server service to run as a logged on user

  1. Click Start Menu, Control Panel, and run Services.

  2. Select the service MSSQLServer and click the Startup button.

  3. In the Service dialog box, select the option This Account.

  4. In the This Account text box, type a domain and user name (for example, "domain\username") that has access to the server where the Visual SourceSafe software is installed.

  5. Type a password into the Password text box. Click OK.

  6. Stop the MSSQLServer service and then restart it.


Working in the Project Explorer

When you are working with database projects, the Project Explorer allows you to manage queries and SQL scripts. Queries and scripts become part of your project and are stored with other database project files. The Project Explorer displays queries and SQL scripts under the node representing the database in which you created them, as shown in the following figure.

Note In Microsoft® Visual C++®, the Project Explorer is called FileView. From FileView, you can manage queries in much the same way as you can in the Project Explorer. For more information, see FileView in the Visual C++ documentation.

By double-clicking, dragging and dropping, and using the right-click features, you can open, create, and edit your queries and SQL scripts from the Project Explorer.

For information about | See
Creating, running, and editing queries | Managing Queries in the Project Explorer
Creating SQL scripts, including stored procedure scripts, trigger scripts, view scripts, and table scripts. | Working with SQL Scripts


Managing Queries in the Project Explorer

The Project Explorer provides a graphical means of managing the queries in your database project. By double-clicking, dragging and dropping, and using the right-click features, you can open, create, edit, and execute your queries.

Note In Microsoft Visual C++®, the Project Explorer is called FileView. From FileView, you can manage queries in much the same way as you can in the Project Explorer. For more information, see FileView in the Visual C++ documentation.

For details about using the Microsoft Visual Database Tools with database projects, see Working with Database Projects.

If you are working in a database project, you can perform the following tasks from the Project Explorer:

  • Create, modify, execute, and save queries with the Query Designer, which includes a visual query tool, an interactive SQL window, and an output window for viewing and updating result sets.

  • Share queries between applications by:
    • Dragging a saved query file into any editor in your development environment to insert the query's SQL statement into that editor. For example, you can drag a query file onto the Visual Database Tools stored procedure editor to add the SQL statement to a stored procedure, or drag a saved query into the Visual C++® or Visual J++™ editor to add the SQL statement to your ODBC code.

    • Dragging a query into any OLE container, such as a Microsoft® Excel spreadsheet, or paste it into an application or component that isn't an OLE container. For example, you can paste the SQL statement into Microsoft® Access as a pass-through query without having to test it again.

    Note This drag-and-drop feature is not available in Microsoft® Visual Basic®. You can, however, paste the SQL statement into your code in a Visual Basic project to set the SQL property of a Remote Data Objects (RDO) Command object.

To add a query in the Project Explorer

  1. Expand the project name to show the names of all the data connections currently defined for your project.

  2. Right-click the data connection for the database you want to work with, and then choose Add Query from the shortcut menu.

Tip You can also right-click the project name, and then select Add Item to open the Add Item dialog box.

  3. In the Add Item dialog box, choose Database Query.

  4. In the Name box, type in a name for the query, and then click Open.

    The Query Designer opens. For details about creating the query, see Creating Queries.

After creating the query in the Query Designer, you can save it. When you save a query:

  • The query is added to or updated in the list of queries under the data connection node [image] in the Project Explorer.

  • Changes to the query definition are saved in a file in your project directory.

  • Changes to the layout of the query diagram or the configuration of the panes inside the Query window are saved with the query definition in the query file.

To save a query

  • From the File menu, choose Save or Save As, and then enter a name for your query.

The Query Designer saves the SQL statement in a file, along with the window layout and any parameter information you have specified. By default, the query is saved in the project directory (the directory you specified when you created the database project), but you can specify any location available to your computer.

Note Queries are not stored as part of the database that you are querying. Instead, they are stored as stand-alone files on your computer or on the network you are connected to.

After creating a query, you can run it or open it again for further editing. If you no longer need a query, you can also delete it from the project.

To run, edit, or delete a query in the Project Explorer

  1. Expand the project name to show the names of all the data connections currently defined for your database project, and then expand the data connection for the database you want to use.

  2. Right-click the query to work with, and then choose one of the following options.
    To | Choose
    Edit the query | Design
    Run the query | Open (or double-click the name of the query)
    Delete the query | Delete
    Rename the query | Rename


Working with SQL Scripts

You can create SQL script files that contain procedures that you frequently run against databases, as well as scripts to create database objects. An SQL script file, similar to a stored procedure, is a text file containing commands to be executed. SQL scripts are useful for database administrators who need to track the changes made to a database.

The Project Explorer provides a graphical means of managing your SQL scripts. By double-clicking, dragging and dropping, and using the right-click features, you can open, create, edit, and execute your queries.

Note For details about using the Microsoft® Visual Database Tools with database projects, see Working with Database Projects.

SQL script files are saved with your database project on your local computer instead of residing on the database server, like a stored procedure. You can add an SQL script file into multiple database projects and run it against multiple databases.

To | See
Create a new SQL script and add it to a project | Creating SQL Scripts
Automatically generate an SQL change script showing all changes made to the database | Saving a Change Script
Run an SQL script | Executing an SQL Script
Create an SQL script file in different SQL dialects, including Microsoft® SQL Server™ Transact-SQL and Oracle SQL+ | Changing the SQL Dialect of an SQL Script


Creating SQL Scripts

You can create and modify database objects in a database project using SQL script files. These files contain DDL (data definition language) SQL statements that define and modify database objects.

Note In Microsoft® Visual InterDev™, you can use the Copy SQL Script command in the Data View window to create a SQL script that will create the selected database object when added to a database project and executed. For more information, see Populating a Database Project.

To create a new SQL script file and add it to a project in Visual InterDev or Visual J++™

  1. Expand the database project folder in the Project Explorer.

  2. Right-click the data connection and choose Add SQL Script.

    The Add Item dialog box is displayed.

    Tip You can also right-click the project name and select Add Item to open the Add Item dialog box.

  3. Select SQL Script in the right pane. Enter a name for the SQL script in the Name box if you want. Click Open.

    The SQL Editor window is displayed and the SQL script is added to the Project Explorer under the data connection node.

  4. Enter SQL statements in the SQL Editor window that define the database objects you want to add to this database project. Follow the conventions of your database. For more information, see your database documentation.

You can also add specialized SQL scripts to your database project using the templates provided with the Visual Database Tools. You can select an SQL script file that creates a table, view, stored procedure, or trigger. You can use these supplied SQL script files as templates for creating your own SQL scripts

To create specialized script files based on templates in Visual InterDev or Visual J++

  1. Expand the database project folder in the Project Explorer.

  2. Right-click the data connection and choose Add SQL Script.

    The Add Item dialog box is displayed.

    Tip You can also right-click the project name and select Add Item to open the Add Item dialog box.

  3. Select Table Script in the right pane. Enter a name for the SQL script in the Name box if you want. Click Open.

    The SQL Editor window is displayed and the SQL script is added to the Project Explorer under the data connection.

  4. Modify the existing SQL statements in the SQL Editor window to define the database object you want to add to this database project. Follow the conventions of your database. For more information, see your database documentation.

Once you've created the SQL script you want, you can execute it to create or modify database objects using the SQL statements in the SQL script file. You can execute the script file from Project Explorer using the Execute command or by double-clicking the script name in the SQL Editor. For more information, see Executing an SQL Script.

Note An SQL script must be executed against a database. You can execute an SQL script against any database for which there's a data connection in your database project.

You can also modify database objects in the Data View window using the Visual Database Tools. For more information, see Working with Database Projects.

To create a new SQL script and add it to a project in Visual C++®

  1. From the File menu, choose New.

  2. Choose the Files tab, and then select ODBC Script File.

  3. Check Add to Project.

  4. Select the name of the database project you want to add the file to.

  5. In the File Name box, type a name for the script file, and then choose OK.

  6. Enter the SQL script, and then save it by choosing Save or Save As from the File menu.

After you have added an SQL script file to the project, you can add commands to the file. For example, you can create the following SQL script to display in the Output window the version number of a Microsoft® SQL Server™ database:

SELECT @@Version

You can run this script against any Microsoft SQL Server database.

You can also create an SQL script to execute a stored procedure. For example, in a Microsoft SQL Server database, you can create an SQL script that runs a built-in stored procedure, such as sp_help or sp_who.

To create an SQL script that executes a stored procedure

  1. Create a new SQL script file.

  2. Type Exec followed by the name of the stored procedure to execute, as in the following two commands:
    Exec sp_who
Exec sp_help
  3. Save the script.


Executing an SQL Script

After creating an SQL script, you can run it to update or modify your database.

To execute an SQL script in Microsoft® Visual InterDev™ or Visual J++™

  1. From the Project Explorer, double-click the SQL script file to open it in the SQL editor.

  2. In Data View, select the database you want to run the script against.

  3. Right-click the open script file in the source editor, and then choose Execute.

    Note If the Execute command is not enabled, make sure that Data View is active, that you've selected the name of the database in Data View, and that the SQL script file is open in the SQL editor.

If the SQL script runs successfully, the result set appears in the Output window.

To execute an SQL script in Microsoft® Visual C++®

  1. From FileView, double-click the SQL script file to open it in the SQL editor.

  2. In Data View, select the database you want to run the script against.

  3. Right-click the open script file in the source editor, and then choose Run.

    Note If the Run command is not enabled, make sure that Data View is active, that you've selected the name of the database in Data View, and that the SQL script file is open in the SQL editor.

If the SQL script runs successfully, the result set appears in the Output window.


Changing the SQL Dialect of an SQL Script

You can create an SQL script file in different SQL dialects, including Microsoft® SQL Server™, Transact-SQL, and Oracle SQL+. After you have created the script, you can change its SQL dialect (if necessary), a choice that is useful if you import the script into a project that uses a different database.

In Microsoft® Visual InterDev™ and Visual J++™, the SQL dialect used is automatically based on the type of database. Visual InterDev and Visual J++ store the SQL scripts with the data connections. If you create an SQL script for a database connection or move an SQL script to that data connection, the correct SQL dialect is automatically used for that database type.

In Microsoft® Visual C++®, you can change the SQL dialect of a SQL script.

To change the SQL dialect for an SQL script file in Microsoft Visual C++

  1. From the Project Explorer (FileView in Microsoft Visual C++), double-click the SQL script file to open it in the source editor.

  2. Right-click the file in the SQL editor and choose Properties.

  3. From the Language list, select one of the available SQL dialects.

    Your SQL script will now use the SQL dialect you selected.


Database Server Considerations

The Microsoft® Visual Database Tools provide a consistent visual interface that allows you to design and query all databases in the same way. However, there are many differences in the features supported by individual databases and in how databases implement database management commands.

For the most part, when using the Database Designer or Query Designer, you do not need to be aware of specific differences between databases. However, in a few cases you might find it helpful to know about the underlying database. For example, when you are working with the Database Designer, it is helpful to understand what data types your database supports. Similarly, the Query Designer creates slightly different SQL commands depending on whether you are working with Microsoft® SQL Server™, Oracle, or another database.

Note These topics are not intended to explain SQL Server databases. Instead, they highlight features unique to SQL Server that are exposed through the Visual Database Tools. For more details about using SQL Server databases, consult your SQL Server database documentation.

For more information about | See
Special considerations for using the Visual Database Tools with SQL Server databases | Working with SQL Server Databases
Special considerations for using the Visual Database Tools with Oracle databases | Working with Oracle Databases


Working with SQL Server Databases

The Microsoft® Visual Database Tools work transparently with SQL Server databases by producing SQL Server-specific SQL commands, recognizing SQL syntax unique to SQL Server, and so on.

In a few instances, however, you will find it useful to know how the Visual Database Tools differ when you are working with SQL Server databases. For example, you might find it helpful to understand how the Query Designer will treat SQL Server-specific syntax if you enter an SQL command yourself, or what operators you can use.

For more information about | See
Issues and notes for using the Database Designer with SQL Server databases | Database Designer Considerations for SQL Server Databases
Issues and notes for using the Query Designer with SQL Server databases | Query Designer Considerations for SQL Server Databases


Database Designer Considerations for SQL Server Databases

If you are creating database diagrams using Microsoft® SQL Server™, you can take advantage of features specific to that server. The following guidelines outline differences you will notice in the Database Designer when you work with SQL Server, and provide information about SQL Server-specific features that you can use.

Below you will find information about:

  • Case Sensitivity

  • Changing Column Properties

  • Enforced and Unenforced Table Relationships

Case Sensitivity

Column and table names in a SQL Server database can be stored in uppercase letters, lowercase letters, or a combination of both. For example, a column name can appear as "LASTNAME," "LastName," or "lastname."

Depending on how SQL Server was installed, databases can be case-sensitive or case-insensitive. If a database is case-sensitive, you must enter owner, table, and column names using the correct combination of uppercase and lowercase characters. If the case of the name you provide does not match exactly, SQL Server returns an error reporting an "invalid object name."

The objects in the Data View window always accurately reflect the case-sensitivity of your server. However, when entering column names in a database diagram, you must be careful to match names to the way they will be interpreted by the server.

If the server was installed with a case-insensitive option, you can enter database object names using any combination of uppercase and lowercase characters.

Tip To determine the case sensitivity of a server, execute the stored procedure sp_server_info, and then examine the contents of row 18. If the server has been installed with the case-insensitive setting, the option for sort_order will be set to nocase.

Changing Column Properties

For information on the procedure you use to set column properties, see Setting Column Properties.

Although the procedure for setting column properties is similar regardless of the database you are using, the following items contain information specific to Microsoft SQL Server databases.

  • Default Values for Data Types

  • Changing the Data Type Assigned to a Column

  • Changing the Column Length

  • Changing the Column Precision

  • Changing the Column Scale

  • Changing the Null Option Assigned to a Column

  • Assigning a Default Value to a Column

  • Redefining a Global Default

  • Changing a Column’s Identity Properties

Default Values for Data Types

The following default values are automatically added for the new column:

Data Type | Description | Default value
Column Name | The name of a column in a table. Column names must conform to your database rules for identifiers and must be unique in the table. | Blank
Datatype | The data type of the column. System- or user-defined data types are acceptable. | Character (char)
Length | The maximum number of digits (for numeric data types) or characters allowed for values in the column. | 10
Precision | The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. | 0
Scale | The maximum number of decimal digits that can be stored to the right of the decimal point. This value must be less than or equal to the precision. | 0
Allow Nulls | Whether or not the column can accept null values. | Yes (checked)
Default Value | The value that will be inserted into the column if the user does not make an entry. Default values are ignored for columns with a timestamp data type. If you do not define a default value and a column allows nulls, NULL will be inserted. | Blank
Identity | Whether or not the column will generate incremental values for new rows based on the Identity Seed and Identity Increment settings. | No (not checked)
Identity Seed | The value assigned to the first row in the table. If left blank, this setting default is 1. | Blank
Identity Increment | The value which is added to the Identity Seed and assigned to the second row in the table. Each subsequent row is increased by this value. If left blank, this setting default is 1. | Blank

Changing the Data Type Assigned to a Column

A column's data type determines what kind of data can be stored in the column. A list of system-defined data types appears in the Datatype property column in Column Properties view.

You can choose the appropriate data type for the information you want to store in the column. If user-defined data types exist for your database, they appear at the end of the Datatype list. The system-defined data type that corresponds to the user-defined data type appears in parentheses at the end of the user-defined data type name. For example: "id (varchar)."

Special considerations for assigning a user-defined data type to a column

  • Selecting a data type automatically sets the length, precision, and scale for the column based on the data type’s definition. You cannot change these settings for user-defined data types.

  • You can change the Allow Nulls setting only if the user-defined data type allows null values.

  • When you select a user-defined data type, the Default Value setting is blank, even if a bound default is defined for the data type. You can check whether a bound default exists by saving the table and reloading it into memory. When you reopen the table, the bound default will appear in the Default Value cell. If you try to set a default value for a column that already has a bound default, an error message will prompt you to remove your entry.

For information about creating user-defined data types in Microsoft SQL Server, see "Creating User-Defined Datatypes" in SQL Server Books Online or Database Developer’s Companion.

Note Changing the data type recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Caution If this column is related to columns in other tables, then the data type of the related columns must also be changed to preserve referential integrity. When you save the table or diagram, the Datatype Change Required dialog box enables you to automatically change the data type of the related columns.

Microsoft SQL Server Data Types

Data type | Description
binary Holds a maximum of 255 bytes of fixed-length binary data; default length is 10.

Columns of this type are accessed somewhat faster than varbinary columns because they use a fixed storage length. Choose binary when you think the values entered in this column will be consistently close to the same size. You can create relationships between binary columns and varbinary columns.
bit Holds either 1 or 0. Integer values other than 1 or 0 are accepted but are always interpreted as 1. Storage size is 1 byte. Multiple bit types in a table can be collected into bytes. For example, 7-bit columns fit into 1 byte; 9-bit columns take 2 bytes.

Columns of this type cannot be NULL and cannot have indexes on them. Choose bit for true/false or yes/no types of data.
char Holds a maximum of 255 characters; default length is 10.

Columns of this type are accessed somewhat faster than varchar columns because they use a fixed storage length. Choose char when you think the data entries in the column will be consistently close to the same size. You can create relationships between char columns and varchar columns.
datetime Stored in two 4-byte integers: 4 bytes for the number of days before or after the base date of January 1, 1990, and 4 bytes for the number of milliseconds after midnight. The date segments of datetime values that represent dates prior to the base date are stored as negative values.

Data values for datetime range from January 1, 1753, to December 31, 9999, to an accuracy of one three-hundredth second, or 3.33 milliseconds. Microsoft SQL Server rejects all values it cannot recognize as dates between 1753 and 9999.

You can omit either portion of the value, but if you omit both, the datetime default of January 1, 1900, 12:00:00:000AM is supplied. If you omit the time portion of a datetime value, the default (12:00:00:000AM) is supplied. If you omit the date portion, the default (Jan 1 1900) is supplied.
decimal An exact numeric data type that holds values from 1038 - 1 through -1038. The Precision property specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The Scale property specifies the maximum number of decimal digits that can be stored to the right of the decimal point; it must be less than or equal to the precision.

Storage size varies according to the specified precision, and ranges from a minimum of 2 bytes to a maximum of 17 bytes. As a general rule, calculate the number of storage bytes required by dividing the precision by 2. For example, precision between 17 and 19 requires 9 storage bytes. For more information, refer to your database documentation.
float Holds positive or negative floating-point numbers. By default, this data type has a 15-digit precision. The range of positive values is approximately from 2.23E - 308 through 1.79E 308; zero can be stored; and the range of negative values is approximately from -2.23E - 308 through -1.79E 308. Storage size is 8 bytes. All arithmetic operations except modulo are available with float.

For float data with an exponential component, enter a number (with or without a decimal point and a positive or negative sign), followed by e or E, followed by an integer. The value represented by a float is the product of the first number and 10 to the power of the second number.
image A variable-length data type that holds a maximum of through 2E31 - 1 (2,147,483,647) bytes of binary data; default length is 16. The image data type cannot be used for variables or parameters in stored procedures.

When image data is entered with an odd number of bytes (but fewer than 255), it is padded with a leading zero. You cannot insert image values with an odd number of characters greater than 255 bytes.
int | Holds whole numbers from -2E31 (-2,147,483,648) through 2E31 - 1 (2,147,483,647). Storage size is 4 bytes.
money | Stores monetary values from -922,337,203,685,477.5808 through +922,337,203,685,477.5807, with accuracy to a ten-thousandth of a monetary unit. Money values are represented as double-precision integers. Storage size is 8 bytes.
numeric Identical to the decimal data type in the Microsoft SQL Server 6.5 implementation. Both are provided for ANSI compatibility. See decimal data type, above.

Caution You should use either decimal or numeric for exact numeric data types within a database to avoid conversion between decimal and numeric data types, and to allow relationships between columns with exact numeric data types.
real | A floating point column similar to float (see above). This column has 7-digit precision. The range of positive values is approximately from 1.18E - 38 through 3.40E 38; zero can be stored; and the range of negative values is approximately from -1.18E - 38 through -3.4E 38. Storage size is 4 bytes.
smalldatetime | A date and time data type that is less precise than datetime. Storage size is 4 bytes, consisting of one small integer for the number of days after January 1, 1900, and one small integer for the number of minutes past midnight. Data values for smalldatetime range from January 1, 1900, through June 6, 2079, with accuracy to the minute.
smallint | Holds whole numbers from -2E15 (-32,768) through 2E15 - 1 (32,767). Storage size is 2 bytes.
smallmoney | Stores monetary values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit. When smallmoney values are displayed, they are rounded up to two places.
sysname | Is the same as varchar(30) and should be assigned only to a column that references the name of a database object in the Microsoft SQL Server system tables such as sysbobjects.
text | Is a variable-length data type that can hold a maximum of 2E31 - 1 (2,147,483,647) characters; default length is 16.
timestamp Automatically updated every time a row containing a timestamp column is inserted or updated. Values in timestamp columns are not datetime data, but binary(8) or varbinary(8), indicating the sequence of Microsoft SQL Server activity on the row. A table can have only one timestamp column.

The timestamp data type has no relation to the system time — it is simply a monotonically-increasing counter whose values will always be unique within a database.
tinyint | Holds whole numbers from 0 through 255. Storage size is 1 byte.
varbinary A variable-length binary data type that holds a maximum of 255 bytes of variable-length binary data; default length is 50. Storage size is the actual length of the data entered.

Choose varbinary when you expect null values or a variation in data size. You can create relationships between binary columns and varbinary columns.
varchar Holds a maximum of 255 characters; default length is 50. Storage size is not fixed with a varchar column. Instead, storage is defined by the actual size of the data entered (ignoring all trailing blanks).

Choose varchar when you expect null values or a wide variation in data size. You can create relationships between char columns and varchar columns.

Changing the Column Length

When you select a data type, the column length is automatically defined. You can reset the length property for a column with a data type of binary, char, varbinary, or varchar if you want to increase or decrease the length of acceptable values in that column. For columns with other data types, the length is derived from the data type.

Note Changing the column length recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Default Column Lengths for Microsoft SQL Server Data Types

Data type | Default length | Range of allowable length values
binary | 10 | 1 - 255
bit | 1 |
char | 10 | 1 - 255
datetime | 8 |
decimal | 9 |
float | 8 |
image | 16 |
int | 4 |
money | 8 |
numeric | 9 |
real | 4 |
smalldatetime | 4 |
smallint | 2 |
smallmoney | 4 |
sysname | 30 | 1 - 255
text | 16 |
timestamp | 8 |
tinyint | 1 |
varbinary | 50 | 1 - 255
varchar | 50 | 1 - 255

Changing the Column Precision

For most data types, the column precision is automatically defined. You can change the column precision for the decimal and numeric data types if you want to redefine the maximum number of digits these columns use. The precision of a numeric column refers to the maximum number of digits used by the selected data type. The precision of a non-numeric column generally refers to either the maximum length or the defined length of the column.

The Database Designer prevents you from changing the precision of a column that does not have one of these assigned data types.

Note Changing the column precision recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Changing the Column Scale

When you select a data type, the column scale by default is set to 0. The scale of a numeric column refers to the maximum number of digits to the right of the decimal point. For columns with approximate floating point numbers, the scale is undefined because the number of digits to the right of the decimal point is not fixed.

You can change the scale for a numeric or decimal column if you want to redefine the number of digits that can appear to the right of the decimal point.

Note Changing the column scale recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Changing the Null Option Assigned to a Column

For each column in your table, you can specify whether to allow null values or disallow null values. A null value, or NULL, is not the same as zero (0) or blank; NULL means that no entry has been made. Its presence usually implies that the value is either unknown or undefined. For example, a null value in the price column of the titles table of the pubs sample database does not mean that the book has no price; it means that the price is unknown or has not been set.

If null values are not allowed, the user entering data in the table must enter a value in the column or the table row cannot be accepted in the database.

Note You cannot change this property on a primary key column. If Allow Nulls is not checked, but null values are stored in that column, Microsoft® SQL Server™ will generate an error message when you try to save the table. Also, Identity columns can't have null values.

Changing the null option on a new, non-key column recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Assigning a Default Value to a Column

For each column in your table, you can specify a default value that will be entered in the column if the user leaves it blank. If you do not assign a default value and the user leaves the column blank, then:

  • If you set the option to allow null values, NULL will be inserted into the column.

  • If you did not set the option to allow null values, the column will remain blank.

For details on setting the Allow Nulls option, see Changing the Null Option Assigned to a Column.

For text strings, enclose the value in single quotation marks ('); do not use double quotation marks (") because they are reserved for quoted identifiers. For example, type: 98036 or 'Paris, France'.

If your entry in the Default Value column replaces a bound default (which is shown without parentheses), the default will be unbound and the new value will replace it.

Redefining a Global Default

A global default is one that is defined for a specific database and is shared by columns of different tables. For example, suppose several of your tables have a quantity column. You can define a global default in your database that inserts a value of 1 in the quantity column whenever the user leaves that column blank in any table.

If a global default is bound to a column, you can specify a different default value for that column in a specific table. In such a case, the existing global default is unbound from the column before the new default value is bound to the column.

To redefine a global default

  1. In your database diagram, assign a new default value to the column you want to change.

    For details about assigning default values, see Assigning a Default Value to a Column.

  2. A message prompts you to permanently unbind the existing default in order for the new default to be applied. Choose OK.

Changing a Column’s Identity Properties

You can change the identity properties of a column if you want to redefine the sequential numbers that are automatically generated and stored in that column when new rows are added to the table. You can set the identity properties on only one column per table.

Columns that have the Identity property contain system-generated sequential values that uniquely identify each row within a table (for example, employee identification numbers). When inserting values into a table with an identity column, Microsoft SQL Server automatically generates the next identifier based on the last used identity value (the Identity Seed property) and the increment value (the Identity Increment property) specified during the creation of the column.

The Identity property can be set only for a column with a data type of decimal, int, numeric, smallint, or tinyint; it must not allow null values; and it must not be bound by a default constraint.

To change a column’s identity properties

  1. In your database diagram, select the table in which you want to change the identity properties of a column.

  2. If you're not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. If the Allow Nulls property is set, clear the check box.

  4. Check the box inside the Identity cell for the column whose values you want to automatically increment.

Note Only one column per table can be defined as an identity column.

  5. Type a value in the Identity Seed cell. This value will be assigned to the first row in the table. If you leave this cell blank, the value 1 will be assigned by default.

  6. Type a value in the Identity Increment cell. This value is the increment that will be added to the Identity Seed for each subsequent row. If you leave this cell blank, the value 1 will be assigned by default.

For example, suppose you want to automatically generate a 5-digit Order ID for each row added to the orders table, beginning with 1000 and incremented by a value of 10. To do this, you would check the Identity property box, type an Identity Seed of 1000, and type an Identity Increment of 10.

If you change any of the identity properties for a table, the existing identity values will be preserved. Your new settings apply only to new rows that are added to the table.

Note If an identity column exists for a table with frequent deletions, gaps can occur between identity values. If you want to avoid such gaps, do not use the Identity property.

Enforced and Unenforced Table Relationships

In SQL Server, the following options are available when enforcing referential integrity:

For details about this option | See
Check existing data on creation | Checking Existing Data When Creating a Relationship
Enable relationship for INSERT and UPDATE statements | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements
Enable relationship for replication | Disabling a Foreign Key Constraint for Replication


Query Designer Considerations for SQL Server Databases

If you are creating queries using Microsoft® SQL Server™, you can take advantage of features specific to that server. The following guidelines outline differences you will notice in the Query Designer when you work with SQL Server, and provide information about SQL Server-specific features that you can use.

Below you will find information about:

  • SQL Server Version

  • SQL Syntax

  • Identifying Database Objects

  • Using Quotation Marks

  • Case Sensitivity

  • Creating Aliases

  • Using Operators in Expressions

  • Entering Keywords in the Grid and SQL Panes

  • Entering Currency Values

  • Using DISTINCT

  • Creating Outer Joins

  • Entering Blanks

  • Including Optimizer Hint Comments

  • ANSI to OEM Character Conversion

  • Unsupported and Partially Supported Query Types

SQL Server Version

The Query Designer is designed to support version 6.5 of the Microsoft SQL Server, but is fully compatible with earlier versions as well. If you are using a version of SQL Server earlier than 6.0, the Query Designer will not recognize SQL Server-specific features (such as syntax elements or functions). Instead, the Query Designer will recognize only standard ODBC syntax.

SQL Syntax

When the Query Designer builds a statement in the SQL pane, it will use syntax specific to SQL Server whenever possible. For example, database objects such as tables and views are qualified using SQL Server owner names.

You can also type SQL Server-specific syntax in the SQL pane yourself. In some cases when you verify a query, the Query Designer converts server-specific syntax to ANSI standard syntax. However, the changed query will always return the same results.

Identifying Database Objects

When you enter the names of database objects (tables, views, and columns) in the SQL pane, you must provide sufficient information for SQL Server to identify the object you want. Database objects are identified with unique names that consist of up to three parts (for tables and views) or four parts (for columns):

database.owner.table

database.owner.table.column

In general, you need to provide only enough qualifiers to uniquely identify the object you want to work with. For example, if you are working with a column called price in the titles table in the current database, you can simply reference the column by name, as in this SQL statement:

SELECT price
FROM titles

However, if you are working with two tables such as orders and products, and each has a column called price, you must qualify references to the column with the appropriate table name, as in this example:

SELECT products.prod_id, orders.price
FROM orders INNER JOIN products ON
 orders.prod_id = products.prod_id

When you use the Diagram pane and Grid pane to work with tables in the current database, the Query Designer automatically adds owner and table qualifiers for you. If you are not the owner of a table that you are working with, the owner’s name will appear in the table names. For example, if you work in the pubs database, the owner name dbo will appear in front of table names. If you are working with multiple tables, the Query Designer adds table name qualifiers to column names.

For compatibility with other databases, you can use [ and ] around identifier names in the SQL pane. When the SQL statement is reformatted, [ and ] are replaced with double quotation marks ("), which are used to mark database identifiers.

Using Quotation Marks

The standard delimiters for literal strings in SQL are single quotation marks ('). By default, SQL Server reserves double quotation marks (") as delimiters for database objects (see Identifying Database Objects, above).

The SQL Server ODBC driver supports a Quoted Identifiers setting for the session or connection. If this setting is on, double quotation marks are interpreted as delimiters for identifiers. However, if you turn this setting off, double quotation marks are interpreted instead as delimiters for literal strings.

To avoid ambiguity, the Query Designer always sets Quoted Identifiers on, so that double quotation marks are always interpreted as database object delimiters. If you have previously turned Quoted Identifiers off, the Query Designer overrides your setting.

Therefore, in the Query Designer, always use single quotation marks to enclose string literals. Use double quotation marks only as needed for database objects delimiters.

Case Sensitivity

Text information in a SQL Server database can be stored in uppercase letters, lowercase letters, or a combination of both. For example, a last name can appear as "SMITH," "Smith," or "smith."

Depending on how SQL Server was installed, databases can be case-sensitive or case-insensitive. If a database is case-sensitive, when you search for text data, you must construct your search conditions using the exact combination of uppercase and lowercase letters. For example, if you are looking for a name such as "Smith," you cannot use the search conditions "=smith" or "=SMITH."

In addition, if the server was installed as case-sensitive, you must provide database, owner, table, and column names using the correct combination of uppercase and lowercase characters. If the case of the name you provide does not match exactly, SQL Server returns an error reporting an "invalid object name."

When you create queries using the Diagram and Grid panes, the Query Designer will always accurately reflect the case-sensitivity of your server. However, if you enter queries in the SQL pane, you must be careful to match names to the way they will be interpreted by the server.

If the server was installed with a case-insensitive option, you can enter database object identifiers and search conditions using any combination of uppercase and lowercase characters.

Tip To determine the case sensitivity of a server, execute the stored procedure sp_server_info, and then examine the contents of row 18. If the server has been installed with the case-insensitive setting, the option for sort_order will be set to nocase.

Creating Aliases

In the SQL pane, you can use the = operator to specify an alias, as in this example:

SELECT tax = price * .1
FROM table

When you change panes or execute the query, the SQL statement is reformatted and the = is replaced with AS.

Using Operators in Expressions

The SQL Server supports all standard operators for expressions, including % for modulus. In addition, you can use the following bitwise operators in expressions:

Operator | Meaning
& | BITAND
| | BITOR
^ | BITXOR
~ | BITNOT

Entering Keywords in the Grid and SQL Panes

The Query Designer supports the use of certain SQL Server constants, variables, and reserved column names in the Grid or SQL panes. Generally, you can enter these values by typing them in, but the Grid pane will not display them in drop-down lists. Examples of supported names include:

  • IDENTITYCOL If you enter this name in the Grid or SQL pane, the SQL Server will recognize it as a reference to an auto-incrementing column.

  • Predefined global values You can enter values such as @@CONNECTIONS and @@CURSOR_ROW into the Grid and SQL panes.

  • Constants (niladic functions) You can enter constant values such as CURRENT_TIMESTAMP and CURRENT_USER in either pane.

  • NULL If you enter NULL in the Grid or SQL panes, it is treated as a literal value, not a constant.

Entering Currency Values

In the Grid pane, to specify that you want data interpreted as money, precede the value with $ or $- (for negative values). Do not include a comma or other delimiter to indicate thousands. Formatting values this way alerts the Query Designer that you are entering values to be treated as or compared to data in money or smallmoney type columns. Values are rounded to the nearest hundredth of a unit.

You can use $ no matter what currency you are working with. When a query displays values from money columns in the Results pane, it does not include the $ prefix. Depending on the setting in the Windows Regional Settings dialog box, currency data might or might not include a comma or other delimiter for thousands.

Using DISTINCT

If you are working with SQL Server version 6.5 or earlier, using the DISTINCT keyword creates a query that cannot be updated in the Results pane.

Creating Outer Joins

In the SQL pane, you can use the SQL Server-specific *= and =* operators to specify an outer join. When you change panes or execute the query, the Query Designer reformats your SQL statement, and replaces *= with LEFT OUTER JOIN and =* with RIGHT OUTER JOIN.

Entering Blanks

In SQL Server, two single quotation marks are treated as a single space. For example, you can use quotation marks in the following expression: 'abc' + '' + 'def'. The resulting value would be 'abd def'.

Including Optimizer Hint Comments

If you are entering a query directly in the SQL pane, you can add optimizer hints to specify the use of specific indexes, locking methods, and so on. However, when reformatting the contents of the SQL pane, the Query Designer might not maintain these comments. Optimizer comments are not represented graphically.

For more details about optimizer hints, refer to the Microsoft SQL Server documentation.

ANSI to OEM Character Conversion

Data containing extended characters — that is, characters outside the ASCII range 32 (space) to 126 (~), including international characters such as "ä," "ç," "é," "ñ," and "ß" — can require special handling when you are working with SQL Server.

The representation of extended characters in a result set depends on the code page in use. A code page is a character set that a computer uses to interpret and display data properly. Code pages usually correspond to different platforms and languages and are used in international applications. For example, the ASCII value 174 might appear as the symbol "®" in one code page but as a chevron character in another code page.

In general, code pages are divided into ANSI code pages and OEM code pages. ANSI code pages, in which high-numbered ASCII values represent international characters, are used in Windows. OEM code pages, in which in which high-numbered ASCII values represent line-drawing and punctuation characters, were designed for MS-DOS®.

When data is entered into a SQL Server database, ODBC settings on the local (client) computer specify whether the data is stored in ANSI or OEM format. The option is specified using the Convert OEM to ANSI Characters option in the ODBC SQL Server Setup dialog box.

By default, this option is not selected for the SQL Server ODBC driver, a choice which causes the data to be stored in ANSI format. However, if this option has been selected, the ODBC driver converts high-numbered ASCII characters to OEM characters. For example, if the OEM conversion option is set and you enter the name "Günther" in a column and then save the row, the character "ü" will be converted to another character before the row is stored in the database.

The results of queries that you create in the Query Designer are affected by the format in which extended-character data is stored in combination with the setting of the OEM conversion option in the ODBC SQL Server Setup dialog box. Depending on these variables:

  • You might not be able to search for data that includes high-order ASCII characters.

  • Your query results might appear in the Results pane with incorrect characters substituted for high-order ASCII characters.

In general, if data is stored in OEM format, you should set the OEM conversion option so the data will display properly and so you can search it. If data is stored in ANSI format (that is, it was not converted to OEM format) but you have set the OEM conversion option, the data will not display properly and you will not be able to search for it.

To determine whether data was stored in OEM format, you can use a query to display the contents of the table or tables you are working with. If extended characters appear incorrect, the OEM conversion setting is probably wrong. Close the query and the project, change the setting in the ODBC SQL Server Setup dialog box, and then open the project and query again.

Unsupported and Partially Supported Query Types

Some types of legal SQL Server queries cannot be represented graphically in the Query Designer. You can still enter them in the SQL pane, and they will execute correctly. However, the Query Designer will display the Query Definitions Differ dialog box and report an error when you execute your query or change panes.

The following types of SQL Server queries are not supported graphically:

  • Queries using INTERSECT

  • Queries using MINUS

  • Queries using UNION [ALL]

  • Queries using CASE

  • Any data definition (DDL) query, including CREATE TABLE, ALTER TABLE, CREATE PROCEDURE, ALTER PROCEDURE, and so on. CREATE VIEW and ALTER VIEW queries are not supported graphically, but you can use the View Designer to create and edit views.

  • Update and Delete queries that include an extra FROM clause (FROM table FROM table) that specifies the list of rows to update or delete.

The following types of queries cannot be represented graphically, so you must enter them in the SQL pane. They do not result in errors when you execute them or change panes.

  • Queries using the FOR BROWSE clause

  • Queries that include TSEQUAL and UPDATE as a search condition

  • Queries including CURRENT OF


Working with Oracle Databases

The Microsoft® Visual Database Tools have been designed to work with Oracle databases transparently — you can design database diagrams, queries, and views in the same way you would for any database. In addition, the tools are Oracle-aware, allowing you to incorporate Oracle data objects such as synonyms, produce Oracle-specific SQL commands, and so on.

In a few instances, however, you will find it useful to know how the Visual Database Tools differ when you are working with Oracle databases. For example, it is helpful to understand how the Query Designer will work with case-sensitive database object names in Oracle.

The topics listed in the following table provide information specific to using the Database Designer and Query Designer with Oracle databases.

Note These topics are not intended to explain Oracle databases. Instead, they highlight features unique to Oracle that are exposed through the Visual Database Tools. For more details about using Oracle databases, consult your Oracle database documentation.

For more information about | See
Additional items in Data View for Oracle databases | Data View for Oracle Databases (below)
Issues and notes concerning using the Database Designer with Oracle databases | Database Designer Considerations for Oracle Databases
Issues and notes concerning using the Query Designer with Oracle databases | Query Designer Considerations for Oracle Databases

Data View for Oracle Databases

For Oracle databases, you will see some differences in the Project Explorer (FileView in Microsoft® Visual C++®) and Data View windows. For example, when you add a connection to an Oracle database, you will see these folders under the connection: Database Diagrams, Tables, Views, Synonyms, Stored Procedures, and Functions.

The Tables folder contains the base tables in your database. The Views folder contains any SELECT statements saved as views.

Synonyms

The Synonyms folder contains synonyms in your database, which are names assigned to tables or views that may thereafter be used to refer to them. You can also create new synonyms.

To create a new synonym

  • From a query or SQL script, execute the following statement:
    create synonym name
for table

    Substitute the name of the new synonym for name and the name of a table for table.

For more details about synonyms, refer to your Oracle documentation.

Functions

The Functions folder contains the functions in your database. For details about functions, refer to your Oracle documentation.

Stored Procedures

The Stored Procedures folder contains stored procedures. For details about working with stored procedures in the Visual Database Tools, see Stored Procedures.

Triggers

When you add a new trigger to an Oracle database from Data View, a template for the new trigger is displayed in the editor, as shown below. This template adheres to correct Oracle syntax for triggers (just as new triggers added for SQL Server databases do). For details about working with triggers in the Visual Database Tools, see Triggers.

The new trigger template is:

CREATE TRIGGER TABLENAME_TRIGGERx
/* BEFORE | AFTER */
/* DELETE | INSERT | UPDATE [OF COLUMN] */
ON TABLENAME
/* REFERENCING OLD AS OLD | NEW AS NEW */
/* FOR EACH ROW */
/* WHEN (CONDITION) */

/*    DECLARE */
/*         VARIABLE DATATYPE; */

BEGIN
END;


Database Designer Considerations for Oracle Databases

If you are creating database diagrams using the Oracle database server, you can take advantage of features specific to that server. Although the Database Designer is designed to work well with Oracle databases, there are some important differences in how the Database Designer works with Oracle databases.

For details about Oracle-specific issues raised here, see your Oracle database server documentation.

The following sections outline differences you will notice in the Database Designer when you work with Oracle databases.

  • Oracle Driver

  • Case Sensitivity of Identifier Names

  • Error Messages

  • Adding Tables with the MLSLABEL Data Type to a Database Diagram

  • Changing Column Properties

  • Enforced and Unenforced Table Relationships

  • Constraints

  • Oracle-Specific Dialog Boxes and Property Pages

Oracle Driver

You must use the Oracle ODBC driver provided with the Microsoft® Visual Database Tools. This driver has been tested to ensure that it works properly with the Database Designer. The Database Designer works with Oracle version 7, and currently supports most of the features of later Oracle versions.

Case Sensitivity of Identifier Names

The names of database objects — tables, views, columns, and synonyms — are case-insensitive by default in the Oracle database server. When objects are added to a database diagram, their names are changed to all uppercase, unless the name is in double quotation marks.

In the Data View window, however, database object names are displayed with the actual combination of uppercase and lowercase letters used when creating the objects.

Error Messages

In many cases the Database Designer catches invalid syntax and displays an appropriate message. However, in some cases — usually involving syntax specific to Oracle databases — the Database Designer does not detect all errors. When Oracle attempts to display the changes to a database object, it detects an error and it returns an error number and string to the Database Designer. The Database Designer then displays the information in a "raw" state.

If you receive such an error message, consult your Oracle documentation for details. If you do not have access to the Oracle documentation, you might have to experiment with your database diagram to determine where the error lies.

Adding Tables with the MLSLABEL Data Type to a Database Diagram

Because the MLSLABEL data type is designed for use primarily with high-security applications, it is not supported by the Microsoft Oracle ODBC driver. However, MLSLABEL is a legal data type in Oracle, so the Database Designer does not immediately detect an error when you add a table containing a column of this data type to a database diagram. You can make changes to this table that require only an ALTER TABLE statement. However, if you make any changes that require the table to be recreated, you'll get an "ORA-03115: unsupported network datatype or representation" error and the changes will not be allowed.

To make the changes to the table, you can view the change script for the database diagram, save the appropriate SQL statements for the changes, and then use an Oracle client tool to execute these SQL statements against the Oracle database.

Changing Column Properties

Although the procedure for setting column properties using the Database Designer is similar regardless of the database you are using, the following sections contain information specific to Oracle databases.

  • Validating Column Names

  • Renaming a Column

  • Supported Oracle Data Types

  • Long or Long Raw Data Type Validation Rules

  • Converting Data Types

  • Default Data Type for New Columns

  • Changing the Null Option Assigned to a Column

  • Adding Column Comments

For information on how to set column properties using the Database Designer, see Setting Column Properties.

Validating Column Names

If you use an invalid name for a column in the Database Designer, the name is automatically put in double quotation marks. See your Oracle documentation for the rules governing naming database objects.

Renaming a Column

Oracle column names will be converted to upper case, unless the name is enclosed in quotation marks or the name is not valid when shifted to upper case. In the latter case, the column name will be automatically enclosed in quotation marks.

For the procedure for changing column names, see Renaming a Column.

Supported Oracle Data Types

Even though Oracle supports both ANSI and their own data types, the Database Designer only allows data types native to Oracle and the ANSI float data type. The following table shows the Oracle data types supported in this version of the Visual Database Tools. The Database Designer uses the specified default lengths when the user changes from one data type to another (the length of the original data type is not preserved).

For more information about these data types, consult your Oracle database documentation.

Supported Oracle data types

Data type | Description | Default value
VARCHAR2( length) | Variable length character string having maximum length bytes. Maximum length is 2000, and minimum is 1. You must specify length for a VARCHAR2. | 50
NUMBER( p,s) | Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from –84 to 127. | 22 No Edit
FLOAT( p) | ANSI Float type that is equivalent to NUMBER(38). The precision p can range from 1 to 126. | 22 No Edit
LONG | Character data of variable length up to 2 gigabytes, or 2 31 –1 bytes. | 0 No Edit
DATE | Valid date range from January 1, 4712 BC to December 31, 4712 AD. | 7 No Edit
RAW( length) | Raw binary data of length bytes. Maximum length is 255 bytes. You must specify length for a RAW value. | 50
LONG RAW | Raw binary data of variable length up to 2 gigabytes. | 0 No Edit
CHAR( length) | Fixed length character data of length bytes. Maximum length is 255. Default and minimum length is 1 byte. | 10
MLSLABEL | Binary format of an operating system label. This data type is used with Trusted Oracle7. | 0 No Edit
ROWID | Hexadecimal string representing the unique address of a row in its table. This data type is primarily for values returned by the ROWID pseudocolumn. | 6 No Edit

The Database Designer will allow you to decrement the Scale value of an existing column of type NUMBER. This will cause data loss, but no error message will be displayed.

Long or Long Raw Data Type Validation Rules

A table can only have one column with a LONG or LONG RAW data type. The Database Designer verifies the data type when you exit the cell. If another column exists in the table with a LONG or LONG RAW data type, the Database Designer displays an error message and returns control back to the data type cell with the value selected.

Converting Data Types

The following table shows the available data type conversions for Oracle version 7.

"S" indicates that the conversion is supported.

"NS" indicates that a conversion is not supported.

Data type conversions

FROM TO | CHAR | DATE | FLOAT | LONG | LONG RAW | MLSLABEL | NUMBER | RAW | ROWID | VARCHAR2
CHAR | S | S | S | S | NS | S | S | S | S | S
DATE | S | S | S | NS | NS | S | S | S | S | S
FLOAT | S | S | S | NS | NS | S | S | S | S | S
LONG | S | S | S | S | NS | S | S | S | S | S
LONG RAW | S | S | S | S | S | NS | S | S | S | S
MLSLABEL | S | S | S | NS | NS | S | S | S | S | S
NUMBER | S | S | S | NS | NS | S | S | S | S | S
RAW | S | NS | NS | NS | NS | NS | NS | S | S | S
ROWID | S | NS | NS | NS | NS | NS | NS | NS | S | S
VARCHAR2 | S | S | S | S | NS | S | S | S | S | S

If you attempt to change a data type to an unsupported type, the Database Designer displays an error message.

Unlike Microsoft® SQL Server™, in Oracle a VARCHAR2 data type cannot relate to a CHAR data type. This means that the Database Designer will change the default length when going from VARCHAR2 to CHAR or the other way around.

Default Data Type for New Columns

The Database Designer uses VARCHAR2 as the default data type for new columns defined in the field list control.

Changing the Null Option Assigned to a Column

You can toggle Allow Nulls on and off regardless of the column's data type. The default value is On for new columns.

The Database Designer doesn’t allow you to name or disable null constraints. The Database Designer will preserve the null constraint name and its disabled state in table recreates.

Disabled null constraints are visually the same as an enabled one. If you toggle Allow Nulls on for a disabled null constraint and then toggle it back off, the null constraint is recreated as enabled.

Adding Column Comments

You can enter up to 2000 bytes for a column comment. If you want to include a single quotation mark in the string, use either a single or two single quotation marks to represent it. If you put in just one quotation mark character, the Database Designer adds the second quotation mark to make it valid for Oracle. For example, a comment of:

Bill’s table

becomes

Bill’’s table

when you exit the edit field.

The Database Designer beeps when you type in more than 2000 characters in the Comment field. If the expansion of the single quotation mark to a double single quotation mark causes the comment to exceed 2000 characters, the Database Designer displays a message, allowing you to choose between truncating the comment or removing the single quotation mark and returning to the Comment field.

Delete a comment by deleting the contents of the Comment field.

Enforced and Unenforced Table Relationships

Oracle support for referential integrity differs from that in SQL Server.

  • How Referential Integrity Works in Oracle

  • Enforcing Referential Integrity Between Tables

For more information about referential integrity, see Enforcing Referential Integrity Between Tables in the Database Designer section of the documentation.

How Referential Integrity Works in Oracle

Referential integrity is a system of rules that ensure relationships between rows in related tables are valid and that you don't accidentally delete or change related data.

When referential integrity is enforced in an Oracle database, you must observe the following rules:

  • You can't enter a value in the foreign key column of the related table if that value doesn't exist in the primary key of the related table. However, you can enter a null in the foreign key column. For example, you can't indicate that a job is assigned to an employee who isn’t included in the employee table, but you can indicate that an employee has no assigned job by entering a null in the job_id column of the employee table.

  • You can't delete a row from a primary key table if rows matching it exist in a related table. For example, you can't delete a row from the jobs table if there are employees assigned to the job represented by that row in the employee table. However, if cascading deletes are enabled, you can delete a primary key row; all matching rows in related tables are also deleted.

  • You can't change a primary key value in the primary key table if that row has related rows. For example, you can't delete an employee from the employee table if that employee is assigned to a job in the jobs table.

Oracle supports only two kinds of referential integrity:

  • Enabling referential integrity to check values in related tables when you enter data. If the data value is not allowed (as determined by the rules above), the data entry fails and the data is not added to the database.

  • Cascading deletes.

SQL Server, on the other hand, supports some additional kinds of referential integrity. You can set options to disable the foreign key constraint under these conditions:

  • Upon creation, to check existing data

  • During INSERT and UPDATE transactions

  • During replication

As a result, the following topics in the Database Designer documentation are not valid for Oracle databases:

Checking Existing Data when Creating a Relationship

Disabling a Foreign Key Constraint with INSERT and UPDATE Statements

Disabling a Foreign Key Constraint for Replication

Enforcing Referential Integrity Between Tables

Referential integrity between tables is enforced by default when you create a relationship in your database diagram. An enforced relationship ensures each value entered in a foreign key column matches an existing value in the related primary key column.

You can change the conditions under which referential integrity is enforced by editing the relationship’s properties.

To change referential integrity options for a new relationship

  1. In your database diagram, create a relationship line. For details, see Creating a Relationship Between Tables.

  2. In the Create Relationship dialog box, clear or select one or more of the options (Enable relationship or ON DELETE CASCADE).

To change referential integrity options for an existing relationship

  1. In your database diagram, select the relationship line.

  2. Right-click the relationship line and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear or select one or more of the options (Enable relationship or ON DELETE CASCADE).

The relationship is updated in the database when you save the diagram or either of the related tables.

For more information on the options for setting referential integrity for Oracle databases, see Oracle-Specific Dialog Boxes and Property Pages.

Constraints

Oracle databases have different functionality for constraints. For example, in Oracle, constraints can be enabled and disabled. For information on how constraints are applied and used in Oracle databases, see your Oracle documentation. For information on how Oracle constraints are set in the Database Designer, see Oracle-Specific Dialog Boxes and Property Pages.

The following topics contain information that is specific to SQL Server databases; the topics note where the implementation is different for Oracle databases.

  • Checking Existing Data When Creating a Check Constraint

  • Disabling a Check Constraint for Replication

  • Creating a Unique Constraint

  • Defining a Primary Key

For more information about using constraints in the Database Designer, see Constraints.

Checking Existing Data When Creating a Check Constraint

In the Database Designer topic Checking Existing Data When Creating a Check Constraint, the following information is SQL Server specific:

When you create a check constraint, you can set an option to apply it either to new data only or to existing data as well. The option of applying the constraint to new data only is useful when you know that the existing data already meets the new check constraint, or when a business rule requires the constraint to be enforced only from this point forward.

Disabling a Check Constraint for Replication

In the Database Designer topic Disabling a Check Constraint for Replication, the following information applies to SQL Server only:

You can disable a check constraint when your table is replicated in another database. When you replicate a table, the table definition and data are copied from the source database to a destination database. These two databases are usually (but not necessarily) on separate servers. If the check constraints are specific to the source database, they may unnecessarily prevent new data from being entered in the destination database.

Creating a Unique Constraint

In Oracle, you can enable and disable constraints.

Defining a Primary Key

In Oracle, you can enable and disable primary keys.

Oracle-Specific Dialog Boxes and Property Pages

The following dialog boxes and property pages are specific to Oracle. For more information on the fields and settings in these dialog boxes and property pages, see your Oracle documentation.

Create Relationship Dialog Box

Tables Tab (Database Diagram Property Pages)

Relationships Tab (Database Diagram Property Pages)

Indexes/Keys Tab (Database Diagram Property Pages)


Query Designer Considerations for Oracle Databases

If you are creating queries using the Oracle database server, you can take advantage of features specific to that server. The following guidelines outline differences you will notice in the Query Designer when you work with the Oracle Server, and provide information about Oracle-specific features that you can use.

Below you will find information about:

  • Oracle Driver

  • Using Synonyms

  • Identifying Database Objects

  • Case-Sensitivity of Identifier Names

  • Error Messages

  • Creating Outer Joins

  • Combining All Columns with Individual Column Names

  • Concatenating Text

  • Entering Dates in the Grid and SQL Panes

  • Creating Aggregate Queries

  • Creating an Insert Values Query

  • Creating a Make Table Query

  • Creating Comparisons Using Distributive Syntax

  • Creating Aliases

  • Including Optimizer Hint Comments

  • Running Queries with the MLSLABEL Data Type

  • Using LEVEL, ROWID, and ROWNUM Pseudo-Columns

  • Unsupported Query Types

Oracle Driver

It is recommended that you install and use the Oracle ODBC driver provided with the Microsoft® Visual Database Tools. This driver has been tested extensively to ensure that it works properly with the Query Designer.

Using Synonyms

Using the Query Designer, you can create queries using not only tables and views, but using synonyms as well. You can query any synonym for which you are the owner or which you have been given permission to.

If you do not see column names in the input source window for a synonym, synonym column information may not have been enabled for the ODBC driver you are using. In that case, you can use the synonym columns if you know their names by entering them in the SQL or Grid panes. For details about enabling synonym column names, see the documentation for the Oracle ODBC driver you are using.

Identifying Database Objects

Database objects (tables, views, columns, and synonyms) in Oracle databases are identified with unique names that consist of two parts (for tables and views) or three parts (for columns):

owner.table

owner.table.column

If you are the owner of a table or view, you do not need to include the owner qualifier when you reference the table or view. For example, if you are working with a column called PRICE in the TITLES table in the current database, you can simply reference the column by name, as in this SQL statement:

SELECT PRICE
FROM TITLES

If you are working in the Diagram and Grid panes, the Query Designer automatically adds the owner name to the table or view if necessary.

If you are not the owner of a table or view, you can reference the table and view in the SQL pane (if you have permission) by including the owner name. For example, to display information from an EMP table owned by the user HR, you can include the owner name. If the query contains more than one table, you must also include table name qualifiers. The following query illustrates the use of the owner and table name qualifiers:

SELECT HR.EMP.LAST_NAME, HR.EMP.FIRST_NAME, MyEmp.NOTES
FROM HR.EMP, EMP MyEmp
WHERE HR.EMP.EMPID = MyEmp.EMPID

Case-Sensitivity of Identifier Names

The names of database objects — tables, views, columns, and synonyms — are case-sensitive by default in the Oracle database server. For example, it is possible to have two tables whose names are distinguished only by uppercase and lowercase letters, such as EMP and Emp.

When a query is executed, the Oracle database server, by default, converts all database object names to uppercase characters. If the actual object name uses lowercase or mixed-case letters, an error results because the converted uppercase name (for example, EMP) would not match the actual name (Emp).

However, the Oracle database server does not convert to uppercase letters an object name that is enclosed in double quotation marks. Therefore, you can specify lowercase or mixed-case database object names by putting the names in double quotation marks. For example, in the following SQL statement, because the mixed-case table name Emp is in double quotation marks, the Oracle database server does not convert it to the name EMP when the query is run:

SELECT "Emp".ENAME
FROM "Emp"

In the Query Designer, database object names are displayed in Data View of the project workspace with the actual combination of uppercase and lowercase letters. When you drag tables or views onto the Diagram pane, and when you choose names in the Grid pane, the Query Designer automatically places double quotation marks around the name if the name is not all uppercase.

If you enter lowercase or mixed-case database object names in the SQL pane, place double quotation marks around any names that contain lowercase letters. If you do not place quotation marks around the lowercase or mixed case names, the Query Designer follows this strategy in resolving the name:

  1. The Query Designer looks first for an exact, case-sensitive match for the name you entered. If a match is found, the Query Designer places double quotation marks around the name when you next use the Diagram or Grid pane to make changes to the query.

  2. If no match is found, the Query Designer converts the name to uppercase letters and attempts again to find a match. If a match is found, the Query Designer converts all references to the name in the SQL pane to uppercase.

  3. If still no match is found, the Query Designer leaves the name as you entered it and allows the server to make its default conversion on the name.

Error Messages

In many cases the Query Designer catches invalid syntax and displays an appropriate message. However, in some cases — usually involving syntax specific to Oracle databases — the Query Designer does not detect all errors. When Oracle attempts to run the query, it detects an error, and it returns an error number and string to the Query Designer, which displays the information in a "raw" state.

For example, if the column list in the SQL statement contains an invalid reference, Oracle might return error 00923, with the phrase "FROM keyword not found." This error indirectly indicates a problem with the column list.

If you have access to Oracle documentation, you can look up the errors returned in this fashion. If not, you might have to experiment with the syntax of your query to determine where the error lies.

In some other cases, it is the Microsoft Oracle ODBC driver that is returning the error. For example, the driver does not support the MLSLABEL data type. If you attempt to create a query using this data type, the driver (not Oracle) reports an "unknown error" or an error indicating that the query contains an "unsupported network data type or representation."

Creating Outer Joins

If you create an outer join between input sources, it is represented in the SQL pane using the Oracle-specific (+) syntax. For example, the following query creates a left outer join between the EMP and DEPT tables:

SELECT EMP.EMPNO, DEPT.DNAME
FROM EMP, DEPT
WHERE EMP.DEPTNO (+) = DEPT.DEPTNO

If you are creating an outer join in the SQL pane, you can use the (+) syntax. If you attempt to use the LEFT OUTER JOIN or RIGHT OUTER JOIN syntax, the Query Designer will display the Query Definitions Differ Dialog Box dialog box and report an error when you execute your query or change panes. You cannot use the (+) operator in the Grid pane.

You can also use the ODBC { oj } syntax. If you do, the Query Designer might convert it to (+) syntax, depending on the ODBC driver you are using.

Oracle does not support full outer joins. When you are working with an Oracle database, the Query Designer will prevent you from creating a full outer join by setting the properties of the Join Line.

Similarly, Oracle also has restrictions on creating outer joins involving three or more tables. In general, the Query Designer will prevent you from creating a query that would not be allowed in Oracle. For more information about restrictions for outer joins, see the Oracle documentation.

Combining All Columns with Individual Column Names

In the list of columns to return, Oracle does not permit you to combine column names with * (All Columns). For example, the following syntax will result in an error:

SELECT pub_id, pr_info, *
FROM pub_info

Because this syntax is allowed in some databases, the Query Designer does not prevent you from entering it in the SQL pane. However, when the SQL statement is processed, the Query Designer will display an error that might include one of the following phrases:

(00923) FROM keyword not found where expected

(00926) Missing Expression

Concatenating Text

When you work with Oracle databases, the Query Designer allows you to use the + operator when you are using the Grid pane to create expressions that concatenate text. However, the Query Designer will convert the + operator to the Oracle-standard || operator. If you are entering expressions directly in the SQL pane, you must use the || operator.

Entering Dates in the Grid and SQL Panes

When you enter a valid date in the Grid pane, the Query Designer replaces the date you entered with a call to the TO_DATE( ) function, using your date as one of the parameters. This assures that Oracle will correctly interpret that data you have entered.

You can enter dates directly in the SQL pane, but you must enter them in exactly the format specified for your database, as specified by the current session's NLS_DATE_FORMAT value. Because there might not be an easy way to determine the correct format, it is advisable to use the TO_DATE( ) format in the SQL pane. For example, a query might look like this:

SELECT   EMP_ID, HIRE_DATE
FROM     EMPLOYEE
WHERE    HIRE_DATE > TO_DATE('01/01/90', 'MM/DD/YY')

For details about the TO_DATE( ) function, refer to the Oracle documentation.

Creating Aggregate Queries

In addition to the standard aggregate functions (AVG, SUM, and on), Oracle allows you to use the aggregate functions STDDEV( ), which calculates the standard deviation of a summary value, and VARIANCE( ), which returns a variance on the summary values. When you are working with an Oracle database, both of these aggregate functions, along with variants that include their optional DISTINCT qualifier, appear in the drop-down list under Group By in the Grid pane. You can also enter them directly in the SQL pane.

Creating an Insert Values Query

When you create an Insert Values query using an Oracle database, you can use named sequences in the New Values clause. For example, you can create the following named sequence:

CREATE SEQUENCE empseq
INCREMENT BY 10

You can then use this named sequence in an Insert Values query, as in the following example:

INSERT INTO emp
VALUES (empseq.nextval, 'Ann', 'E', 'Smith', 7902, 11, '0877', SYSDATE)

Creating a Make Table Query

In Oracle databases, a Make Table query is implemented with the Create Table as Select command. In all other respects a Make Table query functions the same as with any other database.

Creating Comparisons Using Distributive Syntax

Oracle allows you to create comparisons using distributive syntax, as in the following example:

SELECT EMP_ID, LNAME
FROM EMP
WHERE (JOB_ID, DEPT_ID) in (6669,21)

You can enter this syntax directly in the SQL pane. When you change panes or execute the query, the Query Designer reformats the SQL statement by redistributing the elements in the comparisons. The above statement would be reformatted as follows:

SELECT EMP_ID, LNAME
FROM EMP
WHERE (JOB_ID = 6669) AND (DEPT_ID = 21)

Any similar distributive syntax will be reformatted in the same way. In complex statements, especially those involving NOT, the resulting statement can become quite long. However, it is always guaranteed to be logically identical to the distributive syntax that you originally entered.

Creating Aliases

Oracle does not support AS in table alias clauses. However, you can create an alias without the AS, as in the following example:

SELECT *
FROM     DEPT D
WHERE    D.LOC = 'NEW YORK'

Including Optimizer Hint Comments

If you are entering a query directly in the SQL pane, you can add optimizer hints before the SELECT, UPDATE, or DELETE command to specify how the query should be parsed and compiled. When reformatting the contents of the SQL pane, the Query Designer will maintain these comments according to the following conventions:

  • Only optimizer hint comments are retained. Other types of comments are stripped.

  • Optimizer comments are retained only after the keywords listed above.

  • Optimizer comments will be enclosed in C-style comment delimiters (/* */).

  • Multi-line optimizer comments will be reformatted as single-line comments.

  • The Query Designer will start a new line after each optimizer comment.

  • Optimizer comments are not retained if you change query types.

For more details about optimizer hints, refer to the Oracle documentation.

Running Queries with the MLSLABEL Data Type

Because the MLSLABEL data type is designed for use primarily with high-security applications, it is not supported by the Microsoft Oracle ODBC driver. MLSLABEL is a legal data type in Oracle, so the Query Designer does not immediately detect an error when you use an input source that includes a column of that data type. However, when you run the query, the Query Designer displays an error message that indicates an "unknown error" or one that indicates that the query contains an "unsupported network data type or representation."

Using LEVEL, ROWID, and ROWNUM Pseudo-Columns

The identifiers LEVEL, ROWID, and ROWNUM are pseudo-columns in Oracle that you can use in queries you create with the Query Designer. You enter the pseudo-columns into the Grid pane or directly in the SQL pane. They do not appear in the input source window in the Diagram pane.

Unsupported Query Types

Some types of legal Oracle queries cannot be represented graphically in the Query Designer. You can still enter them in the SQL pane, and they will execute correctly. However, the Query Designer will display the Query Definitions Differ dialog box and report an error when you execute your query or change panes.

The following types of Oracle queries are not supported graphically:

  • Queries involving the GLB( ) or LUB( ) functions

  • Hierarchical Select queries

  • Queries using INTERSECT

  • Queries using MINUS

  • Queries using UNION [ALL]

  • CREATE SNAPSHOT queries


Database Designer

The Database Designer is a visual tool allowing you to create, edit, or delete database objects for databases while you’re directly connected to the database in which those database objects are stored.

You interact with the server database using database diagrams. Database diagrams graphically represent the tables in your database. These tables display the columns they contain, the relationships between the tables, and indexes and constraints attached to your tables. When you establish a connection to a database, you can use database diagrams to:

  • View the tables in your database and their relationships.

  • Perform complex operations to alter the physical structure of your database.

You can make changes freely in the database diagram without affecting the underlying database. When you modify a database object through a database diagram, the modifications you make are not saved in the database until you save the table or the database diagram. Thus, you can experiment with "what if" scenarios on a database’s design without permanently affecting its existing design or data.

You can then either:

  • Save the changes to selected tables or the database diagram and have the changes modify the server database. For more information, see Saving Selected Tables.

  • Discard your changes.

    –or–

  • Save a change script that contains the SQL code generated by your changes to the diagram. If you save a change script instead of saving your changes to the database, you can edit the change script in a text editor and then apply the modified script to the database.

    You can also choose to automatically create a change script each time you save your database diagram or any database object in your diagram. This provides you with a record of the changes you made to the database. For more information about change scripts, see Saving a Change Script.

You control the timing, type, and extent of the changes to your database by choosing how changes to the database diagram affect the server database.

Creating and Managing Database Diagrams

You can use database diagrams to:

  • Manipulate database objects without having to write SQL code.

  • Visualize the structure of your database tables and their relationships.

  • Provide different visualizations of complex databases.

  • Experiment with database changes without modifying the underlying database.

  • Create new tables, indexes, relationships, and other constraints.

  • Alter the structure of your database.

For example, you can create a database diagram for your company’s payroll department that shows only tables that hold employee benefits information. Or you can create a diagram for your development team that shows only those tables that are used in a specific application module.

You can change the size, shape, and position of objects in your diagram without affecting their definitions in the database. When you save your database diagram, the layout of your diagram is preserved as well as any changes you made to the object definitions in your diagram.

The Database Designer does not require additional security features set up separately from the security features in your database. Database diagrams are saved in the dtproperties or MicrosoftDTProperties table of your database.

For information about | See
Creating, saving, formatting database diagrams | Working in Database Diagrams
Working with multiple users and reconciling changes with a modified database | Working in a Multi-User Environment
Modifying the database by saving tables and saving change scripts | Controlling Database Changes
Creating, editing, deleting database objects in a database diagram | Working with Database Objects

Creating and Modifying Database Objects

Tables are the basic building blocks of database diagrams. Every diagram is made up of one or more tables and the various objects related to those tables.

Each table has a set of columns that contain information about the type of data that you will store in the table. You must define at least one column in order to save a table in the database. Each column must have a column name, an assigned data type, and an assigned length. These and other properties can be defined in your database diagram. You modify tables and their columns directly in a database diagram.

A table can also have a set of constraints and indexes. Because constraints and indexes are defined for a specific table, they are treated as properties of that table in a database diagram. You use the property pages to create, modify, or delete these database objects for a table.

You can use the Database Designer to create and modify database objects, including:

  • Tables

  • Columns

  • Table Relationships

  • Indexes

  • Constraints

  • Stored Procedures and Triggers

For more information about creating and modifying database objects, see Working with Database Objects.


Working in Database Diagrams

You can perform two types of operations in database diagrams:

  • Operations that modify the structure of your database.

  • Operations that modify the graphical layout of the tables and relationships in your diagram without affecting the definition of those objects in your database.

When you save a database diagram, your changes to the definitions of your database objects, as well as your changes to the graphical layout of your diagram, are saved in the dtproperties or MicrosoftDTProperties table of your database.

Modifying the Structure of Your Database Using Database Diagrams

You can create database diagrams of varying complexity, from diagrams that contain just one table to diagrams that contain hundreds of tables. When you first create a diagram, you are presented with a blank diagram surface to which you can add tables.

To | See
Create a new database diagram for your project | Creating a Database Diagram
Add tables to the database diagram, edit column properties, create relationships between tables, create indexes, constraints, stored procedures, and triggers | Working with Database Objects
Update the database using database diagrams | Controlling Database Changes

You interact with database diagrams by using commands available in menus and on the Database Designer toolbar:

Working with a Single Table in the Database Designer

When you want to work with only one table, you can either create a database diagram for that table or you can create a single-table diagram. When you create, open or design a table in the Tables folder, the table is shown in a single-table diagram.

In this single-table mode, you can define the properties of a new table, adding columns and column properties. When you save the new table, it is added to your database and to the Tables folder. You can then easily add this table to existing or new database diagrams.

Laying Out Tables Graphically Using Database Diagrams

You can perform a variety of diagramming operations in a database diagram without affecting the object definitions in your database. You can customize the appearance of your diagram to meet your development needs in the following ways:

To | See
Arrange tables automatically | Arranging Tables Automatically
Use the keyboard or mouse to move around in a diagram | Navigating a Database Diagram
Change the size and shape of tables | Changing a Table View and Adjusting the Table Size
Remove tables from the diagram without deleting them from the database | Removing a Table from a Database Diagram
Change the magnification of a diagram, zoom to fit selected items in a diagram | Zooming a Database Diagram
Print and preview your database diagram | Printing and Previewing Database Diagrams
Open the Properties pages to edit properties for the objects in your diagram | Setting Properties in a Database Diagram
Divide and merge diagrams to make managing parts of the database easier | Subdividing a Database Diagram and Merging Subdiagrams into a Master Diagram
Select and move tables and relationship lines in a diagram | Selecting Multiple Objects in a Database Diagram

These operations affect the appearance of your diagram, but they do not affect the structure of your database.


Creating a Database Diagram

You can use a database diagram to create, edit, or delete database tables. You can also use a database diagram to see how your tables relate to each other. When you create a new database diagram, you are presented with a blank diagram surface to work on.

To create a database diagram

  1. Make sure you’re connected to the database whose tables you want to edit.

  2. In Data View, right-click the Database Diagrams folder and choose New Diagram from the shortcut menu.

    A blank database diagram appears.

  3. Add tables to the diagram by dragging a table or one of its columns into the diagram. When you release the mouse button, the table appears on your diagram and valid relationship lines to other tables in the diagram are automatically drawn.

    -or-

    Create a new table in the diagram by right-clicking anywhere inside the diagram and then choosing New Table from the shortcut menu.

    For more information see Adding Tables to a Database Diagram.

  4. Arrange the objects in your diagram. For more information, see Formatting a Database Diagram.

If you want to move objects to different parts of your diagram — for example, to align the tables or reduce the number of overlapping relationship lines — first select the objects, and then drag the selection to its new location.

  • To select a table, click its title bar.

  • To select a set of tables, hold down the CTRL key as you click inside the title bar of each table in the set.

  • To select a set of tables grouped together, position the pointer near one of the tables and then drag a rectangle around all the tables in the set.

If you select multiple tables, the relationship lines that connect them are automatically included in the selection.

If you select a relationship line, you can slide a line segment to a location that is parallel to its original position. If the relationship line has more than one segment, you can drag a corner diagonally to change both its vertical and horizontal position.

For an overview of the elements that you can edit in a table, see Working with Database Objects.


Saving a Database Diagram

Save your database diagram to update the database with the changes you made to the diagram layout and the object definitions in the diagram.

If you want to discard your changes to the diagram layout but keep the option to save your changes to your object definitions at a later time, you can save a change script. You can then run the change script at some other time to update the database. You can also edit the change script’s SQL code in a text editor before you run it.

For more information about change scripts and how to use them, see Saving a Change Script.

To save a database diagram

  1. Click the Save button [image] on the toolbar.

  2. In the Save New Database Diagram dialog box, type a name for your diagram and choose OK.

  3. If you have made changes to tables in your diagram, the Save dialog box appears and displays a list of tables that will be saved in the database when you save your diagram. Choose Yes to update the database to match your diagram.

Database diagrams are saved in the dtproperties or MicrosoftDTProperties table of your database.


Navigating a Database Diagram

You can move around in a database diagram by using the keyboard or the mouse.

To use the mouse, click to select an object. To use the keyboard, refer to the following table for keyboard navigation methods.

To | Press
Move from a table cell to the table’s title bar | ESC
Move from a table’s title bar to the last cell you edited | ENTER
Move from table title bar to table title bar, or from cell to cell inside a table | TAB
Expand a list inside a table | ALT + DOWN ARROW
Scroll through the items in a drop-down list from top to bottom | DOWN ARROW
Move to the previous item in a list | UP ARROW
Select an item in a list and move to the next cell | ENTER
Change the setting in a check box | SPACEBAR
Go to the first cell in the row, or to the beginning of the current cell | HOME
Go to the last cell in the row, or to the end of the current cell | END
Scroll to the next "page" inside a table, or to the next "page" of the diagram | PAGE DOWN
Scroll to the previous "page" inside a table, or to the previous "page" of the diagram | PAGE UP


Selecting Multiple Objects in a Database Diagram

You can perform actions on a group of objects by selecting multiple objects in a database diagram. You can select multiple objects that are adjacent to each other or that are spatially separated from each other by other objects.

To select all objects in the diagram

  • Right-click the diagram and choose Select All from the shortcut menu.

To select a group of adjacent tables

  • Hold down the SHIFT key while you click each table that you want to add to your selection.

    –or–

  • Point to the diagram background and drag a rectangle around the tables you want to select. Each table does not have to be fully contained in the rectangle to be selected.

To select a group of spatially separated tables

  • Hold down the CTRL key while you click each table that you want to add to your selection. If you click the title bar of an already selected table, that table is removed from the selection.

To select a group of adjacent columns

  • Hold down the SHIFT key while you click the row selector [image] of the first and last columns that you want to select. This method selects every column from the column that displays the selected row indicator [image] to the last row selector you clicked.

To select a group of spatially separated columns

  • Hold down the CTRL key while you click the row selector [image] of each column that you want to add to your selection. If you click the row selector of an already selected column [image], that column is removed from the selection.

To select a relationship line

  • Click the relationship line.

    You can select only one relationship line at a time. For example, you can select a relationship line when you want to change its properties. When you select a group of tables, the relationship lines between the tables are automatically included in the selection.


Formatting a Database Diagram

You can format your database diagram in a number of convenient ways. You can choose to have the diagram's layout automatically changed to best show the tables you're currently working on, or automatically display labels for relationship lines. The database diagram can display annotations you create for the diagram and its objects. You can also change the zoom setting of the diagram to display just the amount of the diagram you'd like to see.

To | See
Lay out the tables in the diagram automatically | Arranging Tables Automatically
Add notes to a database diagram | Annotating Diagrams
Show a label identifying relationship lines between tables | Adding Labels to Relationship Lines
Change the zoom setting to view different amounts of the diagram | Zooming a Database Diagram


Arranging Tables Automatically

You can automatically rearrange your database diagram to display the table or tables you want to work on, or you can rearrange the entire diagram in a way that best displays all the tables and their relationships.

To arrange all tables in a diagram automatically

  1. Right-click the database diagram.

  2. From the shortcut menu, select Arrange Tables.

    The diagram is rearranged to best display all the tables and their relationships. This is especially useful if you've moved the tables in the diagram, or added new tables, and want to clean up the layout of the diagram.

To arrange selected tables in a diagram automatically

  1. Select the tables you want to arrange.

  2. Right-click a table and choose Arrange Selection from the shortcut menu.

    The diagram is rearranged to best display the currently selected table or tables and their relationships.


Annotating Diagrams

You can put notes into your diagram, to describe the diagram and its objects. These can include headings, descriptions of the tables and their contents, and any other information you want to place in the diagram.

To add annotations to a diagram

  1. Right-click the database diagram.

  2. From the shortcut menu, choose New Text Annotation. A blank text box appears in the diagram at the location where you right-clicked.

  3. Type the annotation in the text box.

To change the font of the annotation

  1. Select the text annotation box whose font you want to change.

  2. Right-click inside the text annotation box and choose Set Text Annotation Font from the shortcut menu.

Note All text in the text annotation box will be changed to the new font.

To arrange the text annotation in a diagram

  1. Select the text annotation box.

  2. Drag the box into position in the diagram.

Tip You can use annotations to describe the relationships between tables in your diagram. However, you can also generate relationship labels automatically. For more information, see Adding Labels to Relationship Lines.


Adding Labels to Relationship Lines

You can choose to have all relationship lines in a database diagram display a label automatically.

To add labels to relationship lines in a diagram

  1. Right-click the database diagram.

  2. From the shortcut menu, choose Show Relationship Labels.

To rename relationship labels

  1. Select the relationship line you want to rename.

  2. Right-click the relationship line and select Properties from the shortcut menu.

  3. Select the Relationships tab.

  4. In the Relationship name box, type a new name for the relationship label.

  5. Click OK.

Note You cannot change the font for relationship labels.

If relationship line labels are not displayed, you can still see the relationship line label for a given relationship.

To view a label for a specific relationship line

  1. In the database diagram, move the mouse over the relationship line.

  2. The Tooltip will show the relationship label.


Zooming a Database Diagram

Change the zoom level of your database diagram to control how much of the diagram you can see on your screen at once.

To zoom a database diagram

  • Select a setting from the Zoom list on the toolbar.

Note To edit tables, you must set the zoom level to 50% or higher. To create relationships, you must set the zoom level to 25% or higher.

To zoom to a selected object

  • Select an object in the diagram and choose Selection from the Zoom list on the toolbar.

Tip To center the entire diagram in the window, use Select All to highlight all objects in the database and then choose Selection from the Zoom list on the toolbar. This will zoom your diagram to fit in the current diagram window size.


Setting Properties in a Database Diagram

Set column properties in the database diagram to redefine a column name, data type, and so on. Use the Properties Pages dialog box to set properties of tables, relationships, indexes, and constraints.

To edit column properties

  1. In your database diagram, select the table whose columns you want to edit.

  2. Right-click the table and select [image] Column Properties.

  3. Click inside the cell you want to change and then edit the property. The new setting takes effect when you exit that cell.

For more information, see Column Properties.

To set properties of other database objects

  1. In your database diagram, select the table or relationship line whose properties you want to edit. To edit an index or constraint, select the table that it’s attached to.

  2. Right-click the object and select Properties from the shortcut menu.

  3. Select the tab that shows the properties for the object you want to edit.
    • Choose the Tables tab to rename the table or edit check constraints.

    • Choose the Relationships tab to rename the relationship or change the columns that participate in the selected relationship.

    • Choose the Indexes/Keys tab to rename an index, create or edit an index or constraint, or set a fill factor.
  4. Type or select a new setting. The setting takes effect when you exit the field.

Property settings are saved in the database when you save the diagram or selected tables. If you close a database diagram to discard unsaved changes when other database diagrams are still open, the modified database objects will remain in memory until you close all open diagrams. For example, suppose you change the properties of the authors table and close the table without saving it. If you then add the authors table to another open diagram, it will appear in the new diagram in its modified state. To discard all unsaved changes, you must close all open database diagrams without saving them.


Printing and Previewing Database Diagrams

Printing your database diagrams gives you a useful picture of your database structure to refer to or distribute. You can preview the page breaks in the database diagram. You can also further customize the way your printed database diagram will look by changing the layout of the database diagram, and by specifying the table views in the diagram.

To print a database diagram

  1. Display the diagram and make sure its layout is what you want to see on the printed page.

  2. From the File menu, choose Print.

  3. Depending on your printer setup, you may need to make or verify a selection in the Print dialog box and click OK.

The Database Designer displays a set of grid lines showing how the database diagram will be broken into pages when it prints. You can recalculate the grid lines after you've added or rearranged objects.

To preview page breaks

  • If grid lines aren't already displayed, right-click the database diagram, and choose View Page Breaks from the shortcut menu.

To recalculate page breaks

  • Right-click in the diagram, and choose Recalculate Page Breaks from the shortcut menu.

Changing the Layout

Before you print, arrange the objects in the database diagram so that it looks the way you want it. You can change the size, shape, and position of objects in your diagram without affecting their definitions in the database.

To change the layout of your diagram, use the features and commands of the Database Designer to move, size, and shape the objects. For example, you can use the mouse to move or size tables, or use the automatic layout command to automatically reposition the objects in relationship to the selected object or objects.

For more information, see Arranging Tables Automatically

Changing the Views

Each table in a database diagram appears in one of five views: Column Properties, Column Names, Key Columns, Table Names, or Custom. These views show different levels of detail about the table columns, column properties, and property settings. For more information, see Changing a Table View.

The Column Properties and Custom views are the most useful for printing, because they show the most information about the overall structure of the database. With the Custom view you can determine exactly what columns you want to see. You can also avoid displaying scroll bars on any of the tables.

The Column Properties view shows all column properties, even ones you don't normally need to see or set.

Note You can hide and show columns in Column Properties view (by setting the column width to zero), and these columns won't be printed. However, this applies only to one table, and can't be applied automatically to other tables. It does not change the default display for new tables added to the diagram. The Custom view gives you all these capabilities.


Subdividing a Database Diagram

Database diagrams can range in complexity from just one table to hundreds of tables. When you’re working with a large number of tables, you can create a "master" diagram that contains all the tables you need, and then divide the master diagram into many smaller diagrams or "subdiagrams."

Subdivide your diagram when you want to isolate a group of the tables. For example, if you are designing an application with many modules, you can create one master diagram with all the tables that your application needs. You can then subdivide the master diagram so that each subdiagram contains only the tables pertaining to a specific module.

To subdivide a database diagram

  1. Open the master diagram.

  2. Create a new database diagram. For details, see Creating a Database Diagram.

  3. In the master diagram, select the group of tables you want to isolate in the subdiagram. For details, see Selecting Multiple Objects in a Database Diagram.

  4. Copy or drag the tables into the new database diagram. For details, see Copying a Table Across Database Diagrams.

Because each table that appears in a database diagram is merely a reference to a database table, you need to edit the table in only one diagram in order for your changes to be immediately reflected in each diagram in which the table appears.


Merging Subdiagrams into a Master Diagram

Merge a set of subdiagrams into a master diagram to consolidate multiple diagrams for a large group of tables that are logically related. For example, as you add new modules to an existing application, you can create one diagram for each new module. You can then merge all the diagrams into the master diagram.

To merge subdiagrams into a master diagram

  1. Open your master diagram or create a new diagram. For details, see Creating a Database Diagram.

  2. Open the subdiagram that you want to merge into the master diagram.

  3. Select Tile Horizontally or Tile Vertically from the Window menu so that both diagrams are visible.

  4. In the subdiagram, choose Select All from the Edit menu.

  5. Position the pointer on the title bar of one of the selected tables and drag the selection to the master diagram. If your selection contains a table that is already displayed on the master diagram, it will not be duplicated. A diagram cannot contain duplicate copies of a table.

  6. Repeat steps 2 through 5 for each subdiagram that you want to merge into the master diagram.

When you consolidate a group of tables into one diagram by merging subdiagrams into a master diagram, the layout of the individual subdiagrams is maintained within the master diagram.


Canceling an Action

In a database diagram, you cannot undo actions once they have been completed. However, you can cancel an action before it is completed.

The following table lists actions and how you can cancel them before they are completed.

Type of action | To cancel the action
Dragging a table into a database diagram | Before you release the mouse button, drag-and-drop the objects outside the diagram or press the ESC key.
Typing in a table cell | Press the ESC key before exiting the cell.
Editing a property inside the properties pages dialog box | Press the ESC key before exiting the field.
Creating a relationship line Before you release the mouse button, drag the line to the diagram background.

–or–

Choose Cancel in the Create Relationship Dialog Box.

Even though you cannot undo a deletion, you can make sure that the deletion does not take effect in your database by closing the affected diagrams without saving them first.

If you want to save some of the tables in your diagram but not others, select them and choose Save Selection from the File menu. Then close the diagram; the unsaved changes will be discarded.


Working in a Multi-User Environment

You can work with database diagrams in a multi-user environment; that is, an environment in which more than one user may make changes to a database diagram and the database at a time. When you save a diagram, the Database Designer verifies that the database has not been modified since you last saved the diagram. If another user has made changes, you will be notified that the database has been modified. You may need to reconcile these changes, both in the database diagram and in the database itself.

To | See
Work with others on shared database diagrams | Multi-User Environments
Resolve changes made to a database diagram by multiple users | Reconciling a Database Diagram with a Modified Database


Multi-User Environments

A multi-user environment is one in which other users can connect and make changes to the same database that you’re working with. As a result, several users might be working with the same database objects at the same time. Thus, a multi-user environment introduces the possibility of your database diagrams being affected by changes made by other users, and vice versa. Such changes could include changes to copies of your diagrams, other users’ diagrams that share database objects with your diagrams, or the underlying database.

A key issue when working with databases in a multi-user environment is access permissions. The permissions you have for the database determine the extent of the work you can do with the database. For example, to make changes to objects in a database, you must have the appropriate write permissions for the database. For more information about permissions in your database, see your database documentation.

As one of multiple users, you may need to address any of the following issues when working with the Database Designer:

  • Ownership of Database Objects

  • Diagrams Affected by Another User’s Changes

  • Database Objects Deleted by Another User


Ownership of Database Objects

Each database has a database owner. The database owner is the creator of the database and has system administrator privileges inside the database. It is the database owner who determines the access and capabilities provided to other users. Within a database diagram, the database owner is identified by his or her database user name.

In most databases, each database object (table, index, view, default, constraint, trigger, rule, and stored procedure) also has a designated owner. The user who creates a database object is the database object owner and is automatically granted all permissions to it. The database object owner is not necessarily the database owner. Any user who has permission to create a database can be a database object owner. In many databases, it is possible to transfer ownership of database objects. See your database documentation for details.

Database diagrams enable you to work with a table that is owned by another user. For example, you can move a column from a table that you don’t own to a table that you just created. If you have sufficient permissions to modify the database with your changes, you can do so by saving your diagram.

Note If you don’t have sufficient privileges to modify the database, you can save your changes in an SQL change script that the database owner can later apply to the database.

If your database diagram contains tables that are not owned by the database owner, the name of the database object owner appears in parentheses at the end of the table name. For example, the following table title bar shows that the authors table is owned by user JohnDoe:

For more information about database owners and database object owners, see the documentation for your database. For details about saving an SQL script of the changes you made in your diagram, see Saving a Change Script.


Diagrams Affected by Another User's Changes

Diagrams Affected by Another User’s Changes

In a multi-user environment, your database diagram can be affected by changes other users have saved to:

  • Your diagram, which other users changed since you opened the diagram.

  • Database objects shared between diagrams.

  • The database.

For example, your diagram might contain a table that another user deleted or renamed. In such a case, your diagram will no longer reflect the current state of the database. When you attempt to save your database diagram or selected tables, the Database Changes Detected dialog box notifies you that the database has been updated since you opened your diagram.

This dialog box also displays a list of database objects that will be affected as a result of saving your diagram or selection. At this point, you can take one of these actions:

  • Save your diagram or selection and update the database with all the changes in the list. This action will also affect other diagrams that share the same database objects.

    For example, suppose you edit the au_id column in the titleauthors table on your diagram and another user’s diagram contains the authors table which is related to the titleauthors table by the au_id column. Saving your diagram will affect the other user’s diagram. Similarly, suppose that another user defined a check constraint for the qty column in the sales table. If you delete the qty column and save the sales table, the other user’s check constraint will be affected.

  • Cancel the save action. You can then close the diagram without saving it. When you reopen or recreate the diagram, it will be in synch with the database.

  • Save a list of the changes. You can save the list of database changes shown in the Database Changes Detected dialog box to a text file in the project directory so that you can investigate the cause of other users’ changes.

    For example, if another user edited a table that you marked for deletion, you may want to research whether the table should be deleted before updating the database.


Database Objects Deleted by Another User

In a multi-user environment, deleting database objects from the database can affect other users. If another user deletes a database object that appears in your database diagram, the effect of the deletion on your diagram depends on where the object was deleted.

Where the object was deleted | How your database diagram is affected
In another copy of your database diagram | The deleted object is removed from your diagram.
In a different database diagram | The deleted object is removed from your diagram.
In the database | If your diagram has no unsaved changes to that object, the object will be removed from your diagram the next time you open it. If your diagram contains unsaved changes to that object, the object will remain in your diagram. You can recreate it in the database by saving your diagram.

Note Recreating a deleted object creates a new definition of that object in the database; it does not restore the data that was deleted when the object was deleted.

For example, if the titles table is deleted in the database and you have unsaved changes to the titles table in your database diagram, then saving your diagram will create a new titles table in the database. Any data that existed in the titles table before it was deleted is not restored.

For details about saving a diagram when the database has changed, see Reconciling a Database Diagram with a Modified Database.


Reconciling a Database Diagram with a Modified Database

You save your database diagram when you’re ready to update the database to match your diagram. However, if other users have updated the database since you opened your diagram, their changes might affect your diagram and vice versa. In such cases, saving your diagram will automatically:

  • Recreate database objects that are referenced in your diagram but that another user deleted.

  • Preserve triggers that were added to a table; triggers that were deleted from a table are not preserved.

  • Delete an object that another user edited because you deleted it from your diagram.

Saving your diagram will reconcile the database with your diagram by overwriting other users’ changes so that the database will match your diagram.

To reconcile your diagram with a modified database

  1. Save your database diagram.

    If you have not previously saved your diagram, type a name for the diagram in the Save New Database Diagram dialog box and choose OK.

  2. The Save dialog box lists the tables that will be affected when you save your diagram. Choose Yes to continue.

  3. The Database Changes Detected dialog box lists the objects that were modified and will be changed to match your diagram. Choose Yes to save the diagram and accept the list of changes.

Note If your diagram contains tables and columns that were deleted in the database, only their definitions are recreated in the database when you save your diagram. This process does not restore any data that was stored in these objects prior to their deletion.


Controlling Database Changes

The Database Designer provides tools to help you make changes to your database. You can control when and how changes to a database made in a database diagram are saved by noting which objects have been changed and which remain unchanged in the database diagram, by saving changes only to selected tables, and by rolling back unwanted changes. You can also use SQL change scripts to track, rollback, and apply unsaved changes.

To | See
Use database diagrams to control changes to the database | Controlling Database Changes Through Database Diagrams
Save changes to a selected table | Saving Selected Tables
Save a change script | Saving a Change Script
Return to a previous version of a database diagram without saving changes | Rolling Back Unsaved Database Changes
Ensure that database objects have a unique name | Uniquely Naming Database Objects


Controlling Database Changes Through Database Diagrams

Database diagrams enable you to modify your database objects without updating the database until you explicitly save the changes you’ve made. If you modify a table and remove it from a diagram without saving it or you close your diagram without saving it, the table continues to exist in memory in its modified state until you close the Database Designer.

During an editing session, you have the freedom to experiment with different object definitions to see how a proposed modification will affect the database. When you complete your modifications, you can either save your diagram and thereby update the database to match your diagram, or you can discard it and leave the underlying database unchanged.

In this topic you can read about:

  • Differentiating Saved from Unsaved Database Changes

  • Using Change Scripts to View Unsaved Changes

Differentiating Saved from Unsaved Database Changes

Identifying Modified Tables

When you edit a table in a database diagram, an asterisk (*) appears after the table name in the title bar to indicate that the table contains changes that you have not yet saved in the database.

This indicator appears as a result of a change you made to a database object, such as a column or index, in the table or your diagram. When you add a modified table to another open diagram, the table appears there with its unsaved changes and an asterisk in its title bar. When you save the table or the diagram, the asterisk disappears.

Identifying Modified Diagrams

Similarly, an asterisk (*) appears at the end of the diagram name in the title bar to indicate that the diagram contains changes that are not yet saved in the database.

This indicator appears whenever a database object in your diagram has an unsaved change or the diagram layout changed since you last saved it. When you save the diagram, the indicator disappears.

Using Change Scripts to View Unsaved Changes

At any point during your editing session, you can view unsaved changes for your diagram in an SQL change script displayed in the Save Change Script dialog box. If you don’t have security permissions to alter a database, or if you’re not ready to update the database but you want a record of your changes, you can save a change script and apply it to the database at a later time. For information about running change scripts, consult your database documentation.

For more information about change scripts, see Saving a Change Script.


Saving Selected Tables

You can save a specific table or a set of tables if you don’t want to save all the changes you made in a database diagram.

To save selected tables

  1. In your database diagram, select the tables you want to save.

  2. From the File menu, choose Save Selection.

  3. The Save dialog box displays the list of tables that will be updated in the database when you save your selection.

    Choose Save Text File if you want to save the list of tables in a text file in the project directory before continuing. When a message box displays the name of the saved text file, choose OK.

  4. In the Save dialog box, confirm the list of tables and choose Yes to save these tables.

Note The list of tables may contain tables in addition to those selected. For example, if you change the datatype of a column that participates in a relationship with another table, both tables will be included in this list.


Saving a Change Script

You can save an SQL change script if you don’t have security permissions to alter a database or if you’re not ready to update the database (for example, if you've made changes to the database diagram that conflict with changes made by other users). An SQL change script provides a record of your changes that can be applied to the database at a later time using a database tool (for example, Microsoft® SQL Server’s™ isql command-line utility).

To save a change script

  1. From the File menu or the Database Designer toolbar, choose Save Change Script. This command is available whenever you have unsaved database changes in your diagram.

  2. In the Save Change Script dialog box, choose Yes.

Note If the option to automatically generate a change script is selected, a change script is generated whenever you save your database diagram or any changed database object in the diagram. This is helpful if you need to track the changes you have made to the database.

  3. A message box displays the file name of the saved change script. Choose OK.

Each time you save a change script, a new text file named DbDgmN.sql (where N equals 1 for the first change script you generate and N+1 for the next change script) is created and saved in the current working directory.

The change script file lists any changed tables and how they were changed (using the DROP TABLE, ALTER TABLE, or CREATE TABLE SQL statements). The change script file also contains any error handling code that is required to clean up temporary tables or to rollback transactions that were part of unsuccessful changes (changes that couldn't be saved). In addition, the change script file contains code to make the script run successfully against the database and code (Print statements) that describe what the script is doing when it runs.

Any error messages that occurred while the changes were saved are stored in a log file, with the same name as the script file, except with a .log extension. You can also view messages showing which tables were successfully and unsuccessfully saved in the Log Viewer.


Rolling Back Unsaved Database Changes

You can discard changes in your database diagram that you don’t want to save in the database. For example, if changing a column property in your diagram affects tables that are not represented in your diagram, you may want to abandon the change to avoid making changes to those tables.

To roll back unsaved database changes

  1. Close your database diagram.

  2. A message prompts you to save your changes to the diagram. Choose No.

Caution Other open diagrams might be affected by your changes even though you closed the diagram without saving it. To be sure that your changes, which still exist in memory, do not affect open diagrams, close all diagrams in your editing session without saving them. If you want to update the database with changes to other diagrams only, save those diagrams before closing the one whose changes you want to discard.


Uniquely Naming Database Objects

The database catalog in your database contains one row for each object (constraint, default, log, rule, stored procedure, etc.) created within a database. Because the name of any object must be unique in the database, you cannot assign the same name to two different objects, even if they are different object types (for example, a table and a check constraint).

When you name database objects in a database diagram, you will be alerted if the name you choose is already used by another object. An error will occur in the following situations when you attempt to give an object a name already defined in the database catalog:

Object you attempt to name | Object already named in the database catalog | Outcome
Table | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Accepted in the diagram, but causes an error when you attempt to save
 | Index | Accepted
Relationship | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Error
 | Index | Accepted
Column | Table | Accepted
 | Relationship | Error
 | Column | Error if within same table; accepted across tables
 | Constraint | Error
 | Index | Accepted
Constraint | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Error
 | Index | Error
Index | Table | Error
 | Relationship | Error
 | Column | Accepted in the diagram, but causes an error when you attempt to save
 | Constraint | Error
 | Index | Error


Working with Database Objects

You can easily manage your database graphically through database diagrams. You can use database diagrams to create, edit, manage, or delete database objects (tables, table columns, table relationships, constraints, stored procedures, triggers) while you’re directly connected to the database in which those objects are stored. In the diagram, you can easily see the relationship between the objects in your database. You can also define and edit the properties of the database objects all from within your database diagram.

The tables represented in your diagrams are merely references to tables that reside in the database. An individual database table can exist in more than one database diagram. Thus, a table that appears in many database diagrams actually exists in only one place, the server database itself.

When you modify a table in a database diagram, your modifications are immediately applied to that table in every other diagram that it appears in. Similarly, when you remove a table from a database diagram, it is also removed from the other diagrams that it appears in. Therefore, if you delete a table in a multi-user environment, the table will be removed from the database diagrams of all other users.

When you save a database diagram, all changes you made to the tables in your diagram and their related objects are saved in the server database. You can choose to select only certain tables in your database diagram and save only those tables without affecting the other tables in the diagram.

In most databases, if you perform any of the following actions on a database table, the table will be automatically recreated in your database when you save the table or the database diagram. The table must be recreated in the database in order for your database to accept your changes.

  • Change the properties of an existing column.

  • Append a column that doesn’t allow nulls to the end of an existing table.

  • Add a column in the body of an existing table.

  • Reorder existing columns.

  • Delete an existing column.

When you save a table on which you’ve performed any of these actions, any triggers, bound defaults, and rules associated with each table are also saved.

For information about | See
Creating tables, changing the table view, adjusting table size, duplicating tables, adding columns to tables | Tables
Inserting, moving, deleting columns in database tables and setting properties for those columns | Columns in a Database Table
Defining relationships and enforcing referential integrity between tables | Table Relationships
Creating indexes to make accessing the information in your tables easier | Indexes
Working with constraints to limit the values that can be entered in tables | Constraints
Creating, editing, and running stored procedures | Stored Procedures
Creating, editing, and running triggers | Triggers


Tables

A database consists of one or more tables. A table is a collection of data, arranged in rows and columns. For example, you might have a table for author information called authors. Each column would contain a certain type of information, such as the author’s last name. Each row would contain all the information about a specific author: first name, last name, address, and so on.

In a database, you might have a number of tables, each devoted to a specific topic. For example, the pubs database might contain tables for authors, titles, and so on. Using a separate table for each topic can eliminate duplicate data, make data storage more efficient, and reduce data-entry errors.

Tables are the basic building blocks of database diagrams. In a database diagram, each table is laid out in a matrix so that you can see all the properties defined for every column in your database table.

Tables in a Database Diagram

Each table in a database diagram has three distinct features: a title bar, a row selector, and a set of property columns.

  • Title Bar The title bar shows the name of the table. If another user owns the table, then that user’s name appears in parentheses at the end of the table name.

    For information about table owners, see Working in a Multi-User Environment.

    If you have modified a table and have not yet saved it, an asterisk (*) appears at the end of the table name to indicate unsaved changes. For information about saving modified tables and diagrams, see Controlling Database Changes.

    or

  • Row Selector You can click the row selector [image] to select a database column in the table. The row selector displays a key symbol [image] if the column is in the table’s primary key. For information about primary keys, see Defining a Primary Key.

  • Property Columns The set of property columns is visible in the Column Properties view or Customized view of your table. You can view a table in any of five different views to help you manage the size and layout of your diagram.

    For more information about column properties, see Column Properties. For more information about table views, see Changing a Table View.

Before you begin defining the columns for a table, determine what type of data the table will hold and how that table relates to the other tables in your database.

Designing Tables

To determine the structure of a new table, you need to decide:

  • What type of data the table will contain.

  • What columns you need in the table and the data type (and length, if required) for each column.

  • Which columns should accept null values. For information about data types, allowing null values, and other column properties, see Columns.

  • Whether to use constraints and if so, where. For more information, see Constraints.

  • What types of indexes you need, where you need them, and which columns should be the primary key and foreign key. For more information, see Indexes.

After you decide on the structure of your table, you can create the table and define its columns in your database diagram. You can also alter the table’s appearance in your diagram so that the information you need is visible when you need it. When you save your table or the diagram, the table is created in your database.

The Database Designer has two modes for working on tables. You can view tables directly in a database diagram using Column Properties view or you can open a single table in design mode by right-clicking the table name and choosing Design. This opens the table in a single window where you can define columns and properties for the table.

If you know exactly what you want in a table, it is often most efficient to define everything you need at the beginning, including the table’s data restrictions and additional properties. However, in many cases, you’ll do best to first create a basic table and save it so it is created in your database. You can then add some test data to the table and experiment with the table in the database diagram to fine-tune its design.

The Database Designer enables you to try out different designs by working with tables in your diagram. Through experimentation, you can determine what types of data are frequently entered and queried and then redesign your table accordingly.

When you change a table’s design in a database diagram, any data that is stored in the table is preserved to the extent possible. When you’re satisfied with your basic design, you can add constraints, indexes, and any additional columns that you require. For more information, see Working in Database Diagrams.

To | See
Create a new table in your database, add existing tables or related tables to your database diagram | Adding Tables to a Database Diagram
Copy a table from one database diagram to another diagram | Copying a Table Across Database Diagrams
Create a new table that contains some of the same columns as an existing table in your diagram | Duplicating Tables
Deleting a table from a database diagram and the database Removing a Table from a database Diagram
Deleting a Table from a Database Diagram and the Database
Change the name of a table in a database diagram and in the database | Renaming a Table
Change the amount of information shown for the tables in the diagram | Changing a Table View
Change the size of the table window in the diagram | Adjusting the Table Size
Add or delete columns to a table, change column property settings | Columns


Adding Tables to a Database Diagram

You can add a table to your database diagram to edit its content or relate it to other tables in your diagram. You can either add existing database tables to a diagram or insert a new table that has not yet been defined in the database.

  • Inserting a New Table

  • Adding an Existing Table

  • Adding Related Tables

Inserting a New Table

Adding a new table to the database diagram means that you are defining a new table that doesn’t already exist in the database. To create a new table, you must define the individual columns that make up the table. The table is created in the database when you save the table or the diagram.

To insert a new table into a diagram

  1. Make sure you’re connected to the database in which you want to create the table.

    To create a table in your current diagram, click the New Table button [image] on the toolbar.

    –or–

    Right-click in the diagram, and select New Table.

  2. In the Choose Name dialog box, change the system-assigned name of the table if you want, and then choose OK.

    A new table appears in the diagram in Column Properties view.

  3. In the first cell of the new table, type a column name. Then press the TAB key to move to the next cell.

  4. Under Datatype, select a data type for the column. Each column must have a name and data type.

    You can set other properties for the column by typing or selecting values, or you can accept the default settings.

  5. Repeat steps 3 and 4 for each column you want to add to the table.

When you save your database diagram, the new table will be added to your database.

Note If you create a new table, then remove it from the diagram before saving it to the database, the table name remains in memory until you close the database diagram. Also, if you delete an existing table from the database, the table name remains in memory. To use the table name again, close and restart the Database Designer.

Adding an Existing Table

Adding an existing table means that the table you want to appear in your diagram already exists in your database. If you add a group of tables to a diagram, any relationships that exist between the tables are also added to the diagram.

To add an existing table to a diagram

  1. Make sure you’re connected to the database whose objects you want to edit.

  2. Select a table in the Tables folder.

  3. Drag the table into your database diagram.

  4. Release the mouse button.

If relationships exist between the selected table and other tables in your diagram, relationship lines are automatically drawn.

When you add a table to a diagram, the definition of the table (not the data that is stored in the table) is loaded from your database into memory. At that point you can edit the table’s definition, for example by adding new columns or modifying the objects that are attached to it.

Adding Related Tables

For tables with existing foreign key constraints, you can easily add the related tables to the database diagram.

To add related tables to a diagram

  1. Select one or more tables with foreign key constraints in the database diagram.

  2. Right-click on any of the selected tables and choose Add Related Tables.

Both those tables referenced by a foreign key constraint from the selected table(s) and those referencing the selected table(s) with a foreign key constraint are added to the diagram.


Changing a Table View

When you’re working with only a few tables in a database diagram, it’s usually helpful to view as much column information as possible. Such a view not only gives you more information, but it also enables you to edit the column definitions.

When you’re working with a large number of tables, however, it’s usually preferable to view only the column names, or only the table name, so that you can see more of the tables in your diagram at once.

In a database diagram, you can expand the tables you want to edit as needed and then collapse them again to save space on the diagram.

Each table in a database diagram can be displayed in one of five views.

  • Column Properties [image] Shows a grid of all the table columns, column properties, and property settings. You can edit the column properties directly by typing in a cell or using the Cut, Copy, and Paste commands. You can also move and delete entire column definitions. You can configure the grid to show a subset of all the available properties for the columns in a table.

    When you insert a new table into a diagram, it is shown in this view so that you can begin defining each column.

  • Column Names [image] Shows the names of all the columns in the table listed by name. You can rename the column names in this view. When you add an existing table to a diagram, it is shown in this view.

  • Keys [image] Shows the names of all the columns in the table that are primary keys or foreign keys or that have unique constraints. You can rename the columns in this view.

  • Name Only [image] Represents a table in its minimized state and shows only the table name.

  • Custom [image] Displays only the columns you choose. This gives you the flexibility to display only the information you want. This view is also useful for printing the database diagrams, because you can display more tables on one page, and won't normally see horizontal scroll bars on the tables. For more information, see Printing and Previewing Database Diagrams.

    The default set of columns for the Custom view includes Column Name, Condensed Datatype, and Nullable.

    Column | Setting
    Column Name | The name of the field in the table.
    Condensed Datatype | Information about the field's data type, in the same format as the SQL Create Table statement. For example, a field containing a variable-length string with a maximum length of 20 characters would be represented as varchar(20).
    Nullable | Null (the field can contain a Null value) or Not Null (the field must contain a non-null value).

To change a table view

  1. In your database diagram, select the tables you want to see in another view. To change the view of all the tables in your diagram, choose Select All from the Edit menu.

  2. Right-click the table and select the desired view from the shortcut menu.

    -or-

    Click the corresponding button on the toolbar to change the view of the selected tables:

    Click this button | Button name | To
    Column Properties Add, rename, or delete columns,
    create relationships to other tables,
    edit column properties
    Column Names Add, rename, or delete columns,
    create relationships to other tables
    Keys Add, rename, or delete key columns,
    create relationships to other tables
    Name Only | Minimize tables
    Custom Add, rename, or delete the property columns you've chosen to display in the property grid,
    create relationships to other tables,
    edit column properties for the columns you've chosen to display

When you finish editing a table, you can change it to a different view or resize it to create more space on the diagram.

To modify the Custom view

  1. In your database diagram, right-click the table you want to see in Custom view.

  2. From the shortcut menu, choose Modify Custom View. The Column Selection dialog box appears.

  3. Use the arrows to move the desired columns from the Available columns box to the Selected columns box.

    Note To add a column, highlight the column in the Available columns box and click the > button. The column will then be listed in the Selected columns box. To display all columns, click the >> button. To remove a column from the Selected columns box, highlight the column and click the < button.

  4. The columns will appear in the table in the order they are displayed in the Selected columns box. Use the Sort arrows to rearrange the columns in the Selected columns box to the desired order.

  5. To make this setting the default Custom view, select the Save as default box.

    Note If the Save as default box is not selected, the columns listed in the Selected columns box will be displayed for all the database tables displayed in Custom view on the current diagram. However, this setting will not be saved and is not applied to other diagrams when you choose the Custom view command.

  6. Click OK.

The selected table is redrawn to display the columns chosen in the dialog box.


Adjusting the Table Size

You can adjust the size of a table in the diagram in any of its five views. For example, you can enlarge a table in Column Properties view to see all of the properties for its columns without having to scroll the table horizontally. For details about table views, see Changing a Table View.

A minimized table can be resized only horizontally.

To automatically adjust the table size

  1. Select the table(s) you want to resize.

  2. Right-click the table and choose Autosize Selected Tables from the shortcut menu.

    The table and the columns within the table are adjusted to show all the information in the displayed columns.

To manually adjust the table size

  1. Position the pointer over the table border.
    To adjust the table… | Position the pointer over the table’s… | Until the pointer changes to…
    height | top or bottom edge
    width | left or right edge
    height and width | corner | or

  2. Hold down the left mouse button and drag the table border to its new size.

  3. Release the mouse button.


Copying a Table Across Database Diagrams

You can copy a table from one database diagram to another in the same database.

Copying a table from one database diagram to another diagram merely adds a reference to the table in the second diagram. The table is not duplicated in your database. For example, if you copy the authors table from one database diagram to another, each diagram references the same authors table in the database.

To copy a table from another database diagram

  1. Make sure you’re connected to the database whose table you want to copy.

  2. Open a database diagram and select the table that you want to copy to your other database diagram.

  3. Click the Copy button on the toolbar. This action places the selected table definition on the Clipboard.

  4. Switch to the diagram where you want to paste the selection. This diagram must be in the same database as the diagram that you’re copying from.

  5. Click the Paste button on the toolbar. The Clipboard contents appear at the new location and remain highlighted until you click elsewhere. If relationships exist between the selected tables and other tables in your diagram, relationship lines are automatically drawn.

When you edit the table in either diagram, your changes are reflected in both diagrams. Similarly, once you save the table in either diagram, the table is no longer considered "modified" in either diagram.


Duplicating a Table

A table can appear only once in a database diagram. However, if you want to create a new table that contains some of the same columns as an existing table in your diagram, you can duplicate the existing table as the first step in creating your new table. Then in your new table, you can delete unwanted columns, add new columns, and assign a unique table name.

Use the same technique for duplicating tables across database diagrams.

To duplicate a table

  1. In the database diagram where you want to duplicate the table, right-click the diagram and choose New Table from the shortcut menu.

    -or-

    Click the New Table button [image] on the Database Diagram toolbar.

    A blank table is added to your diagram.

  2. In the Choose Name dialog box, change the system-assigned name of the new table.

  3. In the table you want to duplicate, select all the columns. This table can be in the same diagram, a different diagram in the same database, or a diagram in a different database.

  4. Copy the columns to the blank table. For details about copying columns, see Copying Columns from One Table to Another.


Renaming a Table

When you rename a table, the table name is automatically updated in every database diagram in which the table appears. It is updated in the database when you save the table or diagram.

To rename a table

  1. In your database diagram, select the table you want to rename.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Tables tab.

  4. In the Table name box, type a new name. Be sure to choose a name that doesn’t duplicate one in the Selected table list.

    To cancel this action, press the ESC key before leaving this field.

  5. Click OK.

The table is renamed in the diagram as soon as you exit the Table name box.

Note Because the table name is used to automatically create and name relationships, indexes, and constraints, it is recommended that you make any changes to the name of your table before you create these database objects.


Removing a Table from a Database Diagram

Remove a table from your database diagram if you do not want it to appear in the diagram. Removing a table does not alter your server database. The table and its relationships to other tables continue to exist in the database.

If you remove a table that has been changed either by you or another user, a message prompts you to save the table before removing it:

  • If you save the table before removing it, the database is updated with the changes.

  • If you discard changes to the table before removing it, the table remains in memory in its modified state until you save the table or close the last open database diagram, even though the table no longer appears in your diagram.

For example, suppose you add a table to your diagram so that you can copy its column definitions for address data to a new table you are creating. If you cut the column definitions in the existing table instead of copying them, that table would be marked as modified. In this case, you would discard your changes to that table before removing it. However, if you wanted to move those column definitions to your new table and then remove the existing table from your diagram, you would save your changes to the existing table before removing it.

To remove a table from a database diagram

  1. In your database diagram, select the table you want to remove.

  2. Right-click the table and choose Remove Table from Diagram from the shortcut menu.

    -or-

    Click the Remove Table from Diagram button [image] on the Database Diagram toolbar.

    If the table has unsaved changes as a result of edits made in the database diagram by you or another user, a message prompts you to save the table before removing it.

The table is removed from your diagram but it continues to exist in the database.

Note If you create a new table, then remove it from the diagram before saving it to the database, the table name remains in memory until you close the database diagram. Also, if you delete an existing table from the database, the table name remains in memory. To use the table name again, close and restart the Database Designer.


Deleting a Table from a Database Diagram and the Database

Delete a table from your database diagram when you want to:

  • Remove the table from your diagram.

  • Remove the table from every other diagram in which it appears.

  • Mark the table for deletion from the database.

A table that is marked for deletion is permanently deleted from the database when you save your diagram. A reference to that table continues to exist in memory until you save the diagram. If you close the diagram without saving it, the table will continue to exist in your database and appear in your diagram and every other diagram in which it appeared before you marked it for deletion.

To delete a table from the database

  1. In your database diagram, select the table you want to delete.

  2. Right-click the table and choose Delete Table from Database from the shortcut menu.

  3. A message box prompts you to confirm the deletion. Choose Yes.

Note Deleting a table in a database diagram automatically removes any relationships to it.


Columns in a Database Table

In a table, data is arranged into columns. Each column stores one data element, such as a first name, one line of an address, a price, or any similar discrete unit of information.

When columns are created in a table, they are given a name that identifies their purpose, such as FirstName or Address1. In most databases, you must also specify additional properties, such as how long the longest entry in the column will be, and what type of data the column will contain - characters, integers, floating-point numbers, dates or times, and so on. Other column properties can include whether the column is the table's primary key, whether users must enter a value into it, and what its default value is.

You can edit the column properties for tables directly in the database diagram. For details about which properties are available in your database, see your database documentation.

To | See
Add new column definitions to the end of a table | Inserting Columns into a Table
Copy the column definitions from one table to another table in the same diagram or in different diagrams | Copying Columns from One Table to Another
Move the column definitions from one table to another table in the same database diagram or in a different diagram | Moving Columns from One Table to Another
Delete columns from a table and from the database | Deleting Columns from a Table
Set or edit the column definition (properties) for a database table | Column Properties


Inserting Columns into a Table

You can add new column definitions to a table to capture additional data that isn’t already stored in an existing column. The Column Properties view, which shows a table with all of its currently defined columns, provides blank grid rows so that you can easily add new column definitions to your database table.

To insert columns into a table

  1. In your database diagram, select the table that you want to add new columns to.

  2. If the table is not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. Right-click a row in the table and select Insert Column from the shortcut menu. A blank column row is inserted.

    -or-

    Place the cursor in the first blank cell in the Column Name column.

  4. In the Column Name column, type the column name in the cell. The Column Name is a required value.

  5. Press the TAB key to go to the Datatype cell. This is a required value.

The default values for your database are added when you create a new column. Define other properties for the column as needed. You can change any of these values and set additional properties at any time according to the rules of your database. For more information about the column properties available to you, refer to your database documentation.


Copying Columns from One Table to Another

You can copy columns from one table to another table in the same diagram or in different diagrams. Copying a column involves only the column definition. The data itself is not automatically transferred to the second table as part of this process.

Tip You can use database queries to copy the column's data from the original column to the new column. Use the Query Designer to run an update query to add the data to the table to which you copied the columns. For details, see Creating Update Queries. For information about the Query Designer, see Designing Queries.

To copy columns from one table to another

  1. In your database diagram, select the columns that you want to copy.

  2. Click the Copy button on the toolbar. This action copies the selection from the table and places the column and its current set of properties on the Clipboard.

  3. Position the cursor in the table at the location where you want to insert the columns.

  4. Click the Paste button on the toolbar. The column and its properties are inserted at the new location and remain highlighted until you click elsewhere.

When you copy a database column that has a user-defined data type from one database to another, the user-defined data type may not be available in the destination database. In such a case, the column will be assigned the nearest matching base data type available in that database.


Moving Columns from One Table to Another

You can move columns from one table to another table in the same database diagram or in a different diagram. Moving columns in the database diagram moves the column definition only. The data itself is not automatically transferred to the second table as part of this process.

Tip To move both the column’s definition and its data, you can use the Query Designer in conjunction with the Database Designer. For information about the Query Designer, see Designing Queries.

To move columns without data from one table to another

  1. In your database diagram, select the columns that you want to move.

  2. Click the Cut button on the toolbar. This action deletes the selection from the table and places the column and its current set of properties on the Clipboard.

  3. Position the cursor in the new table at the location where you want to insert the columns.

  4. Click the Paste button on the toolbar. The columns are inserted at the new location and remain highlighted until you click elsewhere.

To move columns with data from one table to another

  1. In your database diagram, select the columns that you want to move.

  2. Click the Copy button on the toolbar. This action places the selection with its current set of properties on the Clipboard.

  3. Position the cursor in the new table at the location where you want to insert the columns.

  4. Click the Paste button on the toolbar. The columns are inserted at the new location and remain highlighted until you click elsewhere.

  5. Run an update query to add the data to the table to which you copied the columns. For details, see Creating Update Queries.

  6. Return to the database diagram and delete the columns from the original table. For details, see Deleting Columns from a Table.


Deleting Columns from a Table

Delete columns from a table when they’re no longer needed to store data. When a column is deleted from the table in the database diagram, it is also deleted from the database.

Caution This action cannot be undone once the database diagram or table is saved. The only way to restore a deleted column is to close the table or database diagram without saving changes.

To delete columns from a table

  1. In your table or database diagram, select the column you want to delete.

  2. Right-click the column and choose Delete Column from the shortcut menu.

  3. If the column participates in a relationship, a message prompts you to confirm the deletion of the selected columns and their relationships. Choose OK.

The column, any constraints attached to it, any relationships it participates in, as well as the data that’s stored in the column are removed from the database diagram. They are deleted from the database when you save the table or database diagram.


Column Properties

Each column in a table has a set of properties. Each property defines one characteristic, such as the name, data type or length, of a column. The entire set of properties for a column makes up that column’s definition in your database table.

You can set column properties directly in your database table in a database diagram. Three column properties are required — the column name, data type, and length — before you can save a table in your database. You can redefine a column by editing any of its properties. For example, you can rename a column, alter its length, specify a default value, and so on.

When you view your table in Column Properties view, the column properties are laid out in a grid. In this grid, you can choose which properties you want to see. You can hide the properties that you rarely define and show the properties that you define more frequently. You can also resize the columns in the grid so that the properties are easy to read.

For more information about showing, hiding, and resizing property columns, see:

  • Setting Column Properties

  • Resizing Property Columns

  • Changing Which Properties Appear

  • Renaming a Column

For more information about the specific column properties available in your database, see your database documentation.


Setting Column Properties

You can set or change the properties of a column within the grid that appears when you view the table in Column Properties view or when you design a single table.

To set column properties

  1. In your database diagram, select the table whose column properties you want to define.

  2. If you're not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. Click inside the cell that shows the property setting that you want to change. You may have to scroll or enlarge the table to see the property.

  4. Type or select a new setting.

Note The data types available in your database typically have default values. Many databases have rules concerning allowable property values. For example, a binary data type is often limited to a length between 1-255. If you type an invalid value for properties with such limitations, a message box will appear.

The new setting takes effect in the database diagram as soon as you press the TAB key or click outside the cell. The new setting is saved in the database when you save the table or your diagram.

Note You can also set column properties in Custom view for any columns you've chosen to display in this view. For more information about Custom view, see Changing a Table View.


Resizing Property Columns

You can manually change the width of a property column in a database table by resizing it in Column Properties view. For example, you can widen the Datatype column if it contains user-defined data type names that are too long to see in their entirety. You can also automatically resize a property column to fit its widest entry.

To manually change the width of a property column

  1. In your database diagram, select the table whose property columns you want to resize.

  2. Position the pointer along the right border of the column header for the column that you want to resize. The cursor changes from an arrow to a splitter pointer [image].

  3. Drag the column border to the left to reduce its width or to the right to increase its width.

  4. Release the mouse button.

To resize a property column to fit the widest entry

  1. In your database diagram, select the table whose columns you want to resize.

  2. Position the pointer along the right border of the column header for the column that you want to resize. The cursor changes from an arrow to a splitter pointer [image].

  3. Double-click the splitter pointer.

Note You can also resize property columns in Custom view for any columns you've chosen to display in this view.


Changing Which Properties Appear

When you show a database table in Column Properties view, most but not all of that table’s property columns are visible without scrolling. You can customize this view by choosing whether to hide or show each property column in a database table. For example, you could hide the Precision and Scale properties, which you rarely change, in order to show more of the frequently changed properties.

To hide a property column

  1. In your database diagram, select the table whose property column you want to hide.

  2. Position the pointer along the right border of the column header for the column that you want to hide. The cursor changes from an arrow to a splitter pointer [image].

  3. Drag the column border to the left until it meets the column’s left border.

  4. Release the mouse button.

To show a property column that is hidden

  1. In your database diagram, select the table whose property column you want to show.

  2. Position the pointer along the right border of the previous column’s header. The cursor changes from an arrow to a splitter pointer [image].

  3. Double-click the splitter pointer. The hidden column resizes to fit the widest entry.

Note You can also set which column properties you want to display for database tables in a database diagram by using Custom view. For information on this view, see Changing a Table View.


Renaming a Column

The name of a column in a table in your database diagram shows the name of the column as it is stored in the database. You can rename a column directly in your table in the database diagram and the database will be updated with the new name when you save the table or diagram.

Column names are stored in the case (uppercase or lowercase) in which they appear in your diagram. They cannot contain blank spaces.

Warning Because renaming a column may affect triggers, stored procedures, and constraints, it’s recommended that you rename a column before you create these other objects. For more information about these database objects, see Working with Database Objects.

To rename a column

  1. In your database diagram, select the table whose column you want to rename.

  2. If only the table name is shown in the database diagram, right-click the table and select Column Properties, Column Names, or Keys from the shortcut menu.

  3. In the cell that shows the column name you want to change, type a new column name. Make sure that it doesn’t duplicate another column name in the same table.

The column is renamed in your table or diagram as soon as you exit the cell that shows the column name. The column is renamed in your database when you save the table or diagram.


Table Relationships

You can create relationships between your tables in a database diagram to show how the columns in one table are linked to columns in another table.

In a relational database, relationships enable you to prevent redundant data. For example, if you are designing a database that will track information about books you might have a table called titles that stores information about each book, such as the book’s title, date of publication, and publisher. There is also information you might want to store about the publisher, such as the publisher's phone number, address, and zip code. If you were to store all of this information in the titles table, the publisher’s phone number would be duplicated for each title that the publisher prints.

A better solution is to store the publisher information only once in a separate table, publishers. You would then put a pointer in the titles table that references an entry in the publisher table.

To make sure your data is not out of sync, you can enforce referential integrity between the titles and publishers tables. Referential integrity relationships help ensure information in one table matches information in another. For example, each title in the titles table must be associated with a specific publisher in the publishers table. A title cannot be added to the database for a publisher that does not exist in the database.

For a better understanding of table relationships, see:

  • Defining Table Relationships

  • Enforcing Referential Integrity

Defining Table Relationships

A relationship works by matching data in key columns — usually columns with the same name in both tables. In most cases, the relationship matches the primary key from one table, which provides a unique identifier for each row, with an entry in the foreign key in the other table. For example, sales can be associated with the specific titles sold by creating a relationship between the title_id column in the titles table (the primary key) and the title_id column in the sales table (the foreign key).

There are three types of relationships between tables. The type of relationship that is created depends on how the related columns are defined.

  • One-to-Many Relationships

  • Many-to-Many Relationships

  • One-to-One Relationships

One-to-Many Relationships

A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A. For example, the publishers and titles tables have a one-to-many relationship: each publisher produces many titles, but each title comes from only one publisher.

A one-to-many relationship is created if only one of the related columns is a primary key or has a unique constraint.

Many-to-Many Relationships

In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B. For example, the authors table and the titles table have a many-to-many relationship that is defined by a one-to-many relationship from each of these tables to the titleauthors table. The primary key of the titleauthors table is the combination of the au_id column (the authors table’s primary key) and the title_id column (the titles table’s primary key).

One-to-One Relationships

In a one-to-one relationship, a row in table A can have no more than one matching row in table B, and vice versa. A one-to-one relationship is created if both of the related columns are primary keys or have unique constraints.

This type of relationship is not common because most information related in this way would be all in one table. You might use a one-to-one relationship to:

  • Divide a table with many columns.

  • Isolate part of a table for security reasons.

  • Store data that is short-lived and could be easily deleted by simply deleting the table.

  • Store information that applies only to a subset of the main table.

Enforcing Referential Integrity

Referential integrity is a system of rules that ensure relationships between rows in related tables are valid and that you don't accidentally delete or change related data.

When referential integrity is enforced, you must observe the following rules:

  • You can't enter a value in the foreign key column of the related table if that value doesn't exist in the primary key of the related table. However, you can enter a null in the foreign key column. For example, you can't indicate that a job is assigned to an employee who isn’t included in the employee table, but you can indicate that an employee has no assigned job by entering a null in the job_id column of the employee table.

  • You can't delete a row from a primary key table if rows matching it exist in a related table. For example, you can't delete a row from the jobs table if there are employees assigned to the job represented by that row in the employee table.

  • You can't change a primary key value in the primary key table if that row has related rows. For example, you can't delete an employee from the employee table if that employee is assigned to a job in the jobs table.

You can set referential integrity when all of the following conditions are met:

  • The matching column from the primary table is a primary key or has a unique constraint.

  • The related columns have the same data type and size.

  • Both tables belong to the same database.

Enforced and Unenforced Relationships in Database Diagrams

Creating a relationship line in a database diagram automatically enforces referential integrity by creating a foreign key constraint on the related table. An enforced relationship appears in your database diagram as a solid line. For example:

An unenforced relationship, whose foreign key constraint is disabled, appears in your diagram as a dashed line. For example:

Depending on the features of your database, you can set options to disable the foreign key constraint for certain conditions, for example, during INSERT and UPDATE transactions.

To | See
Create relationships between database tables in a database diagram | Creating a Relationship Between Tables
Ensure each value entered in a foreign key column matches an existing value in the related primary key column | Enforcing Referential Integrity Between Tables
Link a column in a table with another column in the same table | Drawing a Single-Table Reflexive Relationship
Relate many rows in one table to many rows in another table | Mapping Many-to-Many Relationships to a Database Diagram
Change the name of a relationship | Renaming a Relationship
Remove the relationship between two tables | Deleting a Relationship
Disable a foreign key constraint | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements and Disabling a Foreign Key Constraint for Replication


Creating a Relationship Between Tables

You create a relationship between two tables when you want them to share data. You can store data in one of the tables, but make it available to both. You can also create a relationship to enforce referential integrity between related tables.

Before you create a relationship, you must first define a primary key or unique constraint in at least one of the tables. You then relate the primary key columns to matching columns in another table. Once you create the relationship, those matching columns become the foreign key of the related table. For more information, see Defining a Primary Key or Creating a Unique Constraint.

To create a relationship between tables

  1. In your database diagram, click the row selector [image] for the database column or combination of columns that you want to relate to a column in another table.

  2. While the pointer is positioned over the row selector, drag the pointer to the related table. To relate the selected columns to the primary key of the related table, drag the pointer to the related table’s title bar.

  3. Release the mouse button. The Create Relationship dialog box appears and attempts to match the columns you selected with columns of the same name and data type in the related table.

  4. In the Create Relationship dialog box, confirm that the columns you want to relate are shown in the Primary key table and Foreign key table lists.

  5. Choose OK to create the relationship.

The primary key side of the relationship is denoted by a key [image] symbol. In one-to-one relationships, the table that initiated the relationship determines the primary key side. For example, if you create a relationship from the pub_id column in the publishers table to the pub_id column in the pub_info table, then the publishers table is on the primary key side of the relationship.

The foreign key side of a relationship is denoted by a key [image] symbol for a one-to-one relationship or an infinity [image] symbol for a one-to-many relationship.

Tip If you want to see labels for relationship lines, use the Show Relationship Labels command. For more information on relationship labels and this command, see Adding Labels to Relationship Lines.


Enforcing Referential Integrity Between Tables

Referential integrity between tables is enforced by default when you create a relationship in your database diagram. An enforced relationship ensures each value entered in a foreign key column matches an existing value in the related primary key column.

You can change the conditions under which referential integrity is enforced by editing the relationship’s properties.

To change referential integrity options for a new relationship

  1. In your database diagram, create a relationship line. For details, see Creating a Relationship Between Tables.

  2. In the Create Relationship dialog box, clear or select one or more of the options.

    For information about the options available for SQL Server databases, see Database Designer Considerations for SQL Server Databases. For more information about the options available for Oracle databases, see Database Designer Considerations for Oracle Databases.

To change referential integrity options for an existing relationship

  1. In your database diagram, select the relationship line.

  2. Right-click the relationship line and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear or select one or more of the options.

    For information about the options available for SQL Server databases, Database Designer Considerations for SQL Server Databases. For more information about the options available for Oracle databases, see Database Designer Considerations for Oracle Databases.

The relationship is updated in the database when you save the diagram or either of the related tables.


Drawing a Single-Table Reflexive Relationship

You create a reflexive relationship to link a column in a table with another column in the same table. For example, suppose the employee table has an emp_id column and a mgr_id column. Because each manager is also an employee, you relate these two columns by drawing a relationship line from the table to itself. This relationship ensures each manager ID that is added to the table matches an existing employee ID.

Before you create a relationship, you must first define a primary key or unique constraint for your table. You then relate the primary key column to a matching column. Once you create the relationship, the matching column becomes the foreign key of the table.

To draw a reflexive relationship

  1. In your database diagram, click the row selector [image] for the database column that you want to relate to another column.

  2. While the pointer is positioned over the row selector, drag the pointer outside the table until a line appears.

  3. Drag the line back to the selected table.

  4. Release the mouse button. The Create Relationship dialog box appears and attempts to match the primary key columns with the non-key columns you dragged the line to.

  5. Confirm that the columns you want to relate are shown in the Primary key table and Foreign key table lists.

  6. Choose OK to create the relationship.

When you run queries against a table, a reflexive relationship is called a self-join. For information about querying tables with joins, see Querying Using Multiple Tables.


Mapping Many-to-Many Relationships to a Database Diagram

Many-to-many relationships enable you to relate many rows in one table to many rows in another table. For example, you could create a many-to-many relationship between the authors table and the titles table to match multiple authors to all of their books. Creating a one-to-many relationship from either table would incorrectly assume a book can have only one author, or that an author can write only one book.

Many-to-many relationships between tables are accommodated in database diagrams by means of junction tables. A junction table contains the primary key columns of the two tables you want to relate. You then create a relationship from the primary key columns of each of those two tables to the matching columns in the junction table.

To create a many-to-many relationship between tables

  1. In your database diagram, add the tables that you want to create a many-to-many relationship between.

  2. Create a third table by right-clicking the diagram and choosing New Table from the shortcut menu. This will become the junction table. For details, see Adding Tables to a Database Diagram.

  3. In the Choose Name dialog box, change the system-assigned table name. For example, the junction table between the titles table and the authors table is now named titleauthors. For details, see Renaming a Table.

  4. Copy the primary key columns from each of the other two tables to the junction table. You can add other columns to this table, just as you can to any other table. For details, see Copying Columns from One Table to Another.

  5. In the junction table, set the primary key to include all the primary key columns from the other two tables. For details, see Defining a Primary Key.

  6. Define a one-to-many relationship between each of the two primary tables and the junction table. For details, see Creating a Relationship Between Tables.

Note The creation of a junction table in a database diagram does not insert data from the related tables into the junction table. For information about inserting data into a junction table, see Creating Insert Queries.


Renaming a Relationship

You can rename a relationship if you want to abbreviate the system-assigned relationship name, or if you want to replace it with a user-defined name. When you rename a relationship, the relationship name is automatically updated in the current diagram and any other diagram in which it appears.

To rename a relationship

  1. In your database diagram, select the line representing the relationship that you want to rename.

  2. Right-click the relationship line and select Properties.

  3. Choose the Relationships tab.

  4. In the Relationship name box, type a new name. Make sure that it doesn’t duplicate any of the names in the Selected relationship list.

The relationship is renamed in the diagram and any other diagram in which it appears as soon as you exit the Relationship name box; it is renamed in the database when you save either of the related tables or the diagram.

Tip If you want to see labels for relationship lines, use the Show Relationship Labels command. For more information on relationship labels and this command, see Adding Labels to Relationship Lines.


Deleting a Relationship

Delete a relationship when you no longer want to relate columns in two related tables. When you redesign tables, it’s often necessary to delete relationships and then recreate them after your new design is complete. For example, if you decide to normalize a database and store all address data in one table, you would delete all the relationships to address columns between existing tables, create a new table containing the address columns, and then create relationships from the new address table to every table that requires an address.

To delete a relationship

  1. In your database diagram, select the line that represents the relationship that you want to delete from the diagram.

  2. Right-click the relationship line and choose Delete Relationship from Database from the shortcut menu.

  3. A message box prompts you to confirm the deletion. Choose Yes.

Note When you delete a relationship, the relationship line is removed from your diagram and every other diagram in which it appears. It is deleted from the database when you save the diagram or either of the tables that it related.


Indexes

You can use an index to gain fast access to specific information in a database table. An index is a structure that orders the values of one or more columns in a database table, for example the last name (lname) column of the employee table. If you were looking for a specific employee by his or her last name, the index would enable you to get that information faster than if you had to search all the rows in the table, which is sorted by employee ID.

The index provides pointers to the data values stored in specified columns of the table, and then orders those pointers according to the sort order you specify. The database uses the index much as you use an index in a book: it searches the index to find a particular value and then follows the pointer to the row containing that value.

In database diagrams, you can create, edit, or delete each type of index in the Indexes/Keys property page for a selected table. An index is saved in the database when you save the table that it’s attached to, or when you save the diagram in which that table appears. For details, see Creating an Index.

Note Not all databases work with indexes in the same way. For more information, see Database Server Considerations, or consult your database documentation.

As a rule of thumb, you should create an index on a table only if the data in the indexed columns will be queried frequently. Indexes take up disk space and slow the adding, deleting, and updating of rows. In most situations, the speed advantages of indexes for data retrieval greatly outweigh these disadvantages. However, if your application updates data very frequently or if you have disk space constraints, you might want to limit the number of indexes.

Before creating an index, you have two important tasks:

  • Deciding Which Columns to Index

  • Choosing the Type of Index

Deciding Which Columns to Index

You can create indexes based on a single column or on multiple columns in a database table. Multiple-column indexes enable you to distinguish between rows in which one column may have the same value.

Indexes are also helpful if you often search or sort by two or more columns at a time. For example, if you often set criteria for last name and first name columns in the same query, it makes sense to create a multiple-column index on those two columns.

To determine the usefulness of an index:

  • Examine the WHERE and JOIN clauses of your queries. Each column included in either clause is a possible candidate for an index.

  • Experiment with the new index to examine its effect on the performance of running queries.

  • Consider the number of indexes already created on your table. It’s best to avoid a large number of indexes on a single table.

  • Examine the definitions of the indexes already created on your table. It’s best to avoid overlapping indexes that contain shared columns.

  • Examine the number of unique data values in a column and compare that number with the number of rows in the table. The result is the selectivity of that column, which can help you decide if a column is a candidate for an index and, if so, what type of index.

Choosing the Type of Index

Depending on the functionality of your database, you can create three types of indexes - unique, primary key, and clustered - in Database Designer. For details about the indexing functionality supported by your database, see your database documentation.

Tip Although a unique index will help locate information, for the best performance results it is recommended that you use primary key or unique constraints instead. For more information about these constraints, see Primary Key Constraints and Unique Constraints.

Unique Index

A unique index is one in which no two rows are permitted to have the same index value.

Most databases prevent you from saving a table with a newly created unique index when there are duplicate key values in the existing data. Your database may also prevent the addition of new data that would create duplicate key values in the table. For example, if you create a unique index on the employee’s last name (lname) in the employee table, then no two employees can share the same last name.

For more information about unique indexes, see Creating a Unique Index.

Primary Key Index

A database table often has a column or combination of columns whose value uniquely identifies each row in the table. This column is called the primary key of the table.

Defining a primary key for a table in a database diagram automatically creates a primary key index that is a specific type of unique index. This index requires each value in the primary key to be unique. It also permits fast access to data when you use the primary key index in queries. For more information about primary keys, see Defining a Primary Key.

Clustered Index

In a clustered index, the physical order of the rows in the table is the same as the logical (indexed) order of the key values. A table can contain only one clustered index.

If an index is not clustered, the physical order of the rows in the table does not match the logical order of the key values. A clustered index usually provides faster access to data than does a nonclustered index.

For more information about using a clustered index, see Creating a Clustered Index.


Creating an Index

You can use an index to speed access to data in a database table. You create an index by selecting one or more columns in a table that you want to be able to search on. You can use the index once you save the table.

To create an index

  1. In your database diagram, select the table you want to index.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Choose New. The Selected index box displays the system-assigned name of the new index.

  5. Under Column name, select the columns you want to index. You can select up to 16 columns. For optimal performance, select only one or two columns.

  6. Specify any other desired settings for the index and then click OK.

The index is created in the database when you save the table or diagram.

Note Not all databases work with indexes in the same way. For more information, see Database Server Considerations, or consult your database documentation.


Creating a Unique Index

Create a unique index when uniqueness is a characteristic of the data itself, but the combination of indexed columns is not the same as the table’s primary key. For example, if you plan to query frequently on the Social Security number (ssn) column in the employee table (where the primary key is emp_id), and you want to ensure Social Security numbers are unique, create a unique index on ssn. If the user enters the same Social Security number for more than one employee, the database displays an error and cannot save the table.

Tip Although a unique index will help locate information, for the best performance results it is recommended that you use primary key or unique constraints instead. For more information about these constraints, see Primary Key Constraints and Unique Constraints.

When you create or modify a unique index, you can set an option to ignore duplicate keys. If this option is set and you attempt to create duplicate keys by adding or updating data that affects multiple rows (with the INSERT or UPDATE statement), the row that causes the duplicates is not added or, in the case of an update, discarded. Neither the new value nor the original value of the row that would produce the duplicate exists in the updated table.

For example, if you try to update "Smith" to "Jones" in a table where "Jones" already exists, you end up with one "Jones" and no "Smith" in the resulting table. The original "Smith" row is lost because an UPDATE statement is actually a DELETE followed by an INSERT. "Smith" was deleted and the attempt to insert an additional "Jones" failed. The whole transaction can’t be rolled back because the purpose of this option is to allow a transaction in spite of the presence of duplicates.

Caution If you do not set the Ignore duplicate keys option and you try to update a row in a way that creates a duplicate key, the original row is discarded. The new value rather than the original value of the row that would produce the duplicate is retained in the updated table. This transaction cannot be rolled back.

To create a unique index

  1. In your database diagram, select the table you want to index.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Choose New. The Selected index list displays the system-assigned name of the new index.

  5. Under Column name, select the columns you want to index. You can select up to 16 columns. For optimal performance, select only one or two columns per index.

  6. Select the Create UNIQUE check box.

  7. Select the Index option.

  8. Select the Ignore duplicate keys option if you want to ignore new or updated data that would create a duplicate key in the index (with the INSERT or UPDATE statement).

The index is created in the database when you save the table or diagram.

Note You cannot create a unique index on a single column if that column contains NULL in more than one row. Similarly, you cannot create a unique index on multiple columns if the combination of columns contains NULL in more than one row. These are treated as duplicate values for indexing purposes.

Note Not all databases work with indexes in the same way. For more information, see Database Server Considerations, or consult your database documentation.


Specifying a Fill Factor for an Index

In Microsoft® SQL Server™ databases, you can identify a fill factor to specify how full each index page can be. The amount of empty space on an index page is important because when an index page fills up, the system must take time to split it to make room for new rows.

It is seldom necessary to specify a fill factor when you create an index. The option is provided for fine-tuning performance. It is useful when you are creating a new index on a table with existing data, and particularly when you can accurately predict future changes in that data.

To specify a fill factor for an index

  1. In your database diagram, select the table for which you want to specify a fill factor.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. In the Fill factor box, type a percentage from 0 to 100.

By default, the fill factor is set to zero. If you change a fill factor after the index has been created, the database does not dynamically update the specified percentage of empty space in the pages. The value of the original fill factor is stored with the index in the database catalog.

For more information about fill factors and their uses, see "sp_configure System Stored Procedure" in SQL Server Books Online.


Creating a Clustered Index

In Microsoft® SQL Server™ databases you can create a clustered index. In a clustered index, the physical order of the rows in the table is the same as the logical (indexed) order of the key values. A table can contain only one clustered index. UPDATE and DELETE operations are often accelerated by clustered indexes because these operations require large amounts of data to be read.

Consider using a clustered index for:

  • Columns that contain a limited number of unique values, such as a state column that contains only 50 unique state codes.

  • Queries that return a range of values, using operators such as BETWEEN, >, >=, <, and <=.

  • Queries that return large result sets.

You can also use a clustered index to control what happens when a duplicate key or duplicate row is created as a result of adding or updating data to the indexed table (with the INSERT or UPDATE statement).

To create a clustered index

  1. In your database diagram, select the table whose index you want to modify.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Create a new index. For details, see Creating an Index.

    To modify an existing index, select the index from the Selected index list.

  5. Select the Create as CLUSTERED check box.

  6. Select one of the duplicate row options:
    Option | Treatment of duplicate rows
    Disallow duplicate rows | The default option. If duplicate rows exist, the index cannot be created when you attempt to save the table.
    Ignore duplicate rows | If duplicate rows exist, the index is created but duplicate rows are deleted when you save the table. When new rows are inserted, duplicates are not accepted and a SQL Server error appears when you attempt to save the table.
    Allow duplicate rows | Duplicate rows are accepted in new and existing data.

The index is created in the database when you save the table or diagram.


Sorting Data in a Clustered Index

When you create or modify a clustered index in Microsoft® SQL Server™ database, you set an option to control when data is sorted in the index. You can either sort the data when the index is created, or sort and reorganize the data when the table has become fragmented. For details about what causes table fragmentation and for recommended solutions, see the DBCC statement in SQL Server Books Online.

The option to sort the data when the index is created is always the faster of these two options because it doesn’t require the data to be copied or nonclustered indexes to be rebuilt.

To sort index values

  1. In your database diagram, select the table whose index values you want to sort.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. Make sure the Create as CLUSTERED option is selected.

  6. Choose one of the sort options:
    Option | Action
    Sort data | The default option. Sorts the data when the index is created.
    Data already sorted Eliminates the sort performed when a clustered index is created and verifies that the data has been sorted by checking each index value to determine whether it is higher than the previous one. If any row fails this check, the index cannot be created when you attempt to save the table.

    When the data satisfies the check, this option will always be faster than the Reorganize sorted data option because the data is not copied and nonclustered indexes will not be rebuilt. This option is useful when a fill factor is specified to compact or expand the pages on which a table is stored.

    For more information about fill factors, see Specifying a Fill Factor for an Index.
    Reorganize sorted data | Same as Data already sorted, except that this option will always be slower because the data is copied and nonclustered indexes will be rebuilt. Reorganizing the data is a good idea when a table becomes fragmented and you want to re-sort index values.

Note Data already sorted creates the clustered index with the SORTED_DATA option. Reorganize sorted data creates the clustered index with the SORTED_DATA_REORG option. If you select either option and any row fails the check, the attempt to create the index when you save the table will fail. In the event of such a failure, you can either fix the data or choose the Sort data option.


Saving, Displaying, and Updating an Index Definition

Your index is automatically saved in the database (and defined in the database catalog) when you save your table or database diagram. The index is available for modification as soon as you create it.

To display and update index definitions

  1. In your database diagram, select the table whose index definitions you want to display.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. To update the definition, select the field you want to update and change its value or setting.

Your changes are saved to the database when you save the table or diagram.


Renaming an Index

New indexes are automatically given system-defined names based on the database table name. If you create multiple indexes on a table, the index names are appended with "_1", "_2", and so on. You can rename an index as long as index names are unique within the table.

Note When you create a primary key or unique constraint for a table, an index with the same name as the constraint is automatically created for the table. Because index names must be unique for a table, you cannot create or rename an index to have the same name as the primary key or unique constraint for the table.

To rename an index

  1. In your database diagram, select the table whose index you want to rename.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. Type a new name in the Index name box. Make sure that it doesn’t duplicate a name in the Selected index list. If you type the same name as an existing index on this table, an error message appears.

The index is renamed in your diagram when you exit the Index name box. It is renamed in the database when you save the table or diagram.


Deleting an Index

Indexes can slow INSERT, UPDATE, and DELETE performance. If you find that an index hinders overall performance or you no longer need it, you can delete it.

To delete an index

  1. In your database diagram, select the table whose index you want to delete.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. From the Selected index list, select the index you want to delete.

  5. Choose Delete.

Caution Choosing Delete will result in an action that cannot be undone without loosing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The index is deleted from the database when you save your table or diagram.


Constraints

Constraints are business logic that your database server enforces for you. They limit the possible values that users can enter into specified columns, enforcing referential integrity. When you create constraints in the Database Designer, they conform to the ANSI standard for creating and altering tables.

The Database Designer accepts five types of constraints:

  • Check Constraints

  • Default Constraints

  • Unique Constraints

  • Primary Key Constraints

  • Foreign Key Constraints


Check Constraints

A check constraint specifies the data values or formats that are acceptable in one or more columns in a table. For example, you can require the zip column of the authors table to allow only five-digit numeric entries.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

You can define many check constraints for a table. You use the Tables property pages to create, modify, or delete each check constraint.

To | See
Attach a check constraint to a table to specify the data values that are acceptable in one or more columns | Attaching a New Check Constraint to a Table or Column
Create a constraint expression to check data for a condition | Defining a Check Constraint Expression
Change the constraint expression or the options that enable or disable the constraint for specific conditions | Modifying a Check Constraint
Apply constraints either to new data only or to existing data as well | Checking Existing Data When Creating a Check Constraint
Disable a check constraint when data is added to, updated in, or deleted from a table | Disabling a Check Constraint with INSERT and UPDATE Statements
Disable a check constraint when your table is replicated in another database | Disabling a Check Constraint for Replication
Remove the limitations on data values in a column | Deleting a Check Constraint


Attaching a New Check Constraint to a Table or Column

Attach a check constraint to a table to specify the data values that are acceptable in one or more columns.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To attach a new check constraint

  1. In your database diagram, select the table where you want to add a check constraint.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Under CHECK constraints for tables and columns, choose New. The Selected constraint box displays the system-assigned name of the new constraint. System-assigned names begin with "CK_" followed by the table name.

  5. In the Constraint expression box, type the SQL expressions for the check constraint. For example, to limit the entries in the state column of the authors table to New York, type:
    state = 'NY'

    Or, to require entries in the zip column to be 5 digits, type:

    zip LIKE '[0-9][0-9][0-9][0-9][0-9]'

    Important Make sure to enclose any non-numeric constraint values in single quotation marks ('). For additional details, see Defining a Check Constraint Expression.

  6. If you want to give the constraint a different name, type the name in the Constraint name box.

When you create a check constraint, it is automatically bound to the specified columns. It takes effect when you save the table or diagram. When you delete a table, all the check constraints attached to that table are automatically deleted.


Defining a Check Constraint Expression

When you attach a check constraint to a table or column, you must include an SQL expression. For details about this operation, see Attaching a New Check Constraint to a Table or Column.

You can create a simple constraint expression to check data for a simple condition; or you can create a complex expression, using Boolean operators, to check data for several conditions. For example, suppose the authors table has a zip column where a 5-digit character string is required. This sample constraint expression guarantees that only 5-digit numbers are allowed:

zip LIKE '[0-9][0-9][0-9][0-9][0-9]'

Or suppose the sales table has a column called qty which requires a value greater than 0. This sample constraint guarantees that only positive values are allowed:

qty > 0

Or suppose the orders table limits the type of credit cards accepted for all credit card orders. This sample constraint guarantees that if the order is placed on a credit card, then only Visa, MasterCard, or American Express is accepted:

NOT (payment_method = ‘credit card’) OR
   (card_type IN (‘VISA’, ‘MASTERCARD’, ‘AMERICAN EXPRESS’))

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To define a constraint expression

  • In the Tables tab of the property pages, type the expression in the Constraint expression box using the following syntax:

    {constant | column_name | function | (subquery)}
    [{operator | AND | OR | NOT}
    {constant | column_name | function | (subquery)}…]

    Note This syntax is Microsoft® SQL Server specific. Consult your database documentation for details.

The SQL syntax is made up of the following parameters:

Parameter | Description
constant | A literal value, such as numeric or character data. Character data must be enclosed within single quotation marks (').
column_name | Specifies a column.
function | A built-in function. For details about functions, see "Functions" in SQL Server Books Online or Transact-SQL Reference.
operator | An arithmetic, bitwise, comparison, or string operator. For details about operators, see "Operators" in SQL Server Books Online or Transact-SQL Reference.
AND | Use in Boolean expressions to connect two expressions. Results are returned when both expressions are true. When AND and OR are both used in a statement, AND is processed first. You can change the order of execution by using parentheses.
OR | Use in Boolean expressions to connect two or more conditions. Results are returned when either condition is true. When AND and OR are both used in a statement, OR is evaluated after AND. You can change the order of execution by using parentheses.
NOT | Negates any Boolean expression (which can include keywords, such as LIKE, NULL, BETWEEN, IN, and EXISTS). When more than one logical operator is used in a statement, NOT is processed first. You can change the order of execution by using parentheses.


Modifying a Check Constraint

Modify a check constraint when you want to change the constraint expression or the options that enable or disable the constraint for specific conditions.

To modify a check constraint

  1. In your database diagram, select the table whose check constraint you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint you want to change from the Selected constraint list.

  5. Complete an action from the following table:

    Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

    To | Follow these steps
    Edit the constraint expression | Type the new expression in the Constraint expression box. For details, see Defining a Check Constraint Expression.
    Rename the constraint | Type a new name in the Constraint name box. Make sure that your new name doesn’t duplicate a name in the Selected constraint list.
    Apply the constraint to existing data (Microsoft SQL Server only) | Select the Check existing data on creation option. For details, see Checking Existing Data When Creating a Check Constraint.
    Disable the constraint when new data is added to the table or when existing data is updated in the table (Microsoft SQL Server only) | Clear the Enable constraint for INSERT and UPDATE option. For details, see Disabling a Check Constraint with INSERT and UPDATE Statements.
    Disable the constraint when the table is replicated in another database(Microsoft SQL Server only) | Clear the Enable constraint for replication option. For details, see Disabling a Check Constraint for Replication.

The constraint is updated in the database when you save your table or diagram.


Checking Existing Data When Creating a Check Constraint

When you create a check constraint, you can set an option to apply it either to new data only or to existing data as well. The option of applying the constraint to new data only is useful when you know that the existing data already meets the new check constraint, or when a business rule requires the constraint to be enforced only from this point forward.

For example, you may have required zip codes to be limited to five digits in the past, but now want new data to allow nine-digit zip codes. Old data with five-digit zip codes will coexist with new data that contains nine-digit zip codes.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To check existing data when creating a check constraint

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Select the Check existing data on creation check box. This option is selected by default.

The check constraint will be applied when you save the table or the database diagram. If any constraint violations are encountered during the save process, the table cannot be saved.


Disabling a Check Constraint with INSERT and UPDATE Statements

You can disable a check constraint when data is added to, updated in, or deleted from a table. Disabling a constraint enables you to perform the following transactions:

  • Add a new row of data to a table (using the INSERT statement) where the existing rows were required to meet specific business rules that no longer apply (Microsoft SQL Server only). For example, you may have required postal codes to be limited to five digits in the past, but now want new data to allow nine-digit postal codes. Old data with five-digit postal codes will coexist with new data that contains nine-digit postal codes.

  • Modify existing rows (using the UPDATE statement) where the existing rows were required to meet specific business rules that no longer apply. For example, you may want to update all existing five-digit postal codes to nine-digit postal codes.

Select the option to disable a check constraint during INSERT and UPDATE transactions if you know that new data will violate the constraint, or if the constraint applies only to the data already in the database.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To disable a check constraint with INSERT and UPDATE statements

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Clear the Enable constraint for INSERT and UPDATE check box.

    You can select this option after you add or modify data to guarantee that the constraint applies to subsequent data modifications.


Disabling a Check Constraint for Replication

You can disable a check constraint when your table is replicated in another database. When you replicate a table, the table definition and data are copied from the source database to a destination database. These two databases are usually (but not necessarily) on separate servers. If the check constraints are specific to the source database, they may unnecessarily prevent new data from being entered in the destination database.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To disable a check constraint for replication

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Clear the Enable constraint for replication check box.

When you replicate a database at a remote site, you should not re-apply check constraints because:

  • The integrity of the data was checked when it was entered into the original database.

  • The replication will fail if data violates the check constraints.


Deleting a Check Constraint

Delete a check constraint when you want to remove the limitations on data values that are accepted in the column or columns included in the constraint expression.

Note Some databases have different functionality for check constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with check constraints.

To delete a check constraint

  1. In your database diagram, select the table whose check constraint you want to delete.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Choose Delete.

Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


Default Constraints

A default constraint enables you to define the value that will be supplied for a column whenever a user fails to enter a value. For example, in a table with a column called payterms, you can instruct your database server to enter "???" or "fill in later" if the user leaves it blank.

In database diagrams, you define a default constraint as a property of a column in your table. You define this type of constraint for a column by specifying a default value inside a table in Column Properties view. Be sure to specify the constraint with the correct delimiters. For example, strings must be surrounded with single quotes.

For more information about defining default constraints, see Setting Column Properties.


Unique Constraints

A unique constraint ensures no duplicate values are entered into specified columns that are not a table’s primary key. For example, in the employee table in which the emp_id column is the primary key, you can define a unique constraint that requires entries in the Social Security number (ssn) column to be unique within the table.

In database diagrams, you use the Indexes/Keys property page to create, modify, or delete unique constraints.

To | See
Ensure no duplicate values are entered in specific columns | Creating a Unique Constraint
Change the columns that the constraint is attached to, change the constraint name, or set additional properties for the constraint | Modifying a Unique Constraint
Remove the requirement for uniqueness for values entered in the column | Deleting a Unique Constraint


Creating a Unique Constraint

Create a unique constraint to ensure no duplicate values are entered in specific columns that do not participate in a primary key. While both a unique constraint and a primary key enforce uniqueness, you should attach a unique constraint instead of a primary key constraint to a table if:

  • You want to enforce uniqueness in a column or combination of columns. You can attach multiple unique constraints to a table, whereas you can attach only one primary key constraint to a table.

  • You want to enforce uniqueness in a column that allows null values. You can attach unique constraints to columns that allow null values, whereas you can attach primary key constraints only to columns that do not allow null values.

To create a unique constraint

  1. In your database diagram, select the table where you want to add a unique constraint.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Choose New. A system-assigned name appears in the Index name box.

  5. Under Column name, expand the list of columns and select the column that you want to attach the constraint to. To attach the constraint to multiple columns, select the additional columns in subsequent rows.

  6. Select the Create UNIQUE check box.

  7. Select the Constraint option.

The unique constraint is created in the database when you save the table or the diagram. If you want to control the sort order of key values and the action taken when duplicate keys exist, you should create a unique index instead of a unique constraint. For more information, see Creating a Unique Index.


Modifying a Unique Constraint

Modify a unique constraint when you want to change the columns that the constraint is attached to, change the constraint name, or set additional properties for the constraint.

To modify a unique constraint

  1. In your database diagram, select the table whose unique constraint you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the constraint you want to change from the Selected index list.

  5. Complete an action from the following table:
    To | Follow these steps
    Change the columns that the constraint is attached to | In the Column name grid, expand the list and select the columns you want to attach the constraint to.
    Rename the constraint | Type a new name in the Index name box. Make sure that your new name doesn’t duplicate a name in the Selected index list.
    Set the clustered option (Microsoft SQL Server only) | Select the Create as CLUSTERED check box. Only one clustered index can exist per table. If a clustered index already exists, you must first clear this setting on that index.
    Define a fill factor (Microsoft SQL Server only) | Type an integer from 0 to 100 in the Fill factor box. Type 0 to accept the default fill factor.

The constraint is updated in the database when you save your table or diagram.


Deleting a Unique Constraint

Delete a unique constraint when you want to remove the requirement for uniqueness for values entered in the column or combination of columns included in the constraint expression.

To delete a unique constraint

  1. In your database diagram, select the table whose unique constraint you want to delete.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the unique constraint from the Selected index list.

  5. Choose Delete.

Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


Primary Key Constraints

A primary key constraint ensures no duplicate values are entered in particular columns and that NULL values are not entered in those columns. You can use primary key constraints to enforce uniqueness as well as referential integrity. For example, the au_id column uniquely identifies each author stored in the authors table.

You create primary key constraints directly in a database diagram.

Note Some databases have different functionality for primary key constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with primary key constraints.

To | See
Enforce uniqueness for values entered in specified columns | Defining a Primary Key
Change the column order, index name, clustered option, or fill factor | Modifying a Primary Key
Copy column properties from a primary key column to a foreign key column to relate the two columns | Copying Column Properties to a Foreign Key Column
Remove the requirement for uniqueness for the values entered in a column | Deleting a Primary Key Constraint


Defining a Primary Key

Define a primary key to enforce uniqueness for values entered in specified columns that do not allow nulls. If you define a primary key for a table in your database, you can relate that table to other tables, thus reducing the need for redundant data. A table can have only one primary key.

Note Some databases have different functionality for primary key constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with primary key constraints.

To define a primary key

  1. In your database diagram, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns.

  2. Right-click the row selector for the column and select Set Primary Key. A primary key index, named "PK_" followed by the table name, is automatically created on the Indexes/Keys tab of the property pages.

Warning If you want to redefine the primary key, any relationships to the existing primary key must be deleted before the new primary key can be created. A message will warn you that existing relationships will be automatically deleted as part of this process.

A primary key column is identified by a primary key symbol [image] in its row selector.

If a primary key consists of more than one column, duplicate values are allowed in one column, but each combination of values from all the columns in the primary key must be unique.

If you define a compound key, the order of columns in the primary key matches the order of columns as shown in the table in your diagram. However, you can change the order of columns after the primary key is created.


Modifying a Primary Key

Modify a primary key if you want to change the column order, index name, clustered option, or fill factor.

To modify a primary key

  1. In your database diagram, select the table whose primary key you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the primary key index from the Selected index list.

  5. Complete an action from the following table:

    Note Some databases have different functionality for primary key constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with primary key constraints.

    To | Follow these steps
    Change the column order In the Column name grid, expand the list of columns and select the column that you want to order first in the primary key. Repeat this step in subsequent rows of the Column name grid to reorder the remaining columns in the primary key.

    Note Each column name must be unique in a primary key. If you select the same column name in more than one row of the Column name grid, an error will prevent you from saving the table.
    Rename the primary key | Type a new name in the Index name box. Make sure that your new name doesn’t duplicate a name in the Selected index list.
    Set the clustered option | (Microsoft SQL Server only.) Select the Create as CLUSTERED check box. Only one clustered index can exist per table. If this option is not available for your index, you must first clear this setting on the existing clustered index.
    Define a fill factor | (Microsoft SQL Server only.) Type an integer from 0 to 100 in the Fill factor box. Type 0 to accept the default fill factor.

The constraint is updated in the database when you save your table or diagram.


Copying Column Properties to a Foreign Key Column

When you copy a column from one table to another table, the column name and many of the other properties you defined for that column in the table are copied to the new location. You can copy column properties from a primary key column to a foreign key column if you want to relate the two columns. Related columns must have the same data type (or data types that can be related) and Length property settings.

To copy primary key column properties to a foreign key column

  1. In your database diagram, select the primary key columns that you want to copy. Primary key columns are indicated by a key symbol [image] in their row selector.

  2. Copy the columns to the foreign key table. For details, see Copying Columns from One Table to Another.

  3. Drag a relationship line from the columns in the primary key table to the same columns in the foreign key table. For details, see Creating a Relationship Between Tables.


Deleting a Primary Key Constraint

Delete a primary key constraint when you want to remove the requirement for uniqueness for the values entered in a column or a combination or columns.

To delete a primary key constraint

  1. In your database diagram, select the primary key columns for the table whose primary key constraint you want to delete. A primary key column is identified by a primary key symbol [image] in its row selector.

  2. Right-click the row selector for the column and select Set Primary Key.

    –or–

  3. In your database diagram, select the table whose primary key constraint you want to delete.

  4. Right-click the table and select Properties.

  5. Choose the Indexes/Keys tab.

  6. Select the primary key index from the Selected index list.

  7. Choose Delete.

Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


Foreign Key Constraints

A foreign key constraint works in conjunction with primary key or unique constraints to enforce referential integrity among specified tables. For example, you can place a foreign key constraint on the title_id column in the publishers table to ensure that a value entered in that column matches an existing value in the title_id column of the titles table.

In database diagrams, a foreign key constraint is automatically placed on specified columns when you create a relationship to a table from another table to which a primary key or unique constraint is attached. For more information about creating relationships, see Creating a Relationship Between Tables.

To | See
See which columns participate in the foreign key side of a relationship | Viewing Foreign Key Attributes
Change which columns are related to columns in the primary key table | Modifying a Foreign Key
Check existing data when creating a relationship | Checking Existing Data when Creating a Relationship
Disable a foreign key constraint during INSERT and UPDATE transactions | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements
Disable a foreign key constraint during replication of the table | Disabling a Foreign Key Constraint for Replication
Remove the requirement to enforce referential integrity between primary key columns and the related columns in another table | Deleting a Foreign Key Constraint


Viewing Foreign Key Attributes

View the foreign key attributes of a relationship if you want to see which columns participate in the foreign key side of a relationship. If the foreign key columns are related to a primary key, the primary key columns are identified in your database diagram by a primary key symbol in the row selector: .

To view the foreign key attributes of a relationship

  1. In your database diagram, select a relationship line.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Make sure the relationship is selected in the Selected relationship list.

  5. The Foreign key table column displays the name of each column that participates in the foreign key side of the relationship.


Modifying a Foreign Key

Modify the foreign key side of a relationship if you want to change which columns are related to columns in the primary key table.

To modify a foreign key

  1. In your database diagram, select the relationship line that you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. In the Foreign key table column, expand the list in the first row.

  6. Select a different table column from the list. The foreign key column must match the data type and size of the primary key column, with these exceptions:
    • A char column or sysname column can relate to a varchar column.

    • A binary column can relate to a varbinary column.

    • A user-defined data type can relate to its base type.

Any changes you make to the relationship’s properties take effect as soon as you move outside the grid in the property pages. The constraint is updated in the database when you save your table or diagram.

Note Modifying a relationship in a database diagram marks both of the related tables as modified. Consequently, each table will also be marked as modified in any other diagrams in which it appears.


Checking Existing Data when Creating a Relationship

Select the option to check existing data when you create a relationship if the foreign key constraint should apply to existing data as well as to new data.

Note Some databases have different functionality for foreign key constraints. For more information about the differences between databases, see Database Server Considerations. Consult your database documentation for details about how your database works with foreign key constraints.

To check existing data when creating a relationship

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Select the Check existing data on creation check box.

This option is not selected by default. The foreign key constraint is applied when you save the table or diagram. If any constraint violations are encountered during the save process, the table cannot be saved.


Disabling a Foreign Key Constraint with INSERT and UPDATE Statements

Select the option to disable a foreign key constraint during INSERT and UPDATE transactions if you know that new data will violate the constraint or if the constraint applies only to the data already in the database.

To disable a foreign key constraint with INSERT and UPDATE statements

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear the Enable relationship for INSERT and UPDATE check box.

After you add or modify data, you should select this option if you want to ensure the constraint applies to subsequent data modifications.

Note If you plan to use triggers to implement database operations, such as cascade updates or cascade deletes, you must disable foreign key constraints in order for the trigger to run.


Disabling a Foreign Key Constraint for Replication

Select the option to disable a foreign key constraint during replication if the constraint is specific to the source database and may unnecessarily prevent new data from being entered into the destination database.

To disable a foreign key constraint for replication

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear the Enable relationship for replication check box.


Deleting a Foreign Key Constraint

Delete a foreign key constraint when you want to remove the requirement to enforce referential integrity between primary key columns and the related columns in another table.

To delete a foreign key constraint

  • In your database diagram, delete the relationship line that represents the foreign key constraint you want to delete. For details, see Deleting a Relationship.

Note Deleting a relationship from a database diagram marks the related tables as modified in all diagrams in which they appear.


Stored Procedures

Stored procedures can make managing your database and displaying information about that database and its users much easier. Stored procedures are a precompiled collection of SQL statements and optional control-of-flow statements stored under a name and processed as a unit. Stored procedures are stored within a database; can be executed with one call from an application; and allow user-declared variables, conditional execution, and other powerful programming features.

Stored procedures can contain program flow, logic, and queries against the database. They can accept parameters, output parameters, return single or multiple result sets, and return values.

You can use stored procedures for any purpose for which you would use SQL statements, with these advantages:

  • You can execute a series of SQL statements in a single stored procedure.

  • You can reference other stored procedures from within your stored procedure, which can simplify a series of complex statements.

  • The stored procedure is compiled on the server when it is created, so it executes faster than individual SQL statements.

The functionality of a stored procedure is dependent on the features offered by your database. For more details about what a stored procedure can accomplish for you, see your database documentation.

When you create a stored procedure in Microsoft® Visual Database Tools™, the stored procedure appears in the Stored Procedures folder in Data View. You can expand a stored procedure in Data View to see a list of the parameters it contains.

For details about working with stored procedures, see the following topics:

To | See
Create stored procedures to be executed from the database | Creating a Stored Procedure
Set execute permissions to allow access to the stored procedures by specific users | Setting Execute Permissions on Stored Procedures
Use parameters in stored procedures | Using Parameters in Stored Procedures
Open a stored procedure to view or edit its text | Opening a Stored Procedure
Save stored procedures | Saving a Stored Procedure
Delete stored procedures | Deleting a Stored Procedure
Copy stored procedures | Copying a Stored Procedure
Run stored procedures against your database | Running a Stored Procedure
Change the name of a stored procedure | Renaming a Stored Procedure


Creating a Stored Procedure

You can use any stored procedures that appear in the Stored Procedures folder for a database in Data View. Or you can create your own stored procedures that can be executed from the database you’re connected to.

To create a new stored procedure

  1. In Data View, right-click the Stored Procedures folder or any stored procedure in that folder.

  2. Choose New Stored Procedure from the shortcut menu.

  3. A new stored procedure is created using skeleton SQL statements.

  4. If desired, replace StoredProcedure1 in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:
    Create Procedure MyProcedure

    Note Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message warns you that a stored procedure with that name already exists.

  5. Write the remaining procedure text in SQL.

For more information and examples of stored procedures, see the documentation for your database server. If you are using Microsoft® SQL Server™, see "CREATE PROCEDURE statement" in SQL Server Books Online.


Setting Execute Permissions on Stored Procedures

You can set execute permissions for a stored procedure that you own to allow access to the stored procedure by specific users or groups. In many databases, if you are not the database owner, then you must explicitly grant permissions for your stored procedure to other users. You can grant permissions to all users, or to just a single user or group. The syntax for both is similar.

Note When you create a stored procedure in an Oracle database, you must explicitly grant permissions for your stored procedure to other users. If you do not grant permissions to a user, that user must have the EXECUTE ANY PROCEDURE system privilege in order to execute the procedure.

To grant permissions to all users

  1. Create a new SQL script file. For details, see Creating SQL Scripts.

  2. Enter the following SQL statement in the script file, replacing sp_name with the name of your stored procedure:
    Grant Execute On sp_name To Public

To grant permissions to a user or group

  1. Create a new SQL script file. For details, see Creating SQL Scripts.

  2. Enter the following SQL statement in the script file, replacing sp_name with the name of your stored procedure, and replacing user with the name of the user or group to grant permissions to:
    Grant Execute On sp_name To user

    For example, if you want to grant permissions on a stored procedure to a group named Managers, you can create an SQL script file and add the following SQL statement:

    Grant Execute On MyPublicProcedure To Managers

Note Microsoft® Visual Basic™ does not support using SQL scripts to change permissions on a stored procedure. You'll need to use a utility such as SQL Enterprise Manager.


Opening a Stored Procedure

You can open a stored procedure in your database to view or edit its text. You can create a stored procedure using Microsoft® Visual Database Tools™, or using tools in the database itself.

To open a stored procedure

  1. In Data View, expand the Stored Procedures folder.

  2. Double-click the name of the stored procedure you want to open.

    -or-

    Right-click the name of the stored procedure that you want to open, choose Open from the shortcut menu.

The stored procedure is opened in a text editor that you can use to edit the SQL statements. For details about editing stored procedures, see your database documentation. For Microsoft SQL Server databases, see "Creating Stored Procedures" in SQL Server Books Online.

Note You can place SQL Server stored procedures under source control using Microsoft® Visual SourceSafe™. For more information, see the Visual SourceSafe documentation.


Saving a Stored Procedure

A stored procedure must be saved before you can run it. If you attempt to run an unsaved stored procedure, a message prompts you to save it first. When you save the stored procedure, it is added to the Stored Procedures folder in Data View.

To save a stored procedure

  • From the File menu, choose Save.

Stored procedures must have unique names. If the name beside CREATE PROCEDURE in the procedure text is already assigned to another database object, a message prompts you to choose another name for the stored procedure.


Renaming a Stored Procedure

When you change the name of a stored procedure, that name is updated in your database and in the Stored Procedures folder of Data View as soon as you save the stored procedure.

To rename a stored procedure

  1. In Data View, expand the Stored Procedures folder.

  2. Right-click the name of the stored procedure that you want to rename.

  3. Choose Rename from the shortcut menu.

  4. Enter the new name for the stored procedure.

Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message warns you that a stored procedure with that name already exists.

Note If you change the name of a stored procedure in the editor, the save command will create a new version of the stored procedure with the new name. Any permissions associated with the original stored procedure are not carried forward.


Copying a Stored Procedure

You can copy a stored procedure as the first step in creating a new stored procedure for your database. Because stored procedures must have names that are unique, the new stored procedure is automatically assigned a new unique name based on the original name.

To copy a stored procedure

  1. Open the Stored Procedure you want to copy in the text editor.

  2. Rename the stored procedure. For details, see Renaming a Stored Procedure.

  3. Save the stored procedure to the database.

The new stored procedure is added to the Stored Procedures folder with the name you specified. The original stored procedure is not removed.

Note This process does not copy any privileges that may have been associated with the original stored procedure.

You can edit the SQL statements in the new stored procedure. For more information about editing stored procedures, see your database documentation.


Running a Stored Procedure

You can run a stored procedure against your database to execute the SQL statements it contains and display the results in the Output window.

To run a stored procedure

  1. In Data View, expand the Stored Procedures folder.

  2. Right-click the name of the stored procedure that you want to run.

  3. Choose Execute from the shortcut menu. The Output window shows the status of the stored procedure.

  4. If the stored procedure contains parameters, the Run Stored Procedure dialog box prompts you for their values. In the Value column, type a value for each parameter that appears in the Name column, and then choose OK. For details about parameters, see Using Parameters in Stored Procedures.

The Output window is updated with status information as the stored procedure is run. The Output window also displays result sets and return values for the stored procedure. If any errors occurred during this process, the Server Errors dialog box displays a list of errors.

Note Microsoft® Visual Basic™ does not support executing stored procedures from the Data View window.


Using Parameters in Stored Procedures

Parameters enable you to use the same stored procedure to search the database many times, rather than requiring you to create one stored procedure for each value that you want to match. For example, in a SQL Server database, you can add a @HireDate parameter to a stored procedure that searches the employee table for employees whose hire date matches the date you specify. You can then run the stored procedure each time you want to specify a different hire date. Or you can use a combination of parameters to specify a range of dates. For example, you can create two parameters — @BeginningDate and @EndingDate — in the where clause of your stored procedure, and then specify a range of hire dates when you run the procedure.

When you use parameters in stored procedures, you can:

  • Return a status value to another stored procedure to indicate success or failure and the reason for the failure.

  • Return parameter values to another stored procedure.

A parameter takes the place of a constant; it cannot take the place of a table name, column name, or other database object.

For more details about how your database works with parameters in stored procedures, see your database documentation.

To view parameters for a stored procedure

  • In Data View, expand the name of the stored procedure.

    Parameters for the stored procedure are listed below the stored procedure name. In SQL Server databases, each parameter name begins with the "@" character. For example, @percentage.

When you run a stored procedure that contains a parameter, you specify a parameter value.

To enter parameter values

  1. Run the stored procedure. For details, see Running a Stored Procedure.

    If the stored procedure contains one or more parameters, the Run Stored Procedure dialog box is displayed.

  2. For each parameter, enter the value to use. Be sure that you provide a value that matches the data type of the parameter.

  3. When you have finished entering parameter values, choose OK.


Deleting a Stored Procedure

When you no longer need to retrieve the information specified by a stored procedure, or the tables or columns it references have been deleted from your database, you can delete the stored procedure.

To delete a stored procedure

  1. In Data View, expand the Stored Procedures folder.

  2. Right-click the stored procedure that you want to delete.

  3. Choose Delete from the shortcut menu.

  4. A message prompts you to confirm the deletion. Choose Yes.

The stored procedure is deleted from the database and Data View.


Triggers

A trigger is a special kind of stored procedure that goes into effect when you modify data in a specified table using one or more data modification operations: UPDATE, INSERT, or DELETE. Triggers can query other tables and can include complex SQL statements. They are primarily useful for enforcing complex business rules or requirements. For example, you could control whether to allow an order to be inserted based on a customer's current account status.

Triggers are also useful for enforcing referential integrity, which preserves the defined relationships between tables when you add, update, or delete the rows in those tables. However, the best way to enforce referential integrity is to define primary key and foreign key constraints in the related tables. If you use database diagrams, you can create a relationship between tables to automatically create a foreign key constraint. For details, see Table Relationships.

Advantages of Using Triggers

Triggers are useful in these ways:

  • Triggers are automatic: they are activated immediately after any modification to the table’s data, such as a manual entry or an application action.

  • Triggers can cascade changes through related tables in the database. For example, you can write a delete trigger on the title_id column of the titles table to cause a deletion of matching rows in other tables. The trigger uses the title_id column as a unique key to locate matching rows in the titleauthor, sales, and roysched tables.

  • Triggers can enforce restrictions that are more complex than those defined with check constraints. Unlike check constraints, triggers can reference columns in other tables. For example, a trigger can roll back updates that attempt to apply a discount (stored in the discounts table) to books (stored in the titles table) with a price of less than $10.

For details about working with triggers, see the following topics:

To | See
Create new triggers | Creating a Trigger
Open existing triggers | Opening a Trigger
Save triggers to your project | Saving a Trigger
Change the name of a trigger | Renaming a Trigger
Delete stored triggers | Deleting a Trigger


Creating a Trigger

A trigger is a database object that you create by specifying:

  • The current table.

  • The data modification transactions that activate the trigger: adding new data (INSERT), updating existing data (UPDATE), or deleting existing data (DELETE).

  • The actions that the trigger will take immediately following the transactions you specified.

You write triggers in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for Oracle databases.

To create a trigger

  1. In Data View, expand the Tables folder.

  2. Right-click the name of the table that you want to create a trigger on.

  3. Choose New Trigger from the shortcut menu.

  4. A new trigger is created in a source code editor with the default SQL statements already defined for you.

  5. Modify the default trigger text as follows:
    Replace | With
    TABLE1_Trigger1 | The name you want to assign to the trigger
    dbo.TABLE1 | The name of the table you want to attach the trigger to
    /*Insert, Update, Delete*/ | The type of transactions that will activate this trigger
    /*If Update (column_name) …*/ | The transactions that will take place

  6. Write the remaining trigger text in SQL.

For syntax and examples of triggers, see your database documentation.


Opening a Trigger

You can open a trigger to view or edit the text of an existing trigger that is stored in your database. Triggers are scripted in Transact-SQL for Microsoft® SQL Server™ databases or PL/SQL for Oracle databases.

A trigger is differentiated from the database table columns in Data View by the trigger icon [image].

To open a trigger

  1. In Data View, expand the Tables folder.

  2. Expand the table whose trigger you want to open.

  3. Right-click the name of the trigger that you want to open and choose Open from the shortcut menu.

    -or-

    Double-click the name of the trigger that you want to open.

The trigger is opened in a source code editor that you can use to edit the SQL statements. For details about editing the Transact-SQL syntax of a trigger for your database, search for "CREATE TRIGGER Statement" in your database documentation.


Saving a Trigger

To add a new trigger to the database or to update an existing trigger that you have modified, you can save a trigger.

To save a trigger

  1. From the File menu, choose Save <trigger name>.

  2. If you are updating an existing trigger, a message box prompts you to confirm the save action. Choose Yes.

A saved trigger appears in the Tables folder in Data View under the table that it’s attached to.


Renaming a Trigger

When you change the name of a trigger, the trigger name is updated in your database and in the Tables folder of Data View as soon as you save the trigger.

To rename a trigger

  1. Open the trigger. For details, see Opening a Trigger.

  2. In the source code editor, replace the existing trigger name with the new name. (The trigger name appears after the Create Trigger statement.)

  3. Save the trigger. For details, see Saving a Trigger.

  4. Delete the old trigger (unless you want two identical triggers with different names). For details, see Deleting a Trigger.

The new trigger name is in the database and is displayed in Data View.

For more information about editing the Create Trigger statement, see Creating a Trigger.


Deleting a Trigger

When you want to disable the actions defined in the trigger that are automatically carried out on your database immediately following the specified transactions, you can delete a trigger.

You might also want to delete any triggers that enforce referential integrity between related tables if you use database diagrams to design your database. Database diagrams use relationships instead of triggers for this purpose. Thus, if a trigger duplicates a relationship in a database diagram, you should delete either the trigger or the relationship. For information about deleting relationships, see Deleting a Relationship.

To delete a trigger

  1. In Data View, expand the Tables folder.

  2. Expand the table whose trigger you want to delete.

  3. Right-click the trigger that you want to delete and choose Delete from the shortcut menu.

  4. A message prompts you to confirm the deletion. Choose Yes.

The trigger is deleted from the database and Data View.


Query Designer

The Microsoft® Visual Database Tools Query Designer is a powerful tool for creating SQL commands using a simple, intuitive visual interface. You can create even complex, multi-table queries by simply dragging tables into your query, selecting options, and entering values.

With the Query Designer you can:

  • Work visually or with SQL commands The Query Designer includes both graphical panes that display your query visually and an SQL pane that displays the SQL text of your query. You can work in either the graphical or SQL panes — the Query Designer keeps both views synchronized so they are always current.

  • Create database-aware commands The Query Designer is designed to be aware of differences between databases such as Microsoft® SQL Server™ and Oracle, so it can generate and recognize database-specific SQL commands.

  • Join related tables If you add more than one table to your query, the Query Designer automatically determines how the tables are related and constructs the appropriate join command in your query.

  • Query or update databases You can use the Query Designer both to return data using SQL SELECT commands or to create queries that update, add, or delete records in a database, such as UPDATE, INSERT, and DELETE.

  • View and edit results immediately You can execute your query and work with a recordset in a grid that allows you to scroll through and edit records in the database.

The following table lists topics that provide overviews of how to work with the Query Designer.

To read about | See
The Query Designer layout and how to work in the Query Designer | Designing Queries
The basics of how to create queries | Creating Queries
Creating new queries, views, and stored procedures | Working in the Project Explorer
Sorting data | Ordering Query Results
Filtering data | Specifying Search Criteria
Updating records in databases | Modifying Data in Tables
Summarizing data | Querying on Groups of Rows
Joining tables | Querying Using Multiple Tables
Combining literals, functions, and variables to form expressions for querying | Using Expressions in Queries
Creating queries that use parameters | Creating Special Purpose Queries
Special considerations for using the Query Designer with specific databases | Query Designer Considerations for SQL Server Databases, Query Designer Considerations for Oracle Databases


Designing Queries

The Microsoft® Visual Database Tools™ Query Designer uses visual design tools to create SQL statements to query or update databases.

To | See
Read about the user interface for the Query Designer | Query Designer Layout
Learn about what types of queries you can create in the Query Designer and how you can use them to retrieve, copy, and modify data | Supported Query Types
Read about the basic steps involved in creating any type of query | Creating a Query
Move around in the different panes of the Query Designer | Navigating in the Query Designer
Use data in different languages in the Query Designer | Using Query Designer With International Data

What You Can Do in the Query Designer

Using the Query Designer, you can:

  • Create queries to retrieve data from any ODBC-compliant database.

  • Specify elements, such as which tables (or views) and columns to display, how to order query results, and what values to search for.

    Note In Oracle you can use synonyms as well. For details, see Query Designer Considerations for Oracle Databases.

  • Preview query results in the Results pane.

  • Join tables to create multi-table queries.

  • Edit databases directly by updating, inserting, or deleting rows.

  • Create queries that modify a database by updating, adding, or deleting rows, or by copying rows.

  • Create special-purpose queries, such as parameter queries in which search values are provided when the query is executed.

If you are familiar with SQL, you can also enter SQL statements directly or edit the SQL statements created by the Query Designer.


Query Designer Layout

The Query Designer consists of four panes: the Diagram pane, the Grid pane, the SQL pane, and the Results pane.

  • The Diagram pane displays the input sources (tables or views) which you are querying. Each window represents an input source and shows the available data columns as well as icons that indicate how each column is used in the query. Joins are indicated by lines between the input source windows. For more information, see Diagram Pane.

  • The Grid pane contains a spreadsheet-like grid in which you specify query options, such as which data columns to display, what rows to select, how to group rows, and so on. For more information, see Grid Pane.

  • The SQL pane displays the SQL statement for the current query. You can edit the SQL statement created by the Query Designer or you can enter your own SQL statement. It is particularly useful for entering SQL statements that cannot be created using the Diagram and Grid panes, such as Union queries. For more information, see SQL Pane.

  • The Results pane shows a grid with the results of the most recently executed Select query. You can modify the database by editing values in the cells of the grid, and you can add or delete rows. For more information, see Results Pane.

You can create a query by working in all of the panes: you can specify a column to display by choosing it in the Diagram pane, entering it into the Grid pane, or making it part of the SQL statement in the SQL pane. The Diagram, Grid, and SQL panes are synchronized — when you make a change in one pane, the Query Designer updates the other panes to reflect the change.


Supported Query Types

You can create the following types of queries in the Diagram and Grid panes (the graphical panes) of the Query Designer:

  • Select query Retrieves data from one or more tables or views. This type of query creates an SQL SELECT statement.

  • Insert Values query Creates a new row and inserts values into specified columns. This type of query creates an SQL INSERT INTO…VALUES statement.

  • Insert query Creates new rows by copying existing rows from one table into another, or into the same table as new rows. This type of query creates an SQL INSERT…SELECT statement.

  • Update query Changes the values of individual columns in one or more existing rows in a table. This type of query creates an SQL UPDATE statement.

  • Delete query Removes one or more rows from a table. This type of query creates an SQL DELETE statement.

    Note A Delete query removes entire rows from the input source. If you want to delete values from individual data columns, use an Update query.

  • Make Table query Creates a new table and creates rows in it by copying the results of a query into it. This type of query creates an SQL SELECT…INTO statement.

    Note In Oracle, a Make Table query is implemented as a Create Table as Select command. For details, see Query Designer Considerations for Oracle Databases.

In addition to the queries you can create using the graphical panes, you can enter any SQL statement into the SQL pane, such as Union queries.

When you create queries using SQL statements that cannot be represented in the graphical panes, the Query Designer dims those panes to indicate that they do not reflect the query you are creating. However, the dimmed panes are still active and, in many cases, you can make changes to the query in those panes. If the changes you make result in a query that can be represented in the graphical panes, those panes are no longer dimmed.

For details about unsupported query types in SQL Server, see Query Designer Considerations for SQL Server Databases. For details about unsupported query types in Oracle, see Query Designer Considerations for Oracle Databases.


Creating a Query

The basic process of creating a query, regardless of the options you specify, consists of these steps:

  1. Starting a new query. For details, see Creating Queries.

  2. Choosing one or more input sources (tables or views) to work with. For details, see Adding Input Sources.

  3. Specifying the data columns to work with in the query, such as the columns to display or to use in search conditions. For details, see Adding Columns.

  4. Specifying the order for rows in the query output, if appropriate. Typically, you order rows only if you are creating a Select query. For details, see Ordering Query Results.

  5. Specifying search criteria to indicate which rows to display (for Select queries) or that will be affected (for Update, Delete, and Insert queries). For details, see Specifying Search Conditions.

  6. Running the query. For details, see Executing a Query.

You can use additional Query Designer features to create more complex queries. For example, you can create queries that:

  • Join two or more tables to display data from multiple tables in one query. For details, see Querying Using Multiple Tables.

  • Produce summary information such as totals, averages, and so on. For details, see Summarizing and Grouping.

  • Update a database directly or using a query. For details, see Modifying Data in Tables.

  • Prompt for values (such as search values) when you run the query. For details, see Specifying Search Conditions.

  • Create or edit views. For details, see Creating a View.


Navigating in the Query Designer

You can work in the Query Designer using the keyboard or the mouse. Refer to the following tables for specific methods.

Any Pane

To | Press | Click
Move among the Query Designer panes | F6, SHIFT+F6 | Anywhere in the target pane

Diagram Pane

To | Press | Click
Move between input source windows (and to join lines, if available) | TAB, SHIFT+TAB | The input source window or join line to move to
Move between columns in an input source window | Arrow keys | The column to go to
Choose the selected data column for output | SPACEBAR1 or PLUS key | The check box next to the name of the column
Remove the selected data column from the query output | SPACEBAR1 or MINUS key | The check box next to the name of the column
Remove the selected input source or join line from the query | DELETE | Right-click, and then choose Remove

1If multiple items are selected, pressing this key affects all selected items. Select multiple items by holding down the SHIFT key while clicking them. Toggle the selected state of a single item by holding down CTRL while clicking it.

Grid Pane

To | Press | Click
Move among cells | Arrow keys or TAB or SHIFT+TAB | The target cell
Move to the last row in the current column | CTRL+DOWN ARROW |
Move to the first row in the current column | CTRL+UP ARROW |
Move to the top left cell in the visible portion of grid | CTRL+HOME |
Move to the bottom right cell | CTRL+END |
Move in a drop-down list | UP ARROW or DOWN ARROW | The button in the cell
Select an entire grid column | CTRL+SPACEBAR | The column header
Select an entire grid row |  | The button to the left of the row
Toggle between edit mode and cell selection mode | F2 |
Copy selected text in cell to the Clipboard (in edit mode) | CTRL+C |
Cut selected text in cell and place it on the Clipboard (in edit mode) | CTRL+X |
Paste text from the Clipboard (in edit mode) | CTRL+V |
Toggle between insert and overstrike mode while editing in a cell | INS |
Toggle the check box in the Output column | SPACEBAR1 | The check box
Clear the selected contents of a cell | DELETE |
Remove row containing selected data column from the query | DELETE1 |
Clear all values for a selected grid column | DELETE |
Insert row between existing rows | INS after you select grid row |
Add an Or … column | INS after you select any Or ... column |

1If multiple items are selected, pressing this key affects all selected items.

SQL Pane

You can use the standard Windows editing keys when working in the SQL pane, such as CTRL+Arrow keys to move between words, and the Cut, Copy, and Paste commands on the Edit menu.

Note You can only insert text; there is no overstrike mode.

Results Pane

To | Press | Click
Move between cells | Arrow keys or TAB or SHIFT+TAB | The target cell
Move to first or last cell in current row | HOME or END |
Move to the last row in the current column | CTRL+DOWN ARROW |
Move to the first row in the current column | CTRL+UP ARROW |
Move to the top left cell | CTRL+HOME |
Move to the bottom cell in the first column | CTRL+END |
Move to first or last character in a cell | SHIFT+HOME or SHIFT+END |
Select an entire grid column | CTRL+SPACEBAR | The column header
Select an entire grid row |  | The button to the left of the row
Toggle between edit mode and cell selection mode | F2 |
Toggle between insert and overstrike mode while editing in a cell | INS |
Insert a new row into the grid (moves to last row in grid) | INS while cell is selected |
Delete a row from the table | DELETE1 |
Undo changes for the current cell | ESC in cell that has changed |
Undo changes for the current row | ESC in cell that has not changed |
Enter null into a cell | CTRL+0 |
Copy selected columns or rows to the Clipboard | CTRL+C |
Copy selected text in cell to the Clipboard (in edit mode) | CTRL+C |
Cut selected text in cell to the Clipboard (in edit mode) | CTRL+X |
Paste text from the Clipboard (in edit mode) | CTRL+V |

1If multiple items are selected, pressing this key affects all selected items.


Using the Query Designer with International Data

You can use the Query Designer with data in any language and in any version of Windows®. The following guidelines outline the differences you will notice, and they provide information about managing data in international applications.

Note For additional information about ANSI to OEM character conversion in SQL Server, see Query Designer Considerations for SQL Server Databases.

Localized Information in the Grid and SQL Panes

If you are using the Grid pane to create your query, you can enter information in the format that corresponds to the Windows Regional Settings for your computer. For example, if you are searching for a date, you can enter the date in the Criteria columns using whatever format you are accustomed to using, with these exceptions:

  • Long date formats are not supported.

  • Currency symbols should not be entered in the Grid pane. However, the correct symbol will appear in the Results pane.

  • Unary minus always appears on the left side (for example, -1) regardless of the Regional Settings options.

In contrast, data and keywords in the SQL pane must always be in ANSI (U.S.) format. For example, as the Query Designer builds a query, it inserts the ANSI form of all SQL keywords such as SELECT and FROM. If you add elements to the statement in the SQL pane, be sure to use the ANSI-standard form for the elements.

When you enter data using locale-specific format in the Grid pane, the Query Designer automatically translates it to ANSI format in the SQL pane. For example, if your Regional Settings are set to Standard German, you can enter a date in the Grid pane in a format such as "31.12.96." However, the date will appear in the SQL pane in ANSI datetime format as { ts '1996-12-31 00:00:00' } If you enter data directly in the SQL pane, you must enter it in ANSI format.

Sort Order

The sort order (collation sequence) of data in your query is determined solely by the database. Options that you set in the Windows Regional Settings dialog box do not affect sort order for queries.

Using Double-Byte Characters

You can enter DBCS characters for literals and for database object names such as table and view names or aliases. You can also use DBCS characters for parameter names and parameter marker characters. However, you cannot use DBCS characters in SQL language elements such as function names or SQL keywords.


Creating Queries

The Query Designer features an easy-to-use interface for working with your queries. The topics in this section describe the fundamentals of working with any query, including how to choose a table or view to work with, how to add or remove data columns from the query, and how to execute the query.

To | See
Add or remove input sources from a query | Adding Input Sources Removing Input Sources
Add or remove columns from a query or from the query output | Adding Columns Removing Columns from Query Output Removing Columns from the Query
Change how query results are displayed | Reordering Output Columns Ordering Query Results
Clear or print the query results | Clearing Query Results Printing Query Results
Create aliases for tables or columns | Creating Table Aliases Creating Column Aliases
Check the syntax of a query | Verifying a Query
To run or stop a query | Executing a Query Stopping a Query


Adding Input Sources

When you create a query, you are retrieving data from or modifying an input source: one or more tables or views. To work with input sources in your query, you add them to the Diagram pane.

Note For information about adding tables from different data sources while working with SQL Server, see Query Designer Considerations for SQL Server Databases.

To add a table or view to the query

  1. In the Project Explorer, expand the available data connections, right-click the data connection to use, and then choose Add Query.

  2. In the Add Item dialog box, select Database Query, in the Name box type in the name of your new query, and then choose Open.

    The Query Designer opens, and if it is not already open, the Data View window opens.

  3. In the Data View window, select one or more tables or views, or one or more individual columns, and then drag them into the Diagram pane of the Query Designer.

    Note If you are working with an Oracle database, you can also use synonyms as input sources. For details, see Query Designer Considerations for Oracle Databases.

The Query Designer updates the SQL pane with a skeleton Select query.

If you drag an individual data column into the Diagram pane, the column is added to the query for output. If the table from which you drag the column has not already been added, the Query Designer adds the table with the specified column selected as an input source to the query.

Note You can add tables or views only from the data connection you are working with, even though other data connections are visible in the Project Explorer.

You can also drag columns or tables from the Database Designer or paste them from the Clipboard. For information about using the Database Designer, see Working in Database Diagrams.

Tables and views are automatically added to the query when you reference them in the statement in the SQL pane.

The Query Designer will not display data columns for an input source if you do not have sufficient access rights to the input source or if the ODBC driver cannot return information about an input source you are using (for example, if no such table currently exists). In such cases, only a title bar is displayed for the input source window and the * (All Columns) check box.


Removing Input Sources

You can remove an input source if you no longer need that input source as part of your query.

Note Removing an input source does not delete the underlying table from the database; it only removes the input source from the current query. For details about removing a table from a database, see Deleting a Table from a Database Diagram and the Database.

To remove an input source

  • In the Diagram pane, select the input source, and then press DELETE, or right-click the input source and then choose Remove. You can select and remove multiple input sources at one time.

    –or–

  • Remove all references to the input source in the SQL pane.

When you remove an input source, the Query Designer automatically removes joins that involve that input source and removes references to the input source’s data columns in the SQL and Grid panes. However, if the query contains complex expressions that involve the table, the table name is not automatically removed until all references to the table are removed.


Adding Columns

To use a column in a query, you must add it to the query window. You might add a column to display it in query output, to use it for sorting, to search the contents of the column, or to summarize its contents.

If you are creating a Select query and add a column in the Diagram or Grid panes, the column you add becomes part of the query output. You can remove the column from the output and still use it for sorting, searching, and so on. For example, to find all employees in the accounting department, you might search the department column but not display it in the output.

Tip Wherever you use a column in a query, you can also use an expression that can consist of any combination of columns, literals, operators, and functions. For details, see Using Expressions in Queries.

You can add columns individually or as a group. Your choices are:

  • An individual column from one table, to use for sorting, searching, or summarizing.

  • All columns from one input source. This is the equivalent of specifying "tablename.*" in the SQL statement.

  • All columns from all input sources, which can be useful if you are working with joined tables. This option is the equivalent of specifying "*" alone in the SQL statement when more than one table is used in the query.

When you add all columns, the Query Designer does not add all individual columns to the query. If you need to work with a specific column, you must add it separately.

Note When you choose "*", all currently defined columns for the tables you are using are included. If a table definition changes, the list of columns returned by "*" changes as well. It is recommended that, if practical, you specify the columns you want to work with instead of using "*".

To add an individual column

  • In the Diagram pane, select the check box next to the data column that you want to include.

    -or-

  • In the Grid pane, move to the first blank grid row where you want to add the column, click the field in the Column column, and select a column name from the list.

    Note To add a data row at a specific location in the Grid pane, select the grid row where you want to add the new column and press INS. A new column is added above that row.

To add all columns for one input source

  • In the Diagram pane, select the check box [image] next to (All Columns).

    –or–

  • Specify tablename.* in the SQL statement in the SQL pane, substituting the name of your input source for tablename.

    Note Oracle does not permit you to combine the "*" operator with individual column names. For details, see Query Designer Considerations for Oracle Databases.

To add all columns for all input sources

  1. Make sure no join lines between input sources in the Diagram pane are selected.

  2. Right-click in the query window and choose Properties from the shortcut menu. Then choose the Query tab.

  3. Choose Output all columns.

    –or–

    Specify * in the output list of the SQL statement in the SQL pane.

    Note Oracle does not permit you to combine the "*" operator with individual column names. For details, see Query Designer Considerations for Oracle Databases.


Removing Columns from Query Output

If you are using a column in a Select query but don’t want to display it in the result set (that is, you don’t want it in the query’s select list), you can remove it from output. After you remove the column from the query’s output, you can still use it in a search condition, to sort the query, and so on.

Note If you want to remove a column from the query altogether, see Removing Columns from the Query.

To remove a column from the query output

  • In the Diagram pane, clear the check box next to the name of the column you want to remove.

    -or-

  • In the Grid pane, clear the check box in the Output column for the data column you want to remove. (If you want to add the column back to the query output, you can check the Output column again.)

    -or-

  • Remove the column from the output list in the SQL pane.


Removing Columns from the Query

If you no longer want to use a column in a query, you can remove it. If you do, the Query Designer removes references to the column in the display list, the sort specification, the search criteria, and any grouping specifications.

Note If you want to remove a column from just the output of a Select query, you can do so without removing it from the query altogether. For details, see Removing Columns from Query Output.

To remove a column from the query

  • In the Grid pane, select the grid row containing the column you want to remove and then press DELETE.

    -or-

  • Remove all references to the column in the SQL pane.


Reordering Output Columns

The order in which you add data columns to a Select query determines the order in which they appear in the results. The first column you add to the query appears leftmost in the results, the second column next, and so on.

If you are creating Update or Insert queries, the order in which you add columns affects the order in which data is processed.

To control where a data column appears in the result set, or in what order it is used, you can reorder the columns.

To reorder columns for output

  1. In the Grid pane, select the row containing the column by clicking the row selector button to the left of the row ( [image]).

  2. Point to the button to the left of the row, and then drag the row to a new location.

    -or-

    Edit the order of the column names in the SQL pane.

Tip You can add a data row at a specific location in the Grid pane by inserting a blank row into the Grid pane, and then specifying the data column to insert. For details, see Adding Columns.


Creating Table Aliases

Aliases can make it easier to work with table names. Using aliases is helpful when:

  • You want to make the statement in the SQL pane shorter and easier to read.

  • You refer to the table name often in your query — such as in qualifying column names — and want to be sure you stay within a specific character-length limit for your query. (Some databases impose a maximum length for queries.)

  • You are working with multiple instances of the same table (such as in a self-join) and need a way to refer to one instance or the other.

For example, you can create an alias "e" for a table name employee_information, and then refer to the table as "e" throughout the rest of the query.

You create table aliases in the SQL pane; you cannot create them in the Grid pane.

To create a table alias

  1. Add the input sources to your query.

  2. In the FROM clause in the SQL pane, add the alias name to each table you are creating an alias for. For example, to assign the alias "e" to the employee_information table and "p" to the positions table, you can create a FROM clause such as the following:
    FROM employee_information e, positions p

    Note For most databases, you can add the option keyword AS between the table name and alias (for example, FROM employee_information AS e). However, some databases do not allow this keyword. For details, see Query Designer Considerations for Oracle Databases.

When you create a table alias, the Query Designer substitutes the alias for the corresponding table name in the Table column of the Grid pane.

Note The SQL standard specifies that when you create an alias for a table name, you must use the alias to refer to the table in the rest of the SQL statement (that is, you cannot use the original table name). However, some databases do allow you to refer to the table by its original name. For details, refer to the documentation for your database.


Creating Column Aliases

You can create aliases for column names to make it easier to work with column names, calculations, and summary values. For example, you can create a column alias to:

  • Create a column name, such as "Total Amount," for an expression such as (quantity * unit_price) or for an aggregate function. The alias is used in the column heading in the Results pane.

  • Create a shortened form of a column name, such as "d_id" for "discounts.stor_id." Using a column alias is particularly useful when the query contains multiple tables, because you can create short aliases to refer to fully qualified column names.

After you have defined a column alias, you can use the alias in a Select query to specify query output.

Note Column aliases do not appear in the list of data columns in the Columns column of the Grid pane. However, you can type in the name of an existing column alias to reference it in the Grid pane.

To create a column alias

  1. In the Grid pane, locate the row containing the data column for which you want to create an alias, and if necessary, mark it for output. If the data column is not already in the grid, add it.

  2. In the Alias column for that row, enter the alias. The alias must follow all naming conventions for SQL (for example, it cannot be a reserved word). If the alias name you enter contains spaces, the Query Designer automatically puts quotation marks around it.


Verifying a Query

To avoid problems, you can check the query you have built to ensure its syntax is correct. This option is especially useful when you enter statements in the SQL pane.

Note A statement can be valid, and therefore be verified successfully, even if it cannot be represented in the Diagram and Grid panes.

To verify an SQL statement

  • Right-click in the SQL pane, and select [image] Verify SQL Syntax from the shortcut menu.


Executing a Query

When you have finished designing your query, you can run it.

Note If you want to test whether the syntax of the query you are creating is correct, you can verify the query. For details, see Verifying a Query.

To execute a query

  • Right-click anywhere in the query window, and select Run from the shortcut menu.

If you are creating a Select query, the results of the query appear in the Results pane.

The Query Designer runs queries in batches (incrementally) so that you can begin viewing results as soon as possible, and so that you can perform other tasks while the query is underway.

If you are creating an Update, Insert, Insert Values query, Delete, or Make Table query, the Query Designer displays a message indicating how many rows were affected by the query.

For information on viewing results and navigating in the Results pane, see Results Pane.


Stopping a Query

If you see that the query is not returning the results you expect, you can stop the query if it has not already finished.

To stop a query

  • Right-click anywhere in the Results pane, and then choose Clear Results.

The Query Designer also stops the current query if you execute a new query.


Clearing Query Results

If you change the current query definition, the Query Designer dims the Results pane to indicate that the contents of the pane no longer reflect the query you are editing. You can also clear the contents of the Results pane.

To clear query results

  • Right-click in the Results pane, and then choose Clear Results.

If a query is being executed when you clear the Results pane, the Query Designer stops the query.


Printing Query Results

To print the results of your query, you can copy the contents of the Results pane to another Windows program, such as a word processing program, then format and print it there.

The Query Designer puts query results onto the Clipboard using tabs as delimiters between columns and carriage return and linefeed characters as delimiters between rows.

To print query results

  1. Select the columns or rows that you want to print.

  2. Use the Copy command to move them to the Clipboard.

  3. Switch to the Windows program you want to use to print the results.

  4. Use the Paste command to move the query results from the Clipboard.

  5. Format and print the results.


Ordering Query Results

You can order your query by the contents of a data column or by an expression. The Query Designer allows you to specify the sort types ascending and descending.

You can also order the query results by more than one column or expression and specify the sort order for each. For example, if you are querying an employee table, you can order the results by department (sort order = 1) and within each department by last name (sort order = 2).

Note You cannot sort by the contents of a memo or binary (BLOB) column.

To order query results

  1. If you have not already, add the columns or expressions that you want to sort by to the Grid pane.

    If you don’t want the columns or expressions to be part of the query results, remove them as output columns.

  2. In the Grid pane, locate the row containing the first data column or expression to sort by, and then in the Sort Type grid column, choose Ascending or Descending.

  3. If you are sorting by multiple columns or expressions, specify the sort order in the Sort Order column of the grid.

    –or–

    In the Diagram pane, right-click the column to sort by and then choose Sort Ascending or Sort Descending from the shortcut menu. You can select multiple columns before right-clicking them. If you use this method, the columns are sorted in the order you select them.


Specifying Search Criteria

To restrict the number of rows a Select query should return, or to specify the rows affected by an Update, Insert Values, Insert, Delete, or Make Table query query, you create search conditions or filter criteria. In SQL, search conditions appear in the WHERE clause of the statement, or if you are creating an aggregate query, in the HAVING clause.

When the query runs, the database engine examines and applies the search condition to each row in the tables you are searching. If the row meets the condition, it is included in the query. For example, a search condition that would find all the employees in a particular region might be:

region = 'UK'

Predicates in Search Conditions

A search condition consists of one or more predicates, each specifying a single condition. If the search condition includes more than one predicate, the predicates are linked with a logical AND (to narrow the search) or OR (to broaden it). The following example shows how you can use multiple conditions when searching an employee table to find the employee (or employees) with the specified first and last names:

WHERE lname = 'Smith' AND fname = 'Jean'

A single predicate follows this format:

search_expression operator search_value

In most instances, search_expression is the name of a column to search. Similarly, the most common form of search_value is a literal value to search for, which can be either a string of characters or a number.

The following two examples show literal values. The first searches for all the employees who are in the United Kingdom, and the second searches for all employees with a specific job level:

WHERE region = 'UK'

WHERE job_lvl = 100

Both search_expression and search_value can consist of any (or any combination) of the following:

  • Literal A single text, numeric, date, or logical value. The following example uses a literal to find all rows for employees in the United Kingdom:
    WHERE region = 'UK'
  • Column reference The name of a column in one of the tables being searched. The following example searches a products table for all rows in which the value of the production cost is lower than the shipping cost:
    WHERE prod_cost < ship_cost
  • Function A reference to a function that the database back end can resolve to calculate a value for the search. The following example searches for orders placed today (the GETDATE( ) function returns the current date):
    WHERE order_date = GETDATE()
  • NULL The following example searches an authors table for all authors who have a first name on file:
    WHERE au_fname IS NOT NULL
  • Calculation The result of a calculation that can involve literals, column references, or other expressions. The following example searches a products table to find all rows in which the retail sales price is more than twice the production cost:
    WHERE sales_price > (prod_cost * 2)
  • Subquery A result set generated by another query. The following example searches a products table to find all the products from Swedish suppliers. The subquery first searches the suppliers table to build a list of the suppliers located in that country. The second search then searches the products table, matching the product’s supplier ID against the list created by the subquery:
    WHERE supplier_id IN
  (SELECT supplier.supplier_id
  FROM supplier
  WHERE (supplier.country = 'Sweden'))

For more details about creating search conditions, refer to the topics listed in the following table.

For information about | See
Specifying search conditions in the Query Designer | Specifying Search Conditions
How to create expressions that you can use in search conditions | Using Expressions in Queries
The operators you can use in search conditions | Comparison Operators, Logical Operators, and Wildcard Characters
How to enter text, numbers, dates, or logical values | Entering Search Values
Finding rows that do not match a value | Selecting Rows that Do Not Match a Value
Removing duplicate rows from Select queries | Excluding Duplicate Rows
Applying multiple search conditions to the same data column | Specifying Multiple Search Conditions for One Column
Including several data columns as part of the search condition for a query | Specifying Multiple Search Conditions for Multiple Columns
Linking search conditions with AND and OR operators | Combining Search Conditions
Using subqueries | Creating Subqueries


Specifying Search Conditions

You can specify the data rows that appear in your query by specifying search conditions. For example, if you are querying an employee table, you can specify that you want to find only the employees who work in a particular region.

You specify search conditions using an expression. Most commonly the expression consists of an operator and a search value. For example, to find employees in a particular sales region, you might specify the following search criterion for the region column:

='UK'

Note If you are working with multiple tables, the Query Designer examines each search condition to determine whether the comparison you are making results in a join. If so, the Query Designer automatically converts the search condition into a join. For more information, see Joining Tables Automatically.

To enter search conditions

  1. If you have not already, add the columns or expressions that you want to search to the Grid pane.

    If you are creating a Select query and don’t want the search columns or expressions to appear in the query output, remove them as output columns.

  2. Locate the row containing the data column or expression to search, and then in the Criteria grid column, enter a search condition.

    If you do not enter an operator, the Query Designer automatically inserts the equality operator "=".

The Query Designer updates the SQL statement in the SQL pane by adding or modifying the WHERE clause.


Comparison Operators

You can use any standard SQL operators in a search condition. When you use operators in a search condition, the following rules apply:

  • The data types of the data used in the comparison must match. That is, only text can be compared to text, numbers to numbers, and so on. Some databases allow you to use a function or keyword (such as CAST) to temporarily convert data to another data type. For details, refer to the documentation for your database.

  • If you compare text data, the result depends on the character set currently in use. For example, if a table was created using Scandinavian characters, the search results might differ depending on whether your current character set (code page) is Scandinavian or another character set.

  • If a comparison value is null, the result is unknown. Nulls are not matched to any value, including other instances of null. For example, if you are searching for a name beginning with the letter "M" or higher (name >= 'M'), and some of the rows contain no value, those rows do not appear, no matter what comparison operator you use.

The following table summarizes search condition operators that are defined for standard SQL.

Note The information in this topic is derived from the rules for standard SQL-92. However, each database can implement SQL in its own way. Therefore, the guidelines provided here might not apply in every case. If you have questions about how to use operators with a particular database, refer to the documentation for the ODBC driver or database that you are using.

Operator Meaning Grid pane example1 SQL pane example
= Equal
= 'Smith'

SELECT fname, lname
FROM employees
WHERE lname = 'Smith'
<>
!= 		Not equal to
<> 'Active'

SELECT fname, lname
FROM employees
WHERE status <> 'Active'
> Greater than
> '01 Jan 1995'2

SELECT fname, lname
FROM employees
WHERE hire_date <
 '12/31/90'
< Less than
< 100

SELECT fname, lname
FROM employees
WHERE job_lvl < 100
>=
!< 		Greater than or equal to
>= 'T'

SELECT au_lname
FROM authors
WHERE au_lname >= 'T'
<=
!> 		Less than or equal to
<= '01 Jan 1995' 2

SELECT fname, lname
FROM employees
WHERE hire_date <
 '01/01/95'
BETWEEN expr1
AND expr2 		Tests range of values
BETWEEN
'01 Jan 1995'
AND
'31 Dec 1995’2

SELECT fname, lname
FROM employees
WHERE hire_date
 BETWEEN '12/31/90'
 AND '12/31/91'
IS [NOT] NULL Tests whether contents of column or result of expression is null
IS NULL

SELECT fname, lname
FROM employees
WHERE photo_on_file IS NULL
[NOT] LIKE Performs pattern matching (usually restricted to character data types)
LIKE ('MAC%')

SELECT fname, lname
FROM employees
WHERE lname LIKE ('MAC%')
expr1 [NOT] IN
(val1, val2, …)

– or –

expr1 [NOT] IN
(subquery) 		Matches list of specific values by testing whether expr1 appears either in a list of values or in the result set of a subquery
IN ('SW', 'SE')

supplier_id IN
  (subquery)

SELECT fname, lname
FROM employees
WHERE sales_region IN ('SW', 'SE')

SELECT product_name
FROM products
WHERE supplier_id IN
  (SELECT supplier_id
  FROM supplier
  WHERE (country = 'Sweden'))
ANY (SOME) Tests whether one or more rows in the result set of a subquery meet the specified condition. (ANY and SOME are synonyms; the Query Designer will use ANY when creating an SQL statement.)
<> ANY (subquery)

SELECT au_lname, au_fname
FROM authors
where city <> any
 (SELECT city FROM publishers)
ALL Tests whether all rows in the result set of a subquery meet the specified condition
advance > ALL (subquery)

SELECT title FROM titles
where advance > all
  (SELECT advance FROM
   publishers,titles
  where titles.pub_id
   = publishers.pub_id
  AND pub_name =
   'Alogdata Infosystems')
[NOT] EXISTS Tests whether a subquery returns any results whatsoever (not a specific result)
EXISTS (subquery)

SELECT product_name
FROM products
WHERE EXISTS
  (SELECT * FROM
   orders, products
  WHERE orders.prod_id
  = products.prod_id)

1For clarity, the Grid pane examples include only one example for each operator and do not indicate which data column is being searched.

2Dates can be entered in the Grid pane using the format specified in the Windows Regional Settings dialog box. For details, see Entering Search Values.


Logical Operators

You can combine or modify search conditions using the standard logical operators listed in the following table. The operators are listed in the order that they are evaluated.

Operator Meaning Example
NOT Logical opposite of condition
SELECT * FROM employee
WHERE NOT (fname = 'Ann')
AND Both conditions must apply
SELECT * FROM employee
WHERE lname = 'Smith' AND fname = 'Ann'
OR Either condition can apply
SELECT * FROM employee
WHERE region = 'UK' OR region = 'FRA'


Wildcard Characters

You can search for patterns within data columns or expressions by using wildcard characters. For example, you can search for all employees whose last names begin with "Mac" or end with "son."

In this topic, you can read about:

  • Wildcard Characters

  • Searching for Characters Used as Wildcard Characters

  • Searching Datetime Columns

  • Examples of Wildcard Searches

Wildcard Characters

You can use wildcard characters to search any columns that can be treated as text strings. Columns with the data type character can always be treated as text strings; those with datetime data can be treated as text strings for some databases.

To search for patterns, use the LIKE operator, and then substitute wildcard characters for one or more characters in the search string. You can use either of the following wildcard characters:

Wildcard character | Meaning
% (percent symbol) | Zero or more characters in that position
_ (underscore) | One character at that position

For example, to search for all names beginning with "Mac," you could specify the search condition LIKE 'Mac%'. To find names such as "Jan," "Jen," and "Jon," you could specify the search condition LIKE 'J_n'.

Searching for Characters Used as Wildcard Characters

In some cases, you might need to search for a string that contains one of the characters used as a wildcard character. For example, in a titles table you might want to find all the publications that contain the string "10%" as part of the title. Because "%" is part of the string you are searching for, you must specify that you mean it as a literal string and not a wildcard character.

To search for characters that can be interpreted as wildcard characters, you can specify an escape character. Place the escape character immediately in front of the "%" or "_" character that you mean literally. To specify the escape character, include an ESCAPE clause immediately after the LIKE search criterion. You can do this in either the Criteria column of the Grid pane or in the SQL pane.

For example, imagine that you want to find all titles that contain the string "10%". Suppose you want to define the character "#" as an escape character, which allows you to include "#" in front of the "%" character that is meant literally. You can enter this in the Grid pane:

LIKE '%10#%%' ESCAPE '#'

The resulting WHERE clause in the SQL statement looks like this:

WHERE title LIKE '%10#%%' ESCAPE '#'

Note You can define an escape character only in the SQL pane.

Searching Datetime Columns

When working with a datetime data type column, you can search any portion of the date or time, including text abbreviations of the month and complete years.

Note The ability to search datetime columns depends on the database you are using and whether datetime data types can be searched as strings. For details, see the documentation for your database.

For example, in a Microsoft® SQL Server™ database, you can use the following LIKE clause to search for all rows in which the date falls within 1994:

LIKE '%1994%'

The following searches for all rows in which the date falls within the month of January, regardless of year:

LIKE 'Jan%'

The exact format of the strings you can use to search a datetime column depends on the database you are using.

Examples of Wildcard Searches

The following examples illustrate the use of wildcard characters.

Search expression Description Sample matches
LIKE 'Mac%'
 Finds values beginning with "Mac" Mac
MacIntosh
Mackenzie
LIKE 'J%n'
 Finds values starting with "J" and ending with "n" Jon
Johnson
Jason
Juan
LIKE '%son'
 Finds values ending with "son" Son
Anderson
LIKE '%sam%'
 Finds values with "sam" anywhere in the string Sam
Samson
Grossam
LIKE '%Mar%'
 Finds values in a datetime column that fall in the month of March, regardless of year 3/1/94
01 Mar 1992
LIKE '%1994%'
 Finds values in a datetime column for the year 1994. 12/1/94
01 Jan 1994
LIKE 'Mac_'
 Finds values with exactly four characters, the first three being "Mac" Mack
Macs
LIKE '_dam'
 Finds values with exactly four characters, the last three being "dam" Adam
Odam
LIKE '%s_n'
 Finds values containing "s" and "n" at the end of the value, with any one character between them and any number of characters in front of them Anderson
Andersen
Johnson
san
sun


Entering Search Values

This topic discusses the conventions you must use when entering the following types of literal values for a search condition:

  • Text values

  • Numeric values

  • Dates

  • Logical values

Note The information in this topic is derived from the rules for standard SQL-92. However, each database can implement SQL in its own way. Therefore, the guidelines provided here might not apply in every case. If you have questions about how to enter search values for a particular database, refer to the documentation for the database that you are using.

Searching on Text Values

The following guidelines apply when you enter text values in search conditions:

  • Quotation marks Enclose text values in single quotation marks, as in this example for a last name:
    'Smith'

    If you are entering a search condition in the Grid pane, you can simply type the text value and the Query Designer will automatically put single quotation marks around it.

    Note In some databases, terms in single quotation marks are interpreted as literal values, whereas terms in double quotation marks are interpreted as database objects such as column or table references. Therefore, even though the Query Designer can accept terms in double quotation marks, it might interpret them differently than you expect. For details about the use of quotation marks for database identifiers in Oracle, see Query Designer Considerations for Oracle Databases.

  • Embedding apostrophes If the data you are searching for contains a single quotation mark (an apostrophe), you can enter two single quotation marks to indicate that you mean the single quotation mark as a literal value and not a delimiter. For example, the following condition searches for the value "Swann’s Way":
    ='Swann''s Way'
  • Length limits Do not exceed the maximum length of the SQL statement for your database when entering long strings. The SQL standard does not impose a maximum length on literal strings, but most ODBC drivers have a maximum length limit for a statement.

  • Case sensitivity Follow the case sensitivity rules for the database you are using. The database you are using determines whether text searches are case sensitive. For example, some databases interpret the operator "=" to mean an exact case-sensitive match, but others will allow matches on any combination of uppercase and lowercase characters. For details about case sensitivity in SQL Server, see Query Designer Considerations for SQL Server Databases.

    If you are unsure about whether the database uses a case-sensitive search, you can use the UPPER or LOWER functions in the search condition to convert the case of the search data, as illustrated in the following example:

    WHERE UPPER(lname) = 'SMITH'

    For details about the functions to convert to uppercase and lowercase letters, see Functions for Expressions.

Searching on Numeric Values

The following guidelines apply when you enter numeric values in search conditions:

  • Quotation marks Do not enclose numbers in quotation marks.

  • Non-numeric characters Do not include non-numeric characters except the decimal separator (as defined in the Regional Settings dialog box of the Windows® Control Panel) and negative sign (-). Do not include digit grouping symbols (such as a comma between thousands) or currency symbols.

  • Decimal marks If you are entering whole numbers, you can include a decimal mark, whether the value you are searching for is an integer or a real number.

  • Scientific notation You can enter very large or very small numbers using scientific notation, as in this example:
    > 1.23456e-9

Note For details about entering currency values in SQL Server, see Query Designer Considerations for SQL Server Databases.

Searching on Dates

The format you use to enter dates depends on the database you are using and in what pane of the Query Designer you are entering the date. The Query Designer can work with the following date formats:

  • Locale-specific The format specified for dates in the Windows Regional Settings Properties dialog box.

  • Database-specific Any format understood by the database.

  • ANSI standard date A format that uses curly brackets, the marker ‘d’ to designate the date, and a date string, as in the following example:
    { d '1990-12-31' }
  • ANSI standard datetime Similar to ANSI-standard date, but uses ‘ts’ instead of ‘d’ and adds hours, minutes, and seconds to the date (using a 24-hour clock), as in this example for December 31, 1990:
    { ts '1990-12-31 00:00:00' }

    In general, the ANSI standard date format is used with databases that represent dates using a true date data type. In contrast, the datetime format is used with databases that support a datetime data type.

Note For details about working with dates in Oracle, see Query Designer Considerations for Oracle Databases.

The following table summarizes the date format that you can use in different panes of the Query Results.

Pane | Date format
Grid | Locale-specific Database-specific ANSI standard Dates entered in the Grid pane are converted to a database-compatible format in the SQL pane.
SQL | Database-specific ANSI standard Dates entered into the SQL pane are converted to the locale-specific format in the Grid pane.
Results | Locale-specific

Searching on Logical Values

The format of logical data varies from database to database. Very frequently, a value of False is stored as zero (0). A value of True is most frequently stored as 1 and occasionally as -1. The following guidelines apply when you enter logical values in search conditions:

  • To search for a value of False, use a zero, as in the following example:
    SELECT * FROM authors
WHERE contract = 0
  • If you are not sure what format to use when searching for a True value, try using 1, as in the following example:
    SELECT * FROM authors
WHERE contract = 1
  • Alternatively, you can broaden the scope of the search by searching for any non-zero value, as the following example:
    SELECT * FROM authors
WHERE contract <> 0


Selecting Rows that Do Not Match a Value

To find row that do not match a value, use the NOT operator. For example, to find all the rows in a products table where the values in the product code column begin with a character other than "A," you can enter a search condition such as the following:

NOT LIKE 'A%'


Excluding Duplicate Rows

Some Select queries create result sets that contain duplicate rows. For example, the following query for an employee table displays the job code for each row in the table:

SELECT job_id
FROM employee
ORDER BY job_id

Because more than one employee can have the same job, this query can create a result set similar to the following:

job_id

2
3
4
5
5
6
6
...

Note The duplicate rows displayed by the query do not necessarily represent true duplicates in the input source for the query. Instead, they appear as duplicates in the result set because columns that would otherwise distinguish one row from another are not displayed.

If you want to see only unique values in a result set, you can specify that you want to exclude duplicates from the result set.

To exclude duplicate rows from the result set

  1. Ensure nothing is selected, then choose Property Pages from the View menu.

  2. In the Query tab of the Property pages window, select Distinct values.

    The Query Designer inserts the keyword DISTINCT in front of the list of display columns in the SQL statement.

    Note Using the DISTINCT keyword in SQL Server results in a non-editable query.


Specifying Multiple Search Conditions for One Column

In some instances, you might want to apply a number of search conditions to the same data column. For example, you might want to:

  • Search for several different names in an employee table or for employees who are in different salary ranges. This type of search requires an OR condition.

  • Search for a book title that both starts with the word "The" and contains the word "Cook." This type of search requires an AND condition.

Note The information in this topic applies to search conditions in both the WHERE and HAVING clauses of a query. The examples focus on creating WHERE clauses, but the principles apply to both types of search conditions. For details about creating HAVING clauses, see Specifying Conditions for Groups.

To search for alternative values in the same data column, you specify an OR condition. To search for values that meet several conditions, you specify an AND condition.

Specifying an OR Condition

Using an OR condition enables you to specify several alternative values to search for in a column. This option expands the scope of the search and can return more rows than searching for a single value.

Tip You can often use the IN operator instead to search for multiple values in the same data column. For details, see Comparison Operators.

To specify an OR condition

  1. In the Grid pane, add the column to search.

  2. In the Criteria column for the data column you just added, specify the first condition.

  3. In the Or … column for the same data column, specify the second condition.

The Query Designer creates a WHERE clause that contains an OR condition such as the following:

SELECT fname, lname
FROM employees
WHERE (salary < 30000) OR (salary > 100000)

Specifying an AND Condition

Using an AND condition enables you to specify that values in a column must meet two (or more) conditions for the row to be included in the result set. This option narrows the scope of the search and usually returns fewer rows than searching for a single value.

Tip If you are searching for a range of values, you can use the BETWEEN operator instead of linking two conditions with AND. For details, see Comparison Operators.

To specify an AND condition

  1. In the Grid pane, add the column to search.

  2. In the Criteria column for the data column you just added, specify the first condition.

  3. Add the same data column to the Grid pane again, placing it in an empty row of the grid.

  4. In the Criteria column for the second instance of the data column, specify the second condition.

The Query Designer creates a WHERE clause that contains an AND condition such as the following:

SELECT title_id, title
FROM titles
WHERE (title LIKE '%Cook%') AND
  (title LIKE '%Recipe%')


Specifying Multiple Search Conditions for Multiple Columns

You can expand or narrow the scope of your query by including several data columns as part of your search condition. For example, you might want to:

  • Search for employees who either have worked more than five years at the company or who hold certain jobs.

  • Search for a book that is both published by a specific publisher and pertains to cooking.

Note Oracle allows you to use distributive syntax for specifying multiple criteria. For details, see Query Designer Considerations for Oracle Databases.

To create a query that searches for values in either of two (or more) columns, you specify an OR condition. To create a query that must meet all conditions in two (or more) columns, you specify an AND condition.

Note If you are creating queries that include combinations of AND and OR clauses, you must be aware of how the query is interpreted when you execute it. For details, see Combining Search Conditions.

Specifying an OR Condition

To create multiple conditions linked with OR, you put each separate condition in a different column of the Grid pane.

To specify an OR condition for two different columns

  1. In the Grid pane, add the columns you want to search. For details, see Adding Columns.

  2. In the Criteria column for the first column to search, specify the first condition. For details, see Specifying Search Conditions.

  3. In the Or … column for the second data column to search, specify the second condition, leaving the Criteria column blank.

    The Query Designer creates a WHERE clause that contains an OR condition such as the following:

    SELECT job_lvl, hire_date
FROM employee
WHERE (job_lvl >= 200) OR
  (hire_date < '01/01/90')
  4. Repeat Steps 3 and 4 for each additional condition you want to add. Use a different Or … column for each new condition.

Specifying an AND Condition

To search different data columns using conditions linked with AND, you put all the conditions in the Criteria column of the grid.

To specify an AND condition for two different columns

  1. In the Grid pane, add the columns you want to search.

  2. In the Criteria column for the first data column to search, specify the first condition.

  3. In the Criteria column for the second data column, specify the second condition.

    The Query Designer creates a WHERE clause that contains an AND condition such as the following:

    SELECT pub_id, title
FROM titles
WHERE (pub_id = '0877') AND (title LIKE '%Cook%')
  4. Repeat Steps 2 and 3 for each additional condition you want to add.


Combining Search Conditions

You can create queries that include any number of search conditions, linked with any number of AND and OR operators. A query with a combination of AND and OR clauses can become complex, so it is helpful to understand how such a query is interpreted when you execute it, and how such a query is represented in the Grid and SQL panes.

Note For details about search conditions that contain only one AND or OR operator, see Specifying Multiple Search Conditions for One Column and Specifying Multiple Search Conditions for Multiple Columns.

Below you will find information about:

  • The precedence of AND and OR in queries that contain both.

  • How the conditions in AND and OR clauses relate logically to one another.

  • How the Query Designer represents in the Grid pane queries that contain both AND and OR.

To help you understand the discussion below, imagine that you are working with an employee table containing the columns hire_date, job_lvl, and status. The examples assume that you need to know information such as how long an employee has worked with the company (that is, what the employee’s hire date is), what type of job the employee performs (what the job level is), and the employee’s status (for example, retired).

Precedence of AND and OR

When a query is executed, it evaluates first the clauses linked with AND, and then those linked with OR.

Note The NOT operator takes precedence over both AND and OR.

For example, to find either employees who have been with the company for more than five years in lower-level jobs or employees with middle-level jobs without regard for their hire date, you can construct a WHERE clause such as the following:

WHERE
   hire_date < '01/01/90' AND
   job_lvl = 100 OR
   job_lvl = 200

To override the default precedence of AND over OR, you can put parentheses around specific conditions in the SQL pane. Conditions in parentheses are always evaluated first. For example, to find all employees who have been with the company more than five years in either lower or middle-level jobs, you can construct a WHERE clause such as the following:

WHERE
   hire_date < '01/01/90' AND
   (job_lvl = 100 OR job_lvl = 200)

Tip It is recommended that, for clarity, you always include parentheses when combining AND and OR clauses instead of relying on the default precedence.

How AND Works with Multiple OR Clauses

Understanding how AND and OR clauses are related when combined can help you construct and understand complex queries in the Query Designer.

If you link multiple conditions using AND, the first set of conditions linked with AND applies to all the conditions in the second set. In other words, a condition linked with AND to another condition is distributed to all the conditions in the second set. For example, the following schematic representation shows an AND condition linked to a set of OR conditions:

A AND (B OR C)

The representation above is logically equivalent to the following schematic representation, which shows how the AND condition is distributed to the second set of conditions:

(A AND B) OR (A AND C)

This distributive principle affects how you use the Query Designer. For example, imagine that you are looking for all employees who have been with the company more than five years in either lower or middle-level jobs. You enter the following WHERE clause into the statement in the SQL pane:

WHERE (hire_date < '01/01/90' ) AND
   (job_lvl = 100 OR job_lvl = 200)

The clause linked with AND applies to both clauses linked with OR. An explicit way to express this is to repeat the AND condition once for each condition in the OR clause. The following statement is more explicit (and longer) than the previous statement, but is logically equivalent to it:

WHERE    (hire_date < '01/01/90' ) AND
  (job_lvl = 100) OR
  (hire_date < '01/01/90' ) AND
  (job_lvl = 200)

The principle of distributing AND clauses to linked OR clauses applies no matter how many individual conditions are involved. For example, imagine that you want to find lower or middle-level employees who have been with the company more than five years or are retired. The WHERE clause might look like this:

WHERE
   (job_lvl = 200 OR job_lvl = 300) AND
   (hire_date < '01/01/90' ) OR (status = 'R')

After the conditions linked with AND have been distributed, the WHERE clause will look like this:

WHERE
   (job_lvl = 200 AND hire_date < '01/01/90' ) OR
   (job_lvl = 200 AND status = 'R') OR
   (job_lvl = 300 AND hire_date < '01/01/90' ) OR
   (job_lvl = 300 AND status = 'R')

How Multiple AND and OR Clauses Are Represented in the Grid Pane

The Query Designer represents your search conditions in the Grid pane. However, in some cases that involve multiple clauses linked with AND and OR, the representation in the Grid pane might not be what you expect. In addition, if you modify your query in the Grid or Diagram panes, you might find that your SQL statement has been changed from what you entered.

In general, these rules dictate how AND and OR clauses appear in the Grid pane:

  • All conditions linked with AND appear in the Criteria grid column or in the same Or … column.

  • All conditions linked with OR appear in separate Or … columns.

  • If the logical result of a combination of AND and OR clauses is that the AND is distributed into several OR clauses, the Grid pane represents this explicitly by repeating the AND clause as many times as necessary.

Note The exact format of date information that you enter will depend on the database you are using. For details about entering dates, see Entering Search Values.

For example, in the SQL pane you might create a search condition such as the following, in which two clauses linked with AND take precedence over a third one linked with OR:

WHERE (hire_date < '01/01/90' ) AND
  (job_lvl = 100) OR
  (status = 'R')

The Query Designer represents this WHERE clause in the Grid pane as follows:

However, if the linked OR clauses take precedence over an AND clause, the AND clause is repeated for each OR clause. This causes the AND clause to be distributed to each OR clause. For example, in the SQL pane you might create a WHERE clause such as the following:

WHERE (hire_date < '01/01/90' ) AND
  ( (job_lvl = 100) OR
  (status = 'R') )

The Query Designer represents this WHERE clause in the Grid pane as follows:

If the linked OR clauses involve only one data column, the Query Designer can place the entire OR clause into a single cell of the grid, avoiding the need to repeat the AND clause. For example, in the SQL pane you might create a WHERE clause such as the following:

WHERE (hire_date < '01/01/90' ) AND
  ((status = 'R') OR (status = 'A'))

The Query Designer represents this WHERE clause in the Grid pane as follows:

If you make a change to the query (such as changing one of the values in the Grid pane), the Query Designer recreates the SQL statement in the SQL pane. The recreated SQL statement will resemble the Grid pane display rather than your original statement. For example, if the Grid pane contains distributed AND clauses, the resulting statement in the SQL pane will be recreated with explicit distributed AND clauses. For details, see "How AND Works with Multiple OR Clauses" earlier in this topic.


Combining Conditions when AND Has Precedence

To combine conditions with AND, you put the conditions in the same column of the Grid pane. To combine conditions with OR, you put the first one in the Criteria column and additional conditions into an Or … column.

For example, imagine that you want to find either employees who have been with the company for more than five years in lower-level jobs or employees with middle-level jobs regardless of their hire date. This query requires three conditions, two of them linked with AND:

  • Employees with a hire date earlier than five years ago and with a job level of 100

    -or-

  • Employees with a job level of 200

The following procedure illustrates how to create this type of query in the Grid pane.

To combine conditions when AND has precedence

  1. In the Grid pane, add the data columns you want to search. If you want to search the same column using two or more conditions linked with AND, you must add the data column name to the grid once for each value you want to search.

  2. In the Criteria column, enter all the conditions that you want to link with AND. For example, to link conditions with AND that search the hire_date and job_lvl columns, enter values as shown here:

    These grid entries produce the following WHERE clause in the statement in the SQL pane:

    WHERE (hire_date < '01/01/91') AND
  (job_lvl = 100)
  3. In the Or … grid column, enter conditions that you want to link with OR. For example, to add a condition that searches for another value in the job_lvl column, enter an additional value as shown here:

    Adding a value in the Or … column adds another condition to the WHERE clause in the statement in the SQL pane:

    WHERE (hire_date < '01/01/91' ) AND
  (job_lvl = 100) OR
  (job_lvl = 200)


Combining Conditions when OR Has Precedence

To link conditions with OR and give them precedence over conditions linked with AND, you must repeat the AND condition for each OR condition.

For example, imagine that you want to find all employees who have been with the company more than five years and those who have lower-level jobs or are retired. This query requires three conditions, a single condition linked to two additional conditions with AND:

  • Employees with a hire date earlier than five years ago, and

  • Employees with a job level of 100 or whose status is "R" (for retired).

The following procedure illustrates how to create this type of query in the Grid pane.

To combine conditions when OR has precedence

  1. In the Grid pane, add the data columns you want to search. If you want to search the same column using two or more conditions linked with AND, you must add the data column name to the grid once for each value you want to search.

  2. Create the conditions to be linked with OR by entering the first one into the Criteria grid column and the second (and subsequent ones) into separate Or … columns. For example, to link conditions with OR that search the job_lvl and status columns, enter values as shown here:

    Entering the values shown in the grid above produces the following WHERE clause in the statement in the SQL pane:

    WHERE (job_lvl = 100) OR (status = 'R')
  3. Create the AND condition by entering it once for each OR condition. Place each entry in the same grid column as the OR condition it corresponds to. For example, to add an AND condition that searches the hire_date column and applies to both OR conditions, enter values as shown here:

    Entering the values shown in the grid above produces the following WHERE clause in the statement in the SQL pane:

    WHERE (job_lvl = 100) AND
  (hire_date < '01/01/90' ) OR
  (status = 'R') AND
  (hire_date < '01/01/91' )

    Tip You can repeat an AND condition by adding it once, and then using the Cut and Paste commands from the Edit menu to repeat it for other OR conditions.

The WHERE clause created by the Query Designer is equivalent to the following WHERE clause, which uses parentheses to specify the precedence of OR over AND:

WHERE (job_lvl = 100 OR status = 'R') AND
   (hire_date < '01/01/91')

Note If you enter the search conditions in the format shown immediately above in the SQL pane, but then make a change to the query in the Diagram or Grid panes, the Query Designer recreates the SQL statement to match the form with the AND condition explicitly distributed to both OR conditions.


Creating Subqueries

You can use the results of one query as the input for another. Typically, you use the results of a subquery as a search condition that uses the IN( ) function or EXISTS operator. However, you can also use a subquery as the FROM clause to specify a result set to be used as an input source.

You can create a subquery by entering it in either the Grid pane or SQL pane.

To define an EXISTS subquery in the Grid pane

  1. Create the primary query.

  2. In the Column column for the first empty row in the Grid pane, enter EXISTS followed by the subquery in parentheses.

  3. In the Criteria column for the row containing the subquery, enter TRUE, FALSE, =TRUE, or =FALSE. Entering FALSE or =FALSE results in a NOT EXISTS query.

Note To create a NOT EXISTS query, create an EXISTS query as listed in the above steps, and set the Criteria column to FALSE. If you enter NOT EXISTS in the Grid pane, the Query Designer will display an error.

If you enter a subquery in the SQL pane, you will probably find it easier to use Cut and Paste commands to create the query.

To define a subquery in the SQL pane

  1. Create the primary query.

  2. In the SQL pane, select the SQL statement, and then use the Copy command to move the query to the Clipboard.

  3. Start the new query, and then use the Paste command to move the first query into the new query’s WHERE or FROM clause.

For example, imagine you have two tables, products and suppliers, and you want to create a query showing all products for suppliers in Sweden. Create the first query on the suppliers table to find all Swedish suppliers:

SELECT supplier_id
FROM supplier
WHERE (country = 'Sweden')

Use the Copy command to move this query to the Clipboard. Create the second query using the products table, listing the information you need about products:

SELECT product_id, supplier_id, product_name
FROM products

In the SQL pane, add a WHERE clause to the second query, then paste the first query from the Clipboard. Place parentheses around the first query, so that the end result looks like this:

SELECT product_id, supplier_id, product_name
FROM products
WHERE supplier_id IN
   (SELECT supplier_id
  FROM supplier
  WHERE (country = 'Sweden'))

Note When you add a subquery to the WHERE clause, the subquery appears in the Criteria column of the Grid pane. You can edit it further in either the Grid pane or SQL pane. However, the input sources, columns, and expressions referenced in the subquery are not displayed in the Diagram or Grid pane.


Using Expressions in Queries

You can use an expression anywhere in a query that you can use a column name. Expressions can calculate values to display, be part of search conditions, or combine the contents of data columns. An expression can consist of a mathematical calculation or a string, and can involve any combination of column names, literals, operators, or functions.

Examples of the use of expressions in a query include:

  • In a products table, displaying a discounted price that is calculated by taking 10% off the retail price.

  • Displaying only the first three digits — the area code — of a phone number.

  • Displaying employee names in the format last_name, first_name.

  • Joining two tables, an orders table and a products table, then sorting the query on the total price (order quantity times product price).

  • In an orders table, copying and then deleting all orders that were shipped more than one year ago.

For more information about creating and using expressions, refer to the topics listed in the following table.

For information about | See
How to create expressions | Creating an Expression
How to enter expressions into a query | Using Expressions in a Query
Creating summaries of data | Summarizing and Grouping
Operators you can use in expressions | Operators for Expressions
Functions you can use in expressions | Functions for Expressions
Predefined variables you can use in expressions | Predefined Variables for Expressions


Creating an Expression

An expression consists of any combination of column names, literals, operators, or functions. Follow these guidelines in combining elements to form expressions:

  • Reference columns by typing their names. If your query uses more than one table and if you use a column name that is not unique, you must add the table name and a period to the column name. The following example shows the column name job_id qualified with the table name employee:
    employee.job_id
  • Include literal text by enclosing it in single quotation marks; no quotation marks are necessary for numbers.

    Note In some databases, terms in single quotation marks are interpreted as literal values whereas terms in double quotation marks are interpreted as database objects such as column or table references. Therefore, the Query Designer can accept terms in double quotation marks, but might interpret them differently than you expect. In SQL Server, the Query Designer always interprets double quotation marks as database object delimiters. For details, see Query Designer Considerations for SQL Server Databases.

  • Use standard arithmetic operators for numbers and a concatenation operator for combining strings. For details, see Operators for Expressions.

  • Include parentheses to establish precedence of operators.

  • If you include a function, use these same guidelines for the arguments passed to the function. That is, reference columns by typing their names, enclose literal text in single quotation marks, and so on. For a list of functions you can use in expressions, see Functions for Expressions.

  • If you pass column names as function arguments, be sure the data type of the column is appropriate for the function argument.

The following table illustrates the use of expressions in a query.

Expression1 Result
SELECT (price * .9)
FROM products 		Displays a discounted price (10% off the value in the price column).
SELECT (lname + ', ' + fname)
FROM employee 		Displays the concatenated values of the last name and first name columns with a comma between them.
SELECT sales.qty, titles.price

FROM sales INNER JOIN titles ON
sales.title_id = titles.title_id
ORDER BY
(sales.qty * titles.price)

 After joining two tables, sorts the result set by the total value of an order (quantity times price).
SELECT au_lname, au_fname
FROM authors
WHERE
(SUBSTRING(phone, 1, 3) = '415') 		Displays authors whose area code is in the San Francisco area.
SELECT ord_num, ord_date
FROM sales
WHERE
(ord_date >=
  DATEADD(day, -10, GETDATE())) 		Finds all orders in the sales table that were made in the last 10 days. Today’s date is returned by the GETDATE( ) function.

1Some of the operators and functions shown here are specific to one database. For details about what operators and functions you can use, refer to the documentation for your database.


Using Expressions in a Query

To use an expression in a query, you can type it directly into the Grid pane or you can enter it in the SQL pane as part of the statement. Entering expressions is similar to entering column names. For details about how to create an expression, see Creating an Expression.

Tip To make it easier to see long expressions on your screen, you can resize the columns in the Grid pane. For details, see Grid Pane.

In this topic you can read about:

  • Displaying Expressions in the Result Set

  • Sorting Using Expressions

  • Searching Using Expressions

Displaying Expressions in the Result Set

You can display an expression in the result set by specifying the expression in place of a column in the Grid pane.

To display an expression in the result set

  1. In the Grid pane, insert a new grid row.

  2. In the Column column of the new grid row, type the expression you want to display.

When you display an expression in the result set, the database assigns a column heading to it using the format "Exprn," where n is the number of the expression in the current query. To assign a more meaningful column heading, you can create an alias for the expression. For details, see Creating Column Aliases.

Sorting Using Expressions

In some databases you can sort by the results of an expression. As with columns, you specify the sort type and sort order.

Note Not all databases allow you to sort using an expression. For details, refer to the documentation for your database.

To sort using an expression

  1. In the Grid pane, insert a new grid row.

  2. In the Column column of the new grid row, type the expression you want to sort by.

  3. If you do not want to display the expression in the query, clear the check box in the Output column of the new row.

  4. In the Sort column, choose Ascending or Descending, and then in the Sort Order column, choose the sort priority for the expression.

Searching Using Expressions

There are two ways to use an expression for searching. The expression can be the condition against which you compare values, or it can function as the value you are comparing.

The following example illustrates how you can use an expression as the condition in a WHERE clause:

SELECT ord_num, ord_date
FROM sales
WHERE (price * .9) > 20

In contrast, the following example illustrates the opposite use of an expression, in which the expression is the value you are comparing:

SELECT ord_num, ord_date
FROM sales
WHERE (ord_date >= DATEADD(day, -10, GETDATE() ) )

The way you specify an expression for searching depends on whether it appears as a condition or as a value to search.

To use an expression as a condition

  1. In the Grid pane, insert a new grid row.

  2. In the Column column of the new grid row, type the expression you want to use as the condition.

  3. In the Criteria column for the new row, type the value to compare against the condition.

To use an expression as a search value

  1. If it is not already in the Grid pane, add the data column or expression you want to search.

  2. In the Criteria column for that data column or expression, enter the expression to use as a search value.


Operators for Expressions

You can use a variety of operators in constructing expressions for your query, including mathematical and text operators.

Mathematical Operators

The following table lists the mathematical operators you can use in constructing an expression.

Operator | Meaning
+, - | Unary positive, negative
+ | Addition
- | Subtraction
* | Multiplication
/ | Division

Note Some databases make additional operators available, such as the "%" operator for modulus. For details about operators available in SQL Server, see Query Designer Considerations for SQL Server Databases. For other databases, refer to the documentation for your database.

If you use more than one mathematical operator in an expression, the Query Designer processes the expression according to the following operator precedence. To override the default precedence, use parentheses around the portion of the expression that is to be evaluated first. If more than one operator of the same level is included, the operators are evaluated left to right.

  1. Unary + and -

  2. * and /

  3. + and -

Text Operator

You can perform one operation on text: concatenation or the linking together of strings. In some databases, you can concatenate strings and perform other operations (such as removing extraneous spaces) using a single operator.

To concatenate a string, you can use the "+" operator in the Grid pane. If your database supports a different concatenation operator, the Query Designer might convert the "+" operator to the appropriate operator in the SQL pane. If you are entering expressions directly into the SQL pane, use the concatenation operator supported by your database. For details, refer to the documentation for your database.

Note Oracle uses the || operator. For details, see Query Designer Considerations for Oracle Databases.

You can also use the ODBC CONCAT function, which is supported by ODBC-compliant drivers. For example, the following expression illustrates how you can use the CONCAT function to combine authors’ last name and first name with a comma between them:

{ fn CONCAT(au_lname,{ fn CONCAT (', ', au_fname)})}

For more details about functions you can use, see Functions for Expressions.


Functions for Expressions

You can call a number of functions when you are building an expression, including:

  • String (character) functions

  • Date functions

  • Mathematical functions

  • System functions

  • Other functions, such as those to convert data from one type to another

In general, if you are familiar with the functions available in your database, you can use the function names and syntax supported by that database. In some cases, such as when you are creating views, stored procedures, or triggers, you must use database-specific function names and syntax.

If you are creating queries (not views, stored procedures, or triggers) that might be run against different databases, you can also use ODBC functions, which are supported by virtually all database drivers no matter what database you are querying. ODBC syntax includes the "fn" qualifier in front of the function name and braces around the entire function. For example, the following expression uses an ODBC function to convert text to lowercase letters:

{fn LCASE ( address ) }

The Query Designer can help you work with functions by:

  • Correctly inserting quotation marks in function arguments

  • Validating the data types of arguments

  • Validating the data types of return values

For details about functions supported by the database, refer to the documentation for the database. For details about ODBC functions, refer to the Open Database Connectivity (ODBC) SDK in the Microsoft Developer Network or to the Microsoft ODBC 2.0 Programmer’s Reference and SDK Guide.

Note You can use a special set of functions, the aggregate functions such as SUM( ) and AVG( ), to create queries that summarize data. For details, see Summarizing and Grouping.

String Functions

The following functions for manipulating character strings provide a sampling of those that are available in ODBC and in many databases, such as Microsoft SQL Server.

Function Description Example
LCASE( )1,
LOWER( ) 		Converts strings to lowercase
SELECT UPPER(substring(lname, 1, 1)) +
  LOWER(substring (lname, 2, 99))
FROM employee

Displays a last name after the first character is converted to uppercase and the remaining characters to lowercase.
LTRIM( ) Removes leading spaces from a string
SELECT stor_name, LTRIM(stor_address)
FROM stores

Displays an address column after extraneous spaces are removed from the front.

SUBSTRING( )
Extracts one or more characters from a string

SELECT SUBSTRING(phone,1,3)
FROM employee

Displays the first three characters (the area code) of a phone number.

UCASE( )1,

UPPER( )
Converts strings to uppercase

SELECT * FROM employee
WHERE UPPER(lname) = 'SMITH'

Converts the contents of the lname column to uppercase before comparing them to a specific value (avoids mismatches if the search is case sensitive). For details about case sensitivity in SQL Server, see Query Designer Considerations .

1If calling as an ODBC function, use syntax such as: { fn LCASE(text) }.

Date Functions

The following functions (or others similar to them) are available in either ODBC or in databases such as Microsoft SQL Server and Microsoft Access.

Note   Oracle uses the TO_DATE function to format dates. For details, see Query Designer Considerations for Oracle Databases.

Function
Description
Example

DATEDIFF( )
Calculates an interval between two dates.

SELECT fname, lname, hire_date
FROM employee
WHERE DATEDIFF(year, hire_date, getdate()) > 5

Locates all employees hired more than five years ago.

DATEPART( )
Returns the specified portion of a date or datetime column, including the day, month, or year.

SELECT DATEPART(year, hire_date)
FROM employee

Displays only the year in which an employee was hired (not the full date).

CURDATE( )1,

GETDATE( ) or DATE( )
Returns the current date in datetime format. This function is useful as input for many other date functions, such as calculating an interval forward or backward from today.

SELECT order_id
FROM orders
WHERE order_date = GETDATE()
Displays orders placed today.

1If calling as an ODBC function, use syntax such as: { fn CURDATE() }.

Mathematical Functions

ODBC and most databases provide some mathematical functions that you can use when performing calculations. The following functions are typical of those available in many databases, but you should refer to the ODBC documentation and documentation for the database for details about what functions are available and what arguments they take.

Note   You can use the aggregate functions AVG( ), COUNT( ), MAX( ), MIN( ), and SUM( ) to create averages and totals in your report. For details, see Summarizing and Grouping.

Function
Description
Example

ROUND( )
Rounds a number off to the specified number of decimal places.

SELECT ROUND(qty * (price * discount), 2)
FROM sales

Displays a total price based on a discount, then rounds the results off to two decimal places.

FLOOR( )
Rounds a number down to the nearest (smallest) whole number.

UPDATE titles
SET price = FLOOR(price)

Rounds all prices in the titles table down to the nearest whole number.

CEILING( )
Rounds a number up to the nearest whole number.

INSERT INTO archivetitle
SELECT title, CEILING(price)
FROM titles

Copies the title and the price (rounded up to the nearest integer) from the titles table to the archivetitle table.

System Functions

ODBC and most databases make available special functions that you can use to return information about the current database, current user, or the server. The following functions are typical of those available in many databases, but refer to the ODBC documentation or documentation for the database for details about what functions are available and what arguments they take.

Function
Description
Example

DATALENGTH( )
Returns the number of bytes used by the specified expression.

SELECT DATALENGTH(au_lname + ', '
  + au_fname)
FROM authors

Lists the number of bytes required for the combination of last and first names.

USER( )1,

USER_NAME( )
Returns the current user name.

SELECT company_name, city, phone
FROM customers
WHERE salesperson = USER_NAME()

Creates a list of customers for the salesperson who runs the query.

1If calling as  an ODBC function, use syntax such as: { fn USER() }.

Other Functions

In addition to the functions listed earlier, ODBC and most databases provide other functions to help you create queries, such as data type conversion or other utility functions. The following functions illustrate the type of utility functions that are available in many databases.

Function
Description
Example

CONVERT( )
Converts data from one data type into another. Useful to format data or to use the contents of a data column as an argument in a function that requires a different data type.

SELECT 'Hired: ' + CONVERT(char (11),
  hire_date)
FROM employee

Displays a date with a caption in front of it; the CONVERT( ) function creates a string out of the date so that it can be concatenated with a literal string.

SOUNDEX( )
Returns the Soundex code for the specified expression, which you can use to create "sounds like" searches.

SELECT au_lname, au_fname
FROM authors
WHERE SOUNDEX(au_fname) = 'M240'

Searches for names that sound like "Michael".

STR( )
Converts numeric data into a character string so you can manipulate it with text operators.

SELECT str(job_id) + ' ' +
   str(job_lvl)
FROM employee

Displays the job_id and job_lvl columns (both numeric) in a single string.


Predefined Variables for Expressions

In addition to using column names, literals, operators, and functions in an expression, you can use predefined variables that have defined meanings or values. For example, you can use a predefined variable to display the user name for the current user or to search for data columns that contain no value (null).

The predefined variables you can use depend on the database you are querying. Refer to the documentation for the database for details about what predefined variables are available.

Note In some instances, a predefined variable might be available as a function. For example, one database might use the predefined variable CURRENT_USER, while another database might make the same information available as the function USER_NAME( ). Refer to the database documentation for details.

The list below includes examples of predefined variables that are available in some databases, such as Microsoft® SQL Server™.

Note For more details about keywords avaiable in SQL Server, see Query Designer Considerations for SQL Server Databases. For details about predefined variables in Oracle (referred to as pseudo-columns, see Query Designer Considerations for Oracle Databases.

Predefined Variable Description Example
CURRENT_USER The user name of the current user
UPDATE accounts
SET salesperson = CURRENT_USER
WHERE region = 'NW'

Changes the salesperson column for all accounts in the northwest region to the name of the current user.
NULL A null value, used in the search expressions
IS NULL and
IS NOT NULL1
SELECT emp_id, lname, fname, minit
FROM employee
WHERE minit IS NULL

Finds authors who have no middle initial.

1The keyword IS is a special operator for use with NULL.


Querying on Groups of Rows

In addition to creating result sets comprised of individual rows, you can create a result set that includes summary information out of information in groups of rows.

To | See
Learn about creating aggregate queries to summarize and group data. | Summarizing and Grouping
Learn about logical principles for creating aggregate queries. | Summary and Grouping Behavior in the Query Designer
Create an average, sum, or other summary from information in all rows in a table. | Summarizing Values for All Rows in a Table
Count the number of rows that meet specific conditions. | Counting Rows in a Table
Create subsets of summary information by organizing data into groups. | Grouping Rows in Query Results
Create search conditions that apply to groups of rows. | Specifying Conditions for Groups
Use search conditions on both individual rows and on groups of rows. | Using HAVING and WHERE Clauses in the Same Query
Use calculations to create summary information. | Summarizing Values Using Custom Expressions


Summarizing and Grouping

In addition to creating queries that display individual data rows, you can create aggregate queries—queries that summarize information from multiple rows. For example, you can create a query that averages the contents of a price column. You can create the average for all rows in a table, or for groups of related rows — for example, all the rows that apply to a particular customer.

In this topic you can find information about summarizing and grouping information using queries.

  • Summary Queries

  • Summarizing Data

  • Grouping Rows

Summary Queries

Using summary queries, you can:

  • Create totals or averages of the data in numeric columns. For example, in an orders table, you can find the total of the order_total column to discover the sales total for a day.

  • Count the number of rows that meet specific criteria. For example, in a customers table, you can find out how many customers are in the state of California.

  • Find the minimum or maximum value in a specific column. For example, in an invoices table, you can find the highest sale made this month.

You can create summary queries on a table as a whole, or you can summarize subsets of a table by subdividing the table into groups.

Summarizing Data

To summarize all the data in a table, you create an aggregate query that involves a function such as SUM( ) or AVG( ). When you run the query, the result set contains a single row with the summary information. For example, you can calculate the total price of all books in the titles table by creating a query that sums the contents of the price column. The resulting query output might look like this:

The corresponding SQL statement might look like this:

SELECT SUM(price) total_price
FROM titles

You can use the following aggregate functions:

Aggregate function | Description
AVG(expr) | Average of the values in a column. The column can contain only numeric data.
COUNT(expr), COUNT(*) | A count of the values in a column (if you specify a column name as expr) or of all rows in a table or group (if you specify *). COUNT(expr) ignores null values, but COUNT(*) includes them in the count.
MAX(expr) | Highest value in a column (last value alphabetically for text data types). Ignores null values.
MIN(expr) | Lowest value in a column (first value alphabetically for text data types). Ignores null values.
SUM(expr) | Total of values in a column. The column can contain only numeric data.

Note Oracle supports additional aggregate functions. For details, see Query Designer Considerations for Oracle Databases.

When you use an aggregate function, by default the summary information includes all specified rows. In some instances, a result set includes non-unique rows. You can filter out non-unique rows by using the DISTINCT option of an aggregate function.

You can combine aggregate functions with other expressions to calculate other summary values. For details, see Summarizing Values Using Custom Expressions.

Grouping Rows

To create summary values for groups of rows, you create a query containing a GROUP BY clause. All the rows that contain the same group value are summarized into one row of the result set. The result set contains as many rows as there are unique values in the column you choose to group. If you group by multiple columns, the result set contains unique values for each combination of grouping columns you specify.

For example, you can query a titles table to find out the average price of a book for each publisher. To do so, you group the pub_id column so that all the rows for a specific publisher are summarized. The result set might look like this:

The corresponding SQL statement might look like this:

SELECT pub_id, AVG(price) AveragePrice
FROM titles
GROUP BY pub_id


Summary and Grouping Behavior in the Query Designer

When you create aggregate queries, certain logical principles apply. For example, you cannot display the contents of individual rows in a summary query. The Query Designer helps you comply with these principles in the way the Diagram and Grid panes behave.

By understanding the principles of aggregate queries and the Query Designer’s behavior, you can create logically correct aggregate queries. The overriding principle is that aggregate queries can result only in summary information. Thus, most of the principles that follow describe the ways that you can reference individual data columns within an aggregate query.

  • Referencing Columns for Output and Sorting

  • Referencing Columns in Search Conditions

  • Working with Columns in Aggregate Queries

Referencing Columns for Output and Sorting

The following principles describe how you can reference columns in an aggregate query for output and for sorting:

  • If you include an aggregate function anywhere in a query, the query is considered an aggregate query. (This principle does not necessarily apply to subqueries, which can include non-aggregate information.)

  • You cannot display the contents of individual rows in an aggregate query; you can display only summary data. As a consequence, all columns marked for output must also be assigned to either an aggregate function or to the GROUP BY clause.

  • Columns used in aggregate functions cannot appear in the GROUP BY clause.

Referencing Columns in Search Conditions

The following principles describe how you can reference columns in an aggregate query in search conditions. In general, you can use a column in a search condition to filter the rows that should be summarized (a WHERE clause) or to determine which grouped results appear in the final output (a HAVING clause).

  • Individual data columns can appear in either the WHERE or HAVING clause, depending on how they are used elsewhere in the query.

  • WHERE clauses are used to select a subset of rows for summarizing and grouping and are thus applied before any grouping is done. Therefore, you can use a data column in a WHERE clause even if it is not part of the GROUP BY clause or contained in an aggregate function. For example, the following statement selects all titles that cost more than $10.00 and averages the price:
    SELECT AVG(price)
FROM titles
WHERE price > 10
  • If you create a search condition that involves a column also used in a GROUP BY clause or aggregate function, the search condition can appear as either a WHERE clause or a HAVING clause — you can decide which when you create the condition. For example, the following statement creates an average price for the titles for each publisher, then displays the average for the publishers in which the average price is greater than $10.00:
    SELECT pub_id, AVG(price)
FROM titles
GROUP BY pub_id
HAVING (AVG(price) > 10)
  • If you use an aggregate function in a search condition, the condition involves a summary and must therefore be part of the HAVING clause.

Working with Columns in Aggregate Queries

When you create aggregate queries using the Diagram and Grid panes, the Query Designer makes certain assumptions so that your query adheres to the principles outlined earlier. For example, if you are creating an aggregate query and mark a data column for output, the Query Designer automatically makes the column part of the GROUP BY clause so that you do not inadvertently attempt to display the contents of an individual row in a summary.

Even though the Query Designer works to help prevent logical errors, it is possible to create aggregate queries that will not execute. Therefore, be sure that you understand the principles listed earlier in order to avoid errors when you create queries.

The Query Designer uses the following guidelines for working with columns:

  • When you choose the Group By option or add an aggregate function to a query, all columns marked for output or used for sorting are automatically added to the GROUP BY clause. Columns are not automatically added to the GROUP BY clause if they are already part of an aggregate function.

    If you don’t want a particular column to be part of the GROUP BY clause, you must manually change it by selecting a different option in the Group By column of the Grid pane. (However, the Query Designer will not prevent you from choosing an option that can result in a query that will not run.)

  • If you manually add a query output column to an aggregate function in either the Grid or SQL pane, the Query Designer does not automatically remove other output columns from the query. Therefore, you must remove the remaining columns from the query output or make them part of the GROUP BY clause or of an aggregate function.

When you enter a search condition into the Criteria column of the Grid pane, the Query Designer follows these rules:

  1. If the Group By column of the grid is not displayed (because you have not yet specified an aggregate query), the search condition is placed into the WHERE clause.

  2. If you are already in an aggregate query and have selected the option Where in the Group By column, the search condition is placed into the WHERE clause.

  3. If the Group By column contains any value other than Where, the search condition is placed in the HAVING clause.


Summarizing Values for All Rows in a Table

Using an aggregate function, you can create a summary for all the values in a table. For example, you can create a query such as the following to display the total price for all books in the titles table:

SELECT SUM(price)
FROM titles

You can create multiple summaries in the same query by using aggregate functions with more than one column. For example, you can create a query that calculates the total of the price column and the average of the discount column.

You can also summarize the same column in different ways (such as totaling, counting, and averaging) in the same query. For example, the following query averages and summarizes the price column from the titles table:

SELECT AVG(price), SUM(price)
FROM titles

If you add a search condition, you can summarize the subset of rows that meet that condition.

Note You can also count all the rows in the table or the ones that meet a specific condition. For details, see Counting Rows in a Table.

When you create a single summary value for all rows in a table, you display only the summaries themselves. For example, if you are totaling the value of the price column of the titles table, you would not also display individual titles, publisher names, and so on.

Note If you are subtotaling — that is, creating groups — you can display column values for each group. For details, see Grouping Rows in Query Results.

To summarize values for all rows

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column you want to summarize to the Grid pane. Be sure that the column is marked for output.

    The Query Designer automatically assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

  4. In the Group By grid column, select the aggregate function that you want to use to summarize the data: Sum, Avg, Min, Max, Count. If you want to summarize only unique rows in the result set, choose an aggregate function with the DISTINCT options, such as Min Distinct. Do not choose Group By, Expression, or Where, because those options do not apply when you are summarizing all rows.

    Note Oracle supports additional aggregate functions. For details, see Query Designer Considerations for Oracle Databases.

    The Query Designer replaces the column name in the statement in the SQL pane with the aggregate function that you specify. For example, the SQL statement might look like this:

    SELECT SUM(price)
FROM titles
  5. If you want to create more than one summary in the query, repeat steps 3 and 4.

    When you add another column to the query output list or order by list, the Query Designer automatically fills the term Group By into the Group By column of the grid. Select the appropriate aggregate function.

  6. Add search conditions, if any, to specify the subset of rows you want to summarize.

When you execute the query, the Results pane displays the summaries that you specified.

Note The Query Designer maintains aggregate functions as part of the SQL statement in the SQL pane until you explicitly turn off Group By mode. Therefore, if you modify your query by changing input sources or changing its type, the resulting query might include invalid aggregate functions.


Counting Rows in a Table

You can count rows in a table to determine:

  • The total number of rows in a table, for example, a count of all the books in a titles table.

  • The number of rows in a table that meet a specific condition, for example, the number of books by one publisher in a titles table.

  • The number of values in a particular column.

When you count values in a column, nulls are not included in the count. For example, you might count the number of books in a titles table that have values in the advance column. By default, the count includes all values, not just unique values.

The procedures for all three types of counts are similar.

To count all the rows in a table

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

    Check * (All Columns) in the input source window for the table.

    The Query Designer automatically fills the term Count into the Group By column in the Grid pane and assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

To count all the rows that meet a condition

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Check * (All Columns) in the input source window for the table.

    The Query Designer automatically fills the term Count into the Group By column in the Grid pane and assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

  4. Add the data column that you want to search, and then clear the check box in the Output column.

    The Query Designer automatically fills the term Group By into the Group By column of the grid.

  5. Change Group By in the Group By column to Where.

  6. In the Criteria column for the data column to search, enter the search condition.

To count the values in a column

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column that you want to count to the Grid pane.

    The Query Designer automatically fills the term Group By into the Group By column of the grid.

  4. Change Group By in the Group By column to Count.

To count only unique values, choose Count Distinct.


Grouping Rows in Query Results

If you want to create subtotals or show other summary information for subsets of a table, you create groups using an aggregate query. Each group summarizes the data for all the rows in the table that have the same value.

For example, you might want to see the average price of a book in the titles table, but break the results down by publisher. To do so, you group the query by publisher (for example, pub_id). The resulting query output might look like this:

When you group data, you can display only summary or grouped data, such as:

  • The values of the grouped columns (those that appear in the GROUP BY clause). In the example above, pub_id is the grouped column.

  • Values produced by aggregate functions such as SUM( ) and AVG( ). In the example above, the second column is produced by using the AVG( ) function with the price column.

You cannot display the contents of individual columns. For example, if you group only by publisher, you cannot also display individual titles in the query. Therefore, if you add columns to the query output, the Query Designer automatically adds them to the GROUP BY clause of the statement in the SQL pane. If you want a column to be summarized instead, you can specify an aggregate function for that column.

If you group by more than one column, each group in the query shows the summary values for all grouping columns.

For example, the following query against the titles table groups by publisher (pub_id) and also by book type (type). The query results are ordered by publisher and show summary information for each different type of book that the publisher produces:

SELECT pub_id, type, SUM(price) Total_price
FROM titles
GROUP BY pub_id, type

The resulting output might look like this:

To group rows

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column you want to group to the Grid pane. If you want the column to appear in the query output, be sure that the column is marked for output.

    The Query Designer adds a GROUP BY clause to the statement in the SQL pane. For example, the SQL statement might look like this:

    SELECT pub_id
FROM titles
GROUP BY pub_id
  4. Add the column you want to summarize to the Grid pane. Be sure that the column is marked for output.

  5. In the Group By grid column for the summary data column, select the aggregate function that you want to use to summarize the data.

    The Query Designer automatically assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

    The corresponding statement in the SQL pane might look like this:

    SELECT   pub_id, SUM(price) AS Expr1
FROM     titles
GROUP BY pub_id


Specifying Conditions for Groups

You can limit the groups that appear in a query by specifying a condition that applies to groups as a whole — a HAVING clause. After the data has been grouped and summarized, the conditions in the HAVING clause are applied. Only the groups that meet the conditions appear in the query.

For example, you might want to see the average price of all books for each publisher in a titles table, but only if the average price exceeds $10.00. In that case, you could specify a HAVING clause with a condition such as AVG(price) > 10.

Note In some instances, you might want to exclude individual rows from groups before applying a condition to groups as a whole. For details, see Using HAVING and WHERE Clauses in the Same Query.

You can create complex conditions for a HAVING clause using AND and OR to link conditions. For details about using AND and OR in search conditions, see Specifying Multiple Search Conditions for One Column.

To specify a condition for a group

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. If it is not already in the Grid pane, add the column on which you want to base the condition. (Most often the condition involves a column that is already a group or summary column.) You cannot use a column that is not part of an aggregate function or of the GROUP BY clause.

  3. In the Criteria column, specify the condition to apply to the group.

    The Query Designer automatically creates a HAVING clause in the statement in the SQL pane, such as in the following example:

    SELECT pub_id, AVG(price)
FROM titles
GROUP BY pub_id
HAVING (AVG(price) > 10)
  4. Repeat steps 2 and 3 for each additional condition you want to specify.


Using HAVING and WHERE Clauses in the Same Query

In some instances, you might want to exclude individual rows from groups (using a WHERE clause) before applying a condition to groups as a whole (using a HAVING clause).

A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the rows in the result set representing groups), whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause. In that case:

  • The WHERE clause is applied first to the individual rows in the input sources. Only the rows that meet the conditions in the WHERE clause are grouped.

  • The HAVING clause is then applied to the rows in the result set that are produced by grouping. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function.

For example, imagine that you are joining the titles and publishers tables to create a query showing the average book price for a set of publishers. You want to see the average price for only a specific set of publishers — perhaps only the publishers in the state of California. And even then, you want to see the average price only if it is over $10.00.

You can establish the first condition by including a WHERE clause, which discards any publishers that are not in California, before calculating average prices. The second condition requires a HAVING clause, because the condition is based on the results of grouping and summarizing the data. The resulting SQL statement might look like this:

SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id
HAVING AVG(price) > 10

You can create both HAVING and WHERE clauses in the Grid pane of the Query Designer. By default, if you specify a search condition for a column, the condition becomes part of the HAVING clause. However, you can change the condition to be a WHERE clause.

You can create a WHERE clause and HAVING clause involving the same column. To do so, you must add the column twice to the Grid pane, then specify one instance as part of the HAVING clause and the other instance as part of the WHERE clause.

To specify a WHERE condition in an aggregate query

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. If it is not already in the Grid pane, add the column on which you want to base the WHERE condition.

  3. Clear the check box in the Output column unless the data column is part of the GROUP BY clause or included in an aggregate function.

  4. In the Criteria column, specify the WHERE condition. The Query Designer adds the condition to the HAVING clause of the SQL statement.

    Note The query shown in the illustrations for this procedure joins two tables, titles and publishers.

    At this point in the query, the SQL statement contains a HAVING clause:

    SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
GROUP BY titles.pub_id
HAVING publishers.state = 'CA'
  5. In the Group By column, select Where from the list of group and summary options. The Query Designer removes the condition from the HAVING clause in the SQL statement and adds it to the WHERE clause.

    The SQL statement changes to include a WHERE clause instead:

    SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id


Summarizing Values Using Custom Expressions

In addition to using aggregate functions to summarize data, you can create custom expressions to produce summary values. You can use custom expressions in place of aggregate functions anywhere in an aggregate query.

For example, in the titles table you might want to create a query that shows not just the average price, but what the average price would be if it were discounted.

You cannot include an expression that is based on calculations involving only individual rows in the table; the expression must be based on an aggregate value, because only the summary values are available at the time the expression is calculated.

To specify a custom expression for a summary value

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. Move to a blank row of the Grid Pane, and then type the expression in the Columns column.

    The Query Designer automatically assigns a column alias to the expression to create a useful column heading in query output. For more details, see Creating Column Aliases.

  3. In the Group By column for the expression, select Expression.


Querying Using Multiple Tables

You can retrieve data from two or more tables in the same query by joining the tables. Joined tables have a relationship to one another based on data they have in common.

For example, in a publishers application, the publishers and the titles tables might each contain a publisher ID column. If so, you can create a query that joins the two tables and produces results that include the publisher name for each book, as shown in the following illustration:

Joining tables creates a result set consisting of a virtual table with rows that combine information from all joined tables. You can specify which columns appear in the result set by selecting particular columns from each of the joined tables. You can also include sort specifications and search conditions, just as you do for queries involving single tables.

To join tables, you specify a join condition. You can create join conditions based on any comparison operator. The most common join condition is to match values exactly — that is, the query matches a value in a column of the first table against values in a column of the other table exactly. (This is sometimes referred to as an "equijoin.") For example, in the earlier illustration, the join condition is that the pub_id column in both tables are equivalent.

You can join any number of tables. If you join more than two tables, two tables are joined, the resulting virtual joined table is joined with the next tables, and so on, until a single virtual joined table is obtained.

Typically, you join tables that are in the same database. However, depending on what database server you are using, you might be able to join tables from different databases.

To | See
Learn the different ways in which tables can be joined | Types of Joins
Learn how the Query Designer displays join information in the Diagram pane | How the Query Designer Represents Joins
Learn what rules the Query Designer uses to determine if tables should be joined | Joining Tables Automatically
Join tables yourself | Joining Tables Manually
Specify that tables should be joined using an operator other than equal (=) | Modifying Join Operators
Specify that joined tables should include rows even when they don't match rows in the corresponding table | Creating Outer Joins
Use a join to find subsets of data within a single table | Creating Self-Joins
Remove a join between tables | Removing Joins


Types of Joins

When you join tables, the type of join that you create determines the rows that appear in the result set. You can create the following types of joins:

  • Inner join A join that displays only the rows that have a match in both joined tables. (This is the default type of join in the Query Designer.) For example, you can join the titles and publishers tables to create a result set that shows the publisher name for each title. In an inner join, titles for which you do not have publisher information are not included in the result set, nor are publishers with no titles.

    Note Columns containing NULL do not match any values when you are creating an inner join and are therefore excluded from the result set. Null values do not match other null values.

  • Outer join A join that includes rows even if they do not have related rows in the joined table. You can create three variations of an outer join to specify the unmatched rows to be included:
    • Left outer join All rows from the first-named table (the "left" table, which appears leftmost in the JOIN clause) are included. Unmatched rows in the right table do not appear. For example, the following SQL statement illustrates a left outer join between the titles and publishers tables to include all titles, even those you don’t have publisher information for:
      SELECT titles.title_id, titles.title,
   publishers.pub_name
FROM titles LEFT OUTER JOIN publishers ON
   titles.pub_id = publishers.pub_id
    • Right outer join All rows in the second-named table (the "right" table, which appears rightmost in the JOIN clause) are included. Unmatched rows in the left table are not included. For example, a right outer join between the titles and publishers tables will include all publishers, even those who have no titles in the titles table.

    • Full outer join All rows in all joined tables are included, whether they are matched or not. For example, a full outer join between titles and publishers shows all titles and all publishers, even those that have no match in the other table.

      Note Some databases, such as Oracle, do not support full outer joins. For details, see Query Designer Considerations for Oracle Databases.

You can also create a self-join, which compares rows within the same table. For example, you can use a self-join to find all publishers that are in a specific city and have the same postal code. For details, see Creating Self-Joins.


How the Query Designer Represents Joins

If tables are joined, the Query Designer represents the join graphically in the Diagram pane and by using SQL syntax in the SQL pane.

Diagram Pane

In the Diagram pane the Query Designer displays a join line between the data columns involved in the join. The Query Designer displays one join line for each join condition. For example, the following illustration shows a join line between two tables that are joined:

If tables are joined using more than one join condition, the Query Designer displays multiple join lines, as in the following example:

If the joined data columns are not displayed (for example, the input source window is minimized or the join involves an expression), the Query Designer places the join line at the title bar of the input source window.

The shape of the icon in the middle of the join line indicates how the input sources are joined. If the join clause uses an operator other than equal (=), the operator appears in the join line icon. The following table lists the icons that appear in the join line.

Join line icon | Description
 | Inner join (created using an equal sign)
 | Inner join based on the "greater than" operator
 | Outer join in which all rows from the table represented on the left will be included, even if they do not have matches in the related table
 | Outer join in which all rows from the table represented on the right will be included, even if they do not have matches in the related table
 | Full outer join in which all rows from both tables will be included, even if they do not have matches in the related table. Note Some databases, such as Oracle, do not support full outer joins. For details, see Query Designer Considerations for Oracle Databases.

The symbols on the ends of the join line indicate the type of join. The following table lists the types of joins and the icons displayed on the ends of the join line.

Icon on ends of join line | Type of join
 | One-to-one join
 | One-to-many join
 | Query Designer cannot determine the join type. This situation occurs most often when you have created a join manually.

SQL Pane

A join can be expressed in a number of ways in an SQL statement. The exact syntax depends on the database you are using and on how you have defined the join.

Syntax option for joining tables include:

  • JOIN qualifier for the FROM clause. The keywords INNER and OUTER specify the join type. This syntax is standard for ANSI 92 SQL.

    For example, if you join the publishers and pub_info tables based on the pub_id column in each table, the resulting SQL statement might look like this:

    SELECT *
FROM publishers INNER JOIN pub_info ON
   publishers.pub_id = pub_info.pub_id

    If you create an outer join, the words LEFT OUTER or RIGHT OUTER appear in place of the word INNER.

  • WHERE clause compares columns in both tables. A WHERE clause appears if the database does not support the JOIN syntax (or if you entered it yourself). If the join is created in the WHERE clause, both table names appear in the FROM clause.

    For example, the following statement joins the publishers and pub_info tables.

    SELECT *
FROM publishers, pub_info
WHERE  publishers.pub_id = pub_info.pub_id

Note SQL Server databases support *= and =* syntax. For details, see Query Designer Considerations for SQL Server. Oracle databases support the { oj } syntax for outer joins. For details, see Query Designer Considerations for Oracle Databases.


Joining Tables Automatically

When you add two or more tables to a query, the Query Designer attempts to determine if they are related. If they are, the Query Designer automatically puts join lines between the input source windows for the tables.

The Query Designer will recognize tables as joined if:

  • The database contains information that specifies that the tables are related.

  • If two columns, one in each table, have the same name and data type. The column must be a primary key in at least one of the tables. For example, if you add employee and jobs tables, if the job_id column is the primary key in the jobs table, and if each table has a column called job_id with the same data type, the Query Designer will automatically join the tables.

    Note The Query Designer will create only one join based on columns with the same name and data type. If more than one join is possible, the Query Designer stops after creating a join based on the first set of matching columns that it finds.

  • The Query Designer detects that a search condition (a WHERE clause) is actually a join condition. For example, you might add the tables employee and jobs, then create a search condition that searches for the same value in the job_id column of both tables. When you do, the Query Designer detects that the search condition results in a join, and then creates a join condition based on the search condition.

If the Query Designer has created a join that is not suitable to your query, you can modify the join or remove it. For details, see Modifying Join Operators and Removing Joins.

If the Query Designer does not automatically join the tables in your query, you can create a join yourself. For details, see Joining Tables Manually.


Joining Tables Manually

When you add two (or more) tables to a query, the Query Designer attempts to join them based on common data or on information stored in the database about how tables are related. (For details, see Joining Tables Automatically.) However, if the Query Designer has not joined the tables automatically, or if you want to create additional join conditions between tables, you can join tables manually.

You can create joins based on comparisons between any two columns, not just columns that contain the same information. For example, if your database contains two tables, titles and roysched, you can compare values in the ytd_sales column of the titles table against the lorange and hirange columns in the roysched table. Creating this join would allow you to find titles for which the year-to-date sales falls between the low and high ranges for the royalty payments.

Tip Joins work fastest if the columns in the join condition have been indexed. In some cases, joining on unindexed columns can result in an extremely slow query. For information about creating indexes using the Visual Database Tools, see Indexes.

To manually join tables

  1. Add to the Diagram pane the tables you want to join.

  2. Drag the name of the join column in the first input source window and drop it onto the related column in the second input source window. You cannot base a join on memo or binary (BLOB) columns.

    Note The join columns must be of the same (or compatible) data types. For example, if the join column in the first table is a date, you must relate it to a date column in the second table. On the other hand, if the first join column is an integer, the related join column must also be of an integer data type, but it can be a different size. The Query Designer will not check the data types of the columns you use to create a join, but when you execute the query, the database will display an error if the data types are not compatible.

  3. If necessary, change the join operator; by default, the operator is an equal sign (=). For details, see Modifying Join Operators.

The Query Designer adds an INNER JOIN clause to the SQL statement in the SQL pane. You can change the type to an outer join. For details see Creating Outer Joins.


Modifying Join Operators

By default, the Query Designer joins tables using an equal sign (an equijoin), which matches values in the two join columns. If you want, you can change the operator used to compare values in the join columns.

To modify join operators

  1. In the Diagram pane, right-click the join line you want to modify, and then choose Properties from the shortcut menu.

  2. In the Join Line tab of the Property Pages dialog box, select a new operator from the list.

    –or–

    Change the operator in the SQL statement in the SQL pane.


Creating Outer Joins

By default, the Query Designer creates an inner join between tables. If you want to include data rows in the result set that do not have a match in the joined table, you can create an outer join.

When you create an outer join, the order in which tables appear in the SQL statement is significant. The first table you add becomes the "left" table and the second table becomes the "right" table. (The actual order in which the tables appear in the Diagram pane is not significant.) When you specify a left or right outer join, you are referring to the order in which the tables were added to the query and to the order in which they appear in the SQL statement in the SQL pane.

To create an outer join

  1. Create the join, either automatically or manually. For details, see Joining Tables Automatically or Joining Tables Manually.

  2. Select the join line in the Diagram pane, and then from either the Query menu or the right-click menu, choose Select All Rows from table, selecting the command that includes the table whose extra rows you want to include.

    –or–

    In the Diagram pane, right-click the join line you want to change to an outer join, and then choose Properties from the shortcut menu. Under Include rows in the Join Line tab of the Property Pages dialog box, choose the option specifying the table from which you want to include all rows.

    • Choose the first table to create a left outer join.

    • Choose the second table to create a right outer join.

    • Choose both tables to create a full outer join.

    Note Some databases, such as Oracle, do not support full outer joins. For details, see Query Designer Considerations for Oracle Databases.

    For example, the following illustration shows the options you would choose for a left outer join:

When you specify an outer join, the Query Designer modifies the join line to indicate an outer join. For example, the following figure shows a join line that represents an outer join in which rows are included from the employee table:

In addition, the Query Designer modifies the SQL statement in the SQL pane to reflect the change in join type, as shown in the following statement:

SELECT employee.job_id, employee.emp_id,
   employee.fname, employee.minit, jobs.job_desc
FROM employee LEFT OUTER JOIN jobs ON
    employee.job_id = jobs.job_id

Because an outer join includes unmatched rows, you can use it to find rows that violate foreign key constraints. To do so, you create an outer join and then add a search condition to find rows in which the primary key column of the rightmost table is null. For example, the following outer join finds rows in the employee table that do not have corresponding rows in the jobs table:

SELECT employee.emp_id, employee.job_id
FROM employee LEFT OUTER JOIN jobs
   ON employee.job_id = jobs.job_id
WHERE (jobs.job_id IS NULL)


Creating Self-Joins

You can join a table to itself — that is, create a self-join — if you want to find rows in a table that have values in common with other rows in the same table. For example, you can use a self-join to find pairs of authors who live in the same postal code.

As with any join, a self-join requires at least two tables. The difference is that, instead of adding a second table to the query, you add a second instance of the same table. That way, you can compare a column in the first instance of the table to the same column in the second instance, which allows you to compare the values in a column to each other. Each instance of the table must be unique, so the Query Designer assigns an alias to the second instance of the table.

For example, if you are creating a self-join to find all authors with the same postal code, you compare the zip column in the first instance of the table against the zip column in the second instance. The resulting join condition might look like the following:

FROM authors INNER JOIN authors authors1 ON
   authors.zip = authors1.zip

Creating a self-join often requires multiple join conditions. The primary join condition is the one on which the join is based. In the example of the authors’ postal code, the primary join condition is based on finding an exact match in the zip column.

However, if you join based on only this condition, each row in the table appears in the result set at least twice. Each row matches itself, resulting in a duplicate. In addition, the join results are reversed for rows that are identical except for the order of the join values.

To eliminate these duplicates, you can include a second join condition to filter out duplicated rows. The second join condition might, for example, compare the primary key (in this example, the au_id column) with a less than (<) operator. The resulting join condition might look like this:

FROM authors INNER JOIN authors authors1 ON
   authors.zip = authors1.zip AND
   authors.au_id < authors1.au_id

When you create a self-join, the Query Designer usually creates the second join condition automatically, because it is based on a primary key. You can then manually add the primary join condition.

To create a self-join

  1. Add to the Diagram pane the table you want to work with.

  2. Add the same table again, so that the Diagram pane shows the same table in two input source windows.

    The Query Designer assigns an alias to the second instance by adding a sequential number to the table name. In addition, the Query Designer creates a join line between the input source windows based on the primary key. In most cases, this join can function as the second join condition.

  3. Right-click the join line between the tables, choose Properties from the shortcut menu, and then change the comparison operator between the primary keys as required. For example, you might change the operator to less than (<).

  4. Create the primary join condition by dragging the name of the primary join column in the first input source window and dropping it on the corresponding column in the second input source window.

  5. Specify other options for the query such as output columns, search conditions, and sort order.


Removing Joins

If you don’t want tables to be joined, you can remove the join between them. For example, you might remove a join that the Query Designer has created automatically between two tables.

Note Removing a join between tables does not make a permanent change to their relationship. If join information for the tables is stored as part of a database, removing the join removes it only for the current query.

If two joined tables are part of your query and you remove all join conditions between them, the resulting query becomes the product of both tables — that is, the query displays all rows from the first table, each one joined to every row in the second table. Therefore, if you remove a join condition, be sure that you add a different join condition or another search condition or the result set can grow very large.

To remove a join

  • In the Diagram pane, select the join line for the join to remove, and then press the DELETE key. You can select and delete multiple join lines at one time.

The Query Designer removes the join line and the join condition in the statement in the SQL pane.


Creating Special Purpose Queries

In many instances, it is useful to create a query that you can reuse many times in your applications with different input each time. In this section you will find information about how to create parameter queries for these special purposes.

To | See
Create a query that you can use many times, but with a different value each time | Parameter Queries
Create a query using unnamed parameters | Creating a Query with Unnamed Parameters
Specify names for the parameters in your query to help distinguish multiple parameters | Creating a Query with Named Parameters
Mark a name as a parameter instead of a string of literal characters | Specifying Parameter Marker Characters


Parameter Queries

In some cases you want to create a query that you can use many times, but with a different value each time. For example, you might frequently query a titles table to find all the books written by one author. You could run the same query for each request, except that the author’s ID or name would be different each time.

To create a query that can have different values at different times, you use parameters in the query. A parameter is a placeholder for a value that is supplied when the query runs. An SQL statement with a parameter might look like the following, where "?" represents the parameter for the author’s state:

SELECT au_lname, au_fname
FROM state
WHERE state = ?

Where You Can Use Parameters

You can use parameters as placeholders for literal values — for either text or numeric values. Most commonly, parameters are used as placeholders in search conditions for individual rows or for groups (that is, in the WHERE or HAVING clauses of an SQL statement).

Some databases allow you to use parameters as placeholders in expressions. For example, you might want to calculate discounted prices by supplying a different discount value each time you run a query. To do so, you could specify the following expression:

(price * ?)

For details about where you can use parameters, refer to the documentation for the database you are using.

Specifying Unnamed and Named Parameters

You can specify two types of parameters: unnamed and named. An unnamed parameter is a question mark (?) that you put anywhere in the query that you want to prompt for or substitute a literal value. For example, if you use an unnamed parameter to search for an author’s id in a titles table, the resulting statement in the SQL pane might look like this:

SELECT au_lname, au_fname
FROM state
WHERE state = ?

When you run the query in the Query Designer, the Define Query Parameters dialog box appears with "?" as the name of the parameter, as in the following illustration.

Alternatively, you can assign a name to a parameter. Named parameters are particularly useful if you have multiple parameters in a query. For example, if you use named parameters to search for an author’s first and last names in a authors table, the resulting statement in the SQL pane might look like this:

SELECT au_id
FROM authors
WHERE au_fname = %first name% AND
  au_lname = %last name%

When you run the query in the Query Designer, the Define Query Parameters dialog box appears with a list of named parameters, as in the following illustration.


Creating a Query with Unnamed Parameters

You can create a query with an unnamed parameter by specifying a question mark (?) as a placeholder for a literal value. You can specify as many unnamed parameters in the query as you need.

Note If you are using multiple parameters, you can use named parameters to help you distinguish them. For details, see Creating a Query with Named Parameters.

When you run the query in the Query Designer, the Define Query Parameters dialog box is displayed with "?" as the name of the parameter.

To specify an unnamed parameter

  1. Add the columns or expressions that you want to search to the Grid pane. If you don’t want the search columns or expressions to appear in the query output, remove them as output columns.

  2. Locate the row containing the data column or expression to search, and then in the Criteria grid column, enter a question mark (?).

    By default, the Query Designer adds the "=" operator. However, you can edit the cell to substitute ">", "<", or any other SQL comparison operator.


Creating a Query with Named Parameters

You can specify names for the parameters in your query to help you distinguish multiple parameters. For example, if you create a parameter query that prompts for an author’s name, you can use the parameter names "first name" and "last name." When you run the query in the Query Designer, you are prompted for the parameter by name:

To mark the parameter name as a name and not a string of literal characters, you specify parameter marker characters and then place those characters around the parameter name. For details, see Specifying Parameter Marker Characters.

If you use both prefix-marker and suffix-marker characters, you can name your parameters using any combination of characters, including text, numbers, punctuation, and spaces. (However, do not use null or a question mark.) If you specify only a prefix-marker character, the parameter name cannot contain spaces.

Note The parameter name you specify is used as a variable in the environment from which you run the query. Be sure that the parameter names you use are acceptable in all environments in which you intend to use the query.

To specify a named parameter

  1. If you have not done so already, specify the parameter marker characters. For details, see Specifying Parameter Marker Characters.

  2. Add the columns or expressions that you want to search to the Grid pane. If you are creating a Select query and don’t want the search columns or expressions to appear in the query output, remove them as output columns.

  3. Locate the row containing the data column or expression to search, and then in the Criteria grid column, enter the name of the parameter. Be sure to mark the parameter using the appropriate characters:

    By default, the Query Designer adds the "=" operator. However, you can edit the cell to substitute ">", "<", or any other SQL comparison operator.


Specifying Parameter Marker Characters

To mark a name as a parameter and not as a string of literal characters, you place a prefix in front of the parameter name (and, as an option, a suffix after it). For example, parameter marker characters might be "@", ":", or "%". Typically, you use the parameter marker character recognized for your database. For details about what parameter marker characters you need, refer to the documentation for your database or environment.

Note If you are querying a SQL Server or Oracle database, the Query Designer will automatically fill in the correct parameter marker character as the default in the Parameters tab.

For example, in your query you might define a parameter called "last name." To indicate that "last name" is a parameter and not a string to search for in the lname column, you might specify that the parameter marker characters are "[" and "]". You can then enter "[last name]" as a search condition value, and the Query Designer will correctly interpret "last name" as a parameter.

In rare instances, the parameter marker character you define might also appear in the name of the parameter. If so, you can specify an escape character. For details, see Parameters Tab, Properties Window.

To specify parameter marker characters

  1. Right-click in any pane of the Query Designer, and then from the shortcut menu choose Properties.

  2. In the Property Pages dialog box, choose the Parameters tab.

  3. Enter the parameter prefix character or characters and, if you intend to use one, a suffix character. (You can specify a suffix character only if you have specified a prefix character.) If you need to specify one, enter an escape character.


Modifying Data in Tables

In addition to viewing the contents of tables, you can use the Query Designer to modify data in tables by editing the contents of columns, adding new rows, and deleting existing rows. Using the graphical features of the Query Designer, you can modify data in tables two ways:

  • Execute a Select query, then edit the data directly in the Results pane.

  • Create a query to update, delete, or copy data in tables.

Note If you are familiar with SQL, you can also execute any statement in the SQL pane, including those that update or delete data in tables. The features discussed in this section relate primarily to capabilities that are available by using the Diagram, Grid, and Results panes.

Editing directly in the Results pane is similar to editing in a form or spreadsheet. You can see the changes immediately, and if there is a problem (for example, you attempt to enter data that does not match the data type of a column), you are notified as soon as you try to move to another row. For details, see Editing Rows in the Results Pane.

On the other hand, even though it is not as simple, creating a query to update, delete, or copy data makes it easier to update many rows in one operation. For example, you can create one query that changes the status of all the employees who have worked at the company more than five years, or a set of two queries that first copy and then delete all orders more than two years old. For details, see Modifying Data Using Queries.


Determining When Query Results Can Be Updated

In many cases, you can update the result set displayed in the Results pane. However, in some cases you cannot.

In general, in order to update results, the Query Designer must have sufficient information to uniquely identify the row in the table. An example is if the query includes a primary key in the output list. In addition, you must have sufficient permission to update the database.

If your query is based on a view, you might be able to update it. The same guidelines apply, except that they apply to the underlying tables in the view, not just to the view itself.

Note The Query Designer cannot determine in advance whether you can update a result set based on a view. Therefore, it displays all views, even though you might not be able to update them.

The following table summarizes specific instances in which you might and might not be able to update a query in the Results pane. In many cases, the database you are using dictates whether you can update query results.

Query | Can be updated?
Query based on one table with primary key in the output list | Yes (except as listed below)
Query based on a table with no unique index and without a primary key | Depends on query and database. Some databases allow updates if sufficient information is available to uniquely identify records.
Query based on multiple tables which are not joined | No
Query based on data marked as read-only in the database | No
Query based on a view that involves one table with no constraints | Yes (except as listed below)
Query based on tables joined with a one-to-one relationship | Yes (except as listed below)
Query based on tables joined with a one-to-many relationship | Usually
Query based on three or more tables in which there is a many-to-many relationship | No
Query based on table for which update permission isn't granted | Can delete but not update
Query based on table for which delete permission isn't granted | Can update but not delete
Aggregate query | No
Query based on a subquery that contains totals or aggregate functions | No
Query that includes the DISTINCT keyword to exclude duplicate rows | No

In addition, you might not be able to update specific columns in the query results. The following list summarizes specific types of columns that you cannot update in the Results pane.

  • Columns based on expressions

  • Rows or columns deleted by another user

  • Rows or columns locked by another user (locked rows can usually be updated as soon as they are unlocked)

  • Timestamp or BLOB columns


Editing Rows in the Results Pane

In many cases, you can edit the data in the Results pane grid and save changes to the table or tables represented by the query. However, whether you can actually change, add, or delete rows depends on the type of query you have defined and on constraints, triggers, and permissions maintained by the database.

For details about the types of queries you can update, see Determining When Query Results Can Be Updated.

Note You cannot update timestamp or binary columns using the Query Designer.

The Query Designer can do only minor validation of the data you enter in the Results pane. For example, if the price column of the titles table accepts only positive values, the Query Designer might not enforce this restriction, and it would be possible to enter a negative value. However, when you save a row, the database will report an error if any column in the row contains invalid data.

To edit data in the Results pane grid

  1. Navigate to the cells containing the data you want to change.

  2. Type in the new data. While you are editing, the leftmost column displays [image] to indicate that the row is being edited.

    While you are editing, the following rules apply:

    • When entering number, currency, time, or date information, use a format that will be recognized according to the specification in the Regional Settings dialog box in the Windows Control Panel (short form for dates).

    • To enter a NULL value into a cell, press CTRL+0.

    • You can edit a memo-type column (such as a text, memo, or long character column) if the column does not display <Long Text>. The Results pane can accept up to 900 characters of text in memo-type columns. If you are typing in a cell and exceed the amount of text that the Results pane can accept, the Query Designer will beep to indicate that you have exceeded this limit.

    • You cannot edit BLOB data.
  3. Save your changes by moving to another row in the grid.

    Note The Query Designer does not automatically save your changes if you switch to another pane. If you edit the current query (for example, by making a change in the Grid Pane), the Results pane is dimmed. However, it is still active, and you can still edit and save the row on which you had been working.

To cancel your changes for the current row, press ESC. If you press ESC while in a cell that you have changed, the changes for only that cell are canceled. If you press ESC while in a cell that you have not changed, the changes for the entire row are canceled and all the cells in that row revert to their old values.

If you are working with tables that can be shared, it is possible that a query you are using conflicts with changes being made by other users. For example, you might be using the Results pane to edit a row while another user executes an Update query that modifies the row you are editing.

When you save the row you have edited, the Query Designer compares the row against the version currently in the database. If there is a difference, the Query Designer displays the Query Definitions Differ dialog box and offers you these options:

  • Save your changes, overwriting changes made by other users.

  • Discard your changes.

  • Cancel the save operation and return to the row. You can then run a second query to examine the row and determine whether to save your original changes, make new changes, or discard your changes.


Adding New Rows in the Results Pane

If the data in the Results pane can be modified, you can also add new rows to the table or tables represented by the result set.

Note You cannot add BLOB or binary columns using the Query Designer.

The Query Designer can perform only simple data validation on the data you enter in the Results pane. For example, if the price column of the titles table accepts only positive values, the Query Designer might be able to enforce this restriction and might display an error message if you enter a negative value. On the other hand, if the column is defined in the database to accept prices in only a certain range (such as between 100 and 1000), the Query Designer cannot enforce this restriction. When you save a row, the database will display an error message if any column in the row contains invalid data.

When you add a row, some columns might be filled in by default values or triggers. In many cases the Query Designer can refresh the display of the new row to show you the automatically generated values. However, rows cannot be refreshed if the row’s primary key:

  • Is not part of the result set.

  • Is generated automatically.

  • Is modified by a trigger.

In these cases, if you want to see the row as it is stored in the database, you must re-execute the query. Even then, however, the new row might not appear if it does not match the search conditions in the query you execute.

You can add new data either by typing it in or by pasting it from the Windows® Clipboard. A row to be pasted must have exactly the same number and types of columns as the table into which you are pasting. You can paste multiple rows into the Results pane at once.

To add a new data row

  1. Navigate to the bottom of the Results pane, where a blank row is available for adding a new data row.

    Tip You can jump from anywhere in the Results pane to the bottom by pressing INS or right-clicking the Results pane, and then choosing New.

  2. If you are pasting rows from the Clipboard, select the new row by clicking the button to its left.

  3. Enter the data for the new row. If you are pasting, choose Paste from the Edit menu.

    Tip To enter null into a cell, press CTRL+0.

  4. Save the new row by moving to another row in the grid.

    Note The Query Designer does not automatically save your changes if you switch to another pane. If you edit the current query (for example, by making a change in the Grid pane), the Results pane is dimmed. However, it is still active, and you can still edit and save the row on which you had been working.

If an error occurs when you save the row (for example, you left a column blank that does not accept null values), the Query Designer displays the error message provided by the database, and then returns you to the row you were editing. You can then:

  • Resolve the error by making further edits in the row.

  • Cancel the edit by pressing ESC. If you press ESC while in a cell that you changed, the changes for that cell are canceled. If you press ESC while in a cell you have not changed, the changes for the entire row are canceled.


Deleting Rows in the Results Pane

If the data in the Results pane can be modified, you can also delete existing rows from the table or tables represented by the result set.

To delete a row

  1. To select the row or rows you want to delete, select the box to the left in the Result pane grid.

  2. Press DELETE.

    Caution Rows you delete in this way are permanently removed from the database and cannot be recalled.


Modifying Data Using Queries

If you need to modify many rows, it is often easier to create a query that changes, inserts, deletes, or copies rows all in one operation than to edit the rows individually in the Results pane.

Types of Queries for Modifying Data

Using the graphical panes of the Query Designer, you can create these types of queries:

  • Update query Changes the values of individual columns in one or more existing rows in a table. This type of query creates an SQL UPDATE statement. For details, see Creating Update Queries.

  • Insert Values query Creates a new row and inserts values into specified columns. This type of query creates an SQL INSERT INTO…VALUES statement. For details, see Creating Insert Values Queries.

  • Insert query Creates new rows by copying existing rows from one table into another, or into the same table as new rows. This type of query creates an SQL INSERT…SELECT statement. For details, see Creating Insert Queries.

  • Make Table query Creates a new table and creates rows in it by copying the results of a query into it. This type of query creates an SQL SELECT…INTO statement. For details, see Creating Make Table Queries.

    Note In Oracle, a Make Table query is implemented as a Create Table As Select command. For details, see Query Designer Considerations for Oracle Databases.

  • Delete query Removes one or more rows from a table. This type of query creates an SQL DELETE statement. For details, see Creating Delete Queries.

    Note A Delete query removes entire rows from the input source. If you want to delete values from individual data columns, use an Update query. If you want to delete columns from a table definition, use the Database Designer. For information on using the Database Designer, see Database Designer.

In addition to using the queries listed above, you can enter any SQL statement into the SQL pane. When you do, the Query Designer dims the graphical panes to indicate that they do not reflect the query you are creating.

In most databases, you can use queries to update or delete rows in only one table. Therefore, the Query Designer displays only one input source window in the Diagram pane. Some databases allow you to update or delete rows in joined tables. In such cases, you must enter your query in the SQL pane, and the graphical panes will be dimmed.

Note You cannot update or insert timestamp or BLOB columns using the Query Designer.

You can edit rows in a multiuser environment, but your changes might conflict with those made by another user.

Constraints and Referential Integrity

When you update a table using the Query Designer, the query respects any constraint defined in the database for the columns and tables that you are updating. For example, if a table is defined with a unique constraint, you cannot execute an Update or Insert query that would write a non-unique row to the table. Similarly, if you are updating a column that has a constraint limiting its values to a certain range, the query will result in an error if you provide an update value outside the specified range.

Queries also respect referential integrity defined between tables. For example, you cannot add rows to a table in the "many" side of a one-to-many relationship if the corresponding "one" side row does not exist.

Note If you are using a database such as Oracle or Microsoft Access that supports cascaded deletes, deleting a row with a one-to-many relationship to another table, deleting a row from the table in the "one" side will also delete rows from the table in the "many." For details, refer to the documentation for your database.


Creating Update Queries

You can change the contents of multiple rows in one operation by using an Update query. For example, in a titles table you can use an Update query to add 10% to the price of all books for a particular publisher.

When you create an Update query, you specify:

  • The table to update

  • The columns whose contents you want to update

  • The value or expression to use to update the individual columns

  • Search conditions to define the rows you want to update

For example, the following query updates the titles table by adding 10% to the price of all titles for one publisher:

UPDATE titles
SET price = price * 1.1
WHERE (pub_id = '0766')

For general information about using queries to update tables, see Modifying Data Using Queries.

Caution You cannot undo the action of executing an Update query. As a precaution, back up your data before executing the query.

To create an Update query

  1. Add the table you want to update to the Diagram pane.

  2. Convert the default query to an Update query by choosing Change Type from the Query menu or the Query Designer Toolbar, and then choosing Update.

    Note If more than one table is displayed in the Diagram pane when you start the Update query, the Query Designer displays the Update Table dialog box to prompt you for the name of the table to update.

  3. Define the data columns to update by adding them to the query. For details, see Adding Columns. Columns will be updated only if you add them to the query.

  4. In the New Value column of the Grid pane, enter the update value for the column. You can enter literal values, column names, or expressions. The value must match (or be compatible with) the data type of the column you are updating.

    Caution The Query Designer cannot check that a value fits within the length of the column you are updating. If you provide a value that is too long, it might be truncated without warning. For example, if a name column is 20 characters long but you specify an update value of 25 characters, the last 5 characters might be truncated.

  5. Define the rows to update by entering search conditions in the Criteria column. For details, see Specifying Search Conditions.

    If you do not specify a search condition, all rows in the specified table will be updated.

    Note When you add a column to the Grid pane for use in a search condition, the Query Designer also adds it to the list of columns to be updated. If you want to use a column for a search condition but not update it, clear the check box next to the column name in the input source window ( [image] ).

When you execute an Update query, no results are reported in the Results pane. Instead, a message appears indicating how many rows were changed.


Creating Insert Queries

You can copy rows from one table to another or within a table using an Insert query. For example, in a titles table, you can use an Insert Query to copy information about all the titles for one publisher to a second table that you can make available to that publisher. An Insert query is similar to a Make Table query, but copies rows into an existing table.

Tip You can also copy rows from one table to another using cut and paste. For details, see Adding New Rows in the Results Pane.

When you create an Insert query, you specify:

  • The database table to copy rows to (the destination table).

  • The table or tables to copy rows from (the source table). The source table or tables become part of a subquery. If you are copying within a table, the source table is the same as the destination table.

  • The columns in the source table whose contents you want to copy.

  • The target columns in the destination table to copy the data to.

  • Search conditions to define the rows you want to copy.

  • Sort order, if you want to copy the rows in a particular order.

  • Group By options, if you want to copy only summary information.

For example, the following query copies title information from the titles table to an archive table called archivetitles. The query copies the contents of four columns for all titles belonging to a particular publisher:

INSERT INTO archivetitles
   (title_id, title, type, pub_id)
SELECT title_id, title, type, pub_id
FROM titles
WHERE (pub_id = '0766')

Note To insert values into a new row, use an Insert Values query.

For general information about using queries to update tables, see Modifying Data Using Queries.

You can copy the contents of selected columns or of all columns in a row. In either case, the data you are copying must be compatible with the columns in the rows you are copying to. For example, if you copy the contents of a column such as price, the column in the row you are copying to must accept numeric data with decimal places. If you are copying an entire row, the destination table must have compatible columns in the same physical position as the source table.

When you create an Insert query, the Grid pane changes to reflect options available for copying data. Because you do not display data in an Insert query, the Output column is removed. An Append column is added to allow you to specify the columns into which data should be copied.

Caution You cannot undo the action of executing an Insert query. As a precaution, back up your data before executing the query.

To create an Insert query

  1. Start an Insert query by choosing Change Type from the Query menu or the Query Designer Toolbar, and then choosing Insert.

  2. In the Insert Into Table dialog box, select the table to copy rows to (the destination table).

    Note The Query Designer cannot determine in advance which tables and views you can update. Therefore, the Table Name list in the Insert Into Table dialog box shows all available tables and views in the data connection you are querying, even those that you might not be able to copy rows to.

  3. Add to the query the table to copy rows from (the source table). For details, see Adding Input Sources. If you are copying rows within a table, you can add the source table as a destination table.

    The data columns from the source table appear in an input window in the Diagram pane.

  4. In the input source window, choose the names of the columns whose contents you want to copy. To copy entire rows, choose * (All Columns).

    The Query Designer adds the columns you choose to the Column column of the Grid pane.

  5. In the Append column of the Grid pane, select a target column in the destination table for each column you are copying. Choose tablename.* if you are copying entire rows. The columns in the destination table must have the same (or compatible) data types as the columns in the source table.

  6. If you want to copy rows in a particular order, specify a sort order. For details, see Ordering Query Results.

  7. Specify the rows to copy by entering search conditions in the Criteria column. For details, see Specifying Search Conditions.

    If you do not specify a search condition, all rows from the source table will be copied to the destination table.

    Note When you add a column to search to the Grid pane, the Query Designer also adds it to the list of columns to copy. If you want to use a column for searching but not copy it, clear the check box next to the column name in the input source window ( [image] ).

  8. If you want to copy summary information, specify Group By options. For details, see Summarizing Values for All Rows in a Table.

When you execute an Insert query, no results are reported in the Results pane. Instead, a message appears indicating how many rows were copied.


Creating Delete Queries

You can delete multiple rows in one operation by using a Delete query. When you create a Delete query, you specify the database table to delete rows from and the search condition to define the rows you want to delete.

Note Deleting all rows from a table clears the data in the table but does not delete the table itself. You can delete tables using the Database Designer. For information about using the Database Designer, see Database Designer.

For general information about using queries to update tables, see Modifying Data Using Queries.

When you create a Delete query, the Grid pane changes to reflect the options available for deleting rows. Because you do not display data in a Delete query, the Output, Sort By, and Sort Order columns are removed. In addition, the check boxes next to the column names in the input source window are removed because you cannot specify individual columns to delete.

Caution You cannot undo the action of executing a Delete query. As a precaution, back up your data before executing a Delete query.

To create a Delete query

  1. Add the table to delete rows from to the Diagram pane.

  2. Start a Delete query by choosing Change Type from the Query menu or the Query Designer Toolbar, and then choosing Delete.

    Note If more than one table is displayed in the Diagram pane when you start the Delete query, the Query Designer displays the Delete Table dialog box to prompt you for the name of the table to delete rows from.

  3. Enter search conditions to define the rows to be deleted. For details, see Specifying Search Conditions. If you do not specify a search condition, all rows in the specified table will be deleted.

    Note Because you cannot delete the contents of individual columns, the check boxes in the input source window are removed when you start a Delete query. To add columns to the Grid pane to use in search conditions, drag them from the input source window to the Columns column, or select a data column in the Columns column.

When you execute the Delete query, no results are reported in the Results pane. Instead, a message appears indicating how many rows were deleted.


Creating Insert Values Queries

You can create a new row in the current table using an Insert Values query. When you create an Insert Values query, you specify:

  • The database table to add the row to.

  • The columns whose contents you want to add.

  • The value or expression to insert into the individual columns.

Note In Oracle, you can also use named sequences in an Insert Values query. For details, see Query Designer Considerations for Oracle Databases.

For example, the following query adds a row to the titles table, specifying values for the title, type, publisher, and price:

INSERT INTO titles
         (title_id, title, type, pub_id, price)
VALUES   ('BU9876', 'Creating Web Pages', 'business', '1389', '29.99')

For general information about using queries to update tables, see Modifying Data Using Queries.

When you create an Insert Values query, the Grid pane changes to reflect the only options available for inserting a new row: the column name and the value to insert.

Caution You cannot undo the action of executing an Insert Values query. As a precaution, back up your data before executing the query.

To create an Insert Values query

  1. Add the table you want to update to the Diagram pane.

  2. Convert the default query to an Insert Values query by choosing Change Type from the Query menu or the Query Designer Toolbar, and then choosing Insert Values.

    Note If more than one table is displayed in the Diagram pane when you start the Insert Values query, the Query Designer displays the Insert Values dialog box to prompt you for the name of the table to update.

  3. Define the data columns to create by adding them to the query. For details, see Adding Columns. Columns will be updated only if you add them to the query.

  4. In the New Value column of the Grid pane, enter the new value for the column. You can enter literal values, column names, or expressions. The value must match (or be compatible with) the data type of the column you are updating.

    Caution The Query Designer cannot check that a value fits within the length of the column you are inserting. If you provide a value that is too long, it might be truncated without warning. For example, if a name column is 20 characters long but you specify an insert value of 25 characters, the last 5 characters might be truncated.

When you execute an Insert Values query, no results are reported in the Results pane. Instead, a message appears indicating how many rows were changed.


Creating Make Table Queries

You can copy rows into a new table using a Make Table query, which is useful for creating subsets of data to work with or copying the contents of a table from one database to another. A Make Table query is similar to an Insert query, but creates a new table to copy rows into.

Note In Oracle, a Make Table query is implemented as a Create Table As Select command. For details, see Query Designer Considerations for Oracle Databases.

When you create a Make Table query, you specify:

  • The name of the new database table (the destination table).

  • The table or tables to copy rows from (the source table). You can copy from a single table or from joined tables.

  • The columns in the source table whose contents you want to copy.

  • Sort order, if you want to copy the rows in a particular order.

  • Search conditions to define the rows you want to copy.

  • Group By options, if you want to copy only summary information.

For example, the following query creates a new table called uk_customers and copies information from the customers table to it:

SELECT *
INTO uk_customers
FROM customers
WHERE country = 'UK'

In order to use a Make Table query successfully:

  • Your database must support the SELECT...INTO syntax.

  • You must have permission to create a table in the target database.

To create a Make Table query

  1. Add the source table or tables to the Diagram pane.

  2. Convert the default query to a Make Table query by choosing Change Type from the Query menu or the Query Designer Toolbar, and then choosing Make Table.

  3. In the Make Table dialog box, type the name of the destination table. The Query Designer does not check whether the name is already in use or whether you have permission to create the table.

    To create a destination table in another database, specify a fully qualified table name including the name of the target database, the owner (if required), and the name of the table.

  4. Specify the columns to copy by adding them to the query. For details, see Adding Columns. Columns will be copied only if you add them to the query. To copy entire rows, choose * (All Columns).

    The Query Designer adds the columns you choose to the Column column of the Grid pane.

  5. If you want to copy rows in a particular order, specify a sort order. For details, see Ordering Query Results.

  6. Specify the rows to copy by entering search conditions. For details, see Specifying Search Conditions.

    If you do not specify a search condition, all rows from the source table will be copied to the destination table.

    Note When you add a column to search to the Grid pane, the Query Designer also adds it to the list of columns to copy. If you want to use a column for searching but not copy it, clear the check box next to the column name in the input source window ( [image]).

  7. If you want to copy summary information, specify Group By options. For details, see Summarizing Values for All Rows in a Table.

When you execute a Make Table query, no results are reported in the Results pane. Instead, a message appears indicating how many rows were copied.


Visual Database Tools Glossary

A | B | C | D | E | F | G | H | I | J | K | L | M

N | O | P | Q | R | S | T | U | V | W | X | Y | Z

A

aggregate function

A function that generates a single value from a group of values, often used with Group By and Having clauses. Aggregate functions include Avg, Count, Max, Min, and Sum. Also known as a set function.

aggregate query

A query (SQL statement) that summarizes information from multiple rows by including an aggregate function such as Sum or Avg. For example, you can create a query that averages the contents of a price column. Aggregate queries can also display subtotal information by creating groups of rows that have data in common. An example would be a query that displays the average price of a book for each publisher.

alias

An alternative name for a table or column in expressions. Aliases are often used to shorten the table or column name for subsequent references in code, prevent possible ambiguous references, or provide a more descriptive name in query output.

asynchronous

Of an action, that executes separately from other events or actions. Asynchronous actions are performed in such a way that other actions can be performed simultaneously. For example, in the Query Designer, queries are executed asynchronously. Because individual results are returned as they are found, you can view results or perform other actions while the query continues to search for additional results.

B

back end

The server or engine in a database system. In general, back end refers to the system that is the repository for the data, in contrast to the client, which presents data to the user. In a client/server system, the back end is the server. In an integrated database system, such as Microsoft® Visual FoxPro™ or Microsoft® Excel, the back end is the core database functionality of the product. As a rule, the back end contains the code that handles not only data storage, but indexes, validation, triggers, referential integrity, and other database functions.

BCP (Bulk Copy Program)

A command-line utility that copies Microsoft® SQL Server™ data to or from an operating-system file in a user-specified format.

BLOB (Binary Large Object)

A type of data column containing binary data such as graphics, sound, or compiled code.

C

candidate key

A unique identifier for a row within a database table. A candidate (or surrogate) key can be made up of one or more columns. By definition, every table must have at least one candidate key (in which case it automatically becomes the primary key for a table), but it is possible for a table to have more than one candidate key (in which case one of them must be designated as the primary key). Any candidate key that is not the primary key is called an alternate key.

change script

A text file that contains SQL statements for all changes made to a database, in the order in which they were made during an editing session. Each change script is saved in a separate text file with an .sql extension. The change script creates a record of the changes made to the database which can be applied back to the database at a later time via a tool such as isql.

check constraint

Specifies data values that are acceptable in a column. You can apply check constraints to multiple columns and you can apply multiple check constraints to a single column. When a table is deleted, all check constraints are also deleted.

client

The portion of a database system or application that presents data to the user. As a rule, the client (or front end) does not perform any database functions; instead, the client sends requests for data to a server, and then formats and displays the results.

Contrast with server, and back end.

client/server

A type of application that has a local interface but accesses data on a remote server. The application distributes the work between the local machine (the client) and the server (the back end), depending on the strengths of the client and server products. Client/server systems are often very efficient because they minimize network traffic, and because each portion of the application can be optimized for its particular function.

code page

A character set that a computer uses to interpret and display data properly. Code pages usually correspond to different platforms and languages and are used in international applications.

Compare with locale.

column

A location within a database table that stores a particular type of data (for example, the firstname column in the authors table of the pubs sample database). The logical equivalent of a field.

Individual columns have their own specifications as to data type (for example, binary, character, integer, and so on) and maximum length. These are called column properties.

constraint

Restriction placed upon the value that can be entered into a column or a row. For example, age cannot be < 0 or > 110.

Compare with check constraint, unique constraint.

crosstab query

Displays data for summarized values from a field in a table, and then groups them by two sets of facts; one down the left side and the other across the top of the datasheet.

D

data connection

A collection of information required to access a specific database. The collection includes a data source name (DSN) and logon information. Data connections are stored in a project and are activated when the user performs an action that requires access to the database.

For example, a data connection for a Microsoft® SQL Server™ database consists of the name of the database, the location of the server on which it resides, network information used to access that server, and a user ID and password.

data definition language (DDL)

A language, usually a part of a database management system, that is used to define all attributes and properties of a database, especially row layouts, column definitions, key columns (and, sometimes, keying methodology), file locations, and storage strategy.

data source

An ODBC term for the entity that provides data; similar to the term back end.

data source name (DSN)

An ODBC term for the collection of information used to connect your application to a particular ODBC database. The ODBC Driver Manager uses this information to create a connection to the database. A DSN can be stored in a file (a file DSN) or in the Windows® Registry (a machine DSN).

Compare with data connection.

database diagram

A graphical representation of any portion of a database schema. A database diagram can be either a whole or partial picture of the structure of a database; it includes objects for tables, the columns they contain, and the relationships between them.

database object

One of the components of a database: a table, index, trigger, view, key, constraint, default, rule, user-defined data type, or stored procedure.

database project

A collection of one or more data connections (a database and the information needed to access that database). When you create a database project, you can connect to one or more databases through ODBC and view their components through a visual user interface that includes a Database Designer for designing and creating databases and a Query Designer for creating SQL statements for any ODBC-compliant database.

data-definition query

An SQL-specific query that contains Data Definition Language (DDL) statements. These are statements that allow you to create or alter objects (such as tables, indexes, views, and so on) in the database.

DBCS (Double-Byte Character Set)

A character set that uses one or two bytes to represent a character, allowing more than 256 characters to be represented. DBCS character sets are typically used in environments that use ideographic writing systems, such as Japanese, Korean, and Chinese.

default

Database object that enables the database to insert a value into a column if the user does not explicitly enter one.

Compare with global default.

Delete query

A query (SQL statement) that removes rows from one or more tables. For example, the following Delete query removes rows from the titles table if their pub_id column contains the value "0766":

DELETE FROM titles
WHERE pub_id = '0766'

direct connect

The state of being connected to a back-end database, like Microsoft® SQL Server™, so that any changes you make to a database diagram automatically update your database when you save the diagram or selected objects in it.

drag-and-drop

A combination of features that allows the user to drag an item and drop it into another item using the mouse. An item can be a source (the item the user drags) or a target (the item on which the user drops a source).

DSN-less connection

A type of data connection that is created based on information in a data source name (DSN) but is stored as part of a project or application. DSN-less connections are especially useful for Web applications because they enable you to move the application from one server to another without recreating the DSN on the new server.

Compare with data connection, data source name.

E

encrypted trigger

A trigger that is created with an optional encryption parameter that encrypts the definition text and cannot be decrypted. Encryption makes the information indecipherable to protect it from unauthorized viewing or use.

Compare with trigger.

equijoin

A join in which rows from two tables are combined and added to the result set when there are equal values in the joined columns. By default, the inner and outer join types in the Query Designer are equijoins.

escape character

A character used to indicate that another character in an expression is meant literally and not as an operator. For example, in SQL the character "%" is used as a wildcard character to mean "any number of characters in this position." However, if you want to search for a string such as "10%" (ten percent), you cannot specify "10%" alone as a search string, because the "%" would be interpreted to mean "any number of characters in addition to 10." By specifying an escape character, you can flag instances where you mean "%" as "percent" specifically. For example, if you specify the escape character "#", you can indicate a search string of "10#%" to mean "ten percent."

Compare with wildcard character.

expression

Any combination of operators, constants, literal values, functions, names of columns, controls, and properties that result in a single value. In a query, you can use expressions anywhere that you can use a column name. In the Query Designer, you can use expressions as settings for many action and properties arguments, to set criteria or define calculated fields in queries, and to set conditions in macros. In the Database Designer, you can use expressions to define check constraints.

F

field

A location in a record where data is stored; used in some database systems to mean "column." Although the terms "field" and "column" have slightly different meanings in formal database theory, in most instances they are meant synonymously.

file DSN

Stores connection information for a database in a file that's saved on your computer. The file is a text file with the extension .dsn. The connection information consists of parameters and corresponding values that the ODBC Driver Manager uses to establish a connection.

Compare with data source name.

Contrast with machine DSN.

fill factor

An option that specifies how full the database should make each index page. The amount of empty space on an index page is important because when an index page fills up, the system must take time to split it to make room for new rows. Use a fill factor of zero (0) to accept the database default.

filter

A set of criteria applied to records to show a subset of the records or to sort the records.

foreign key

A column or combination of columns whose values match the primary key of some other table. A foreign key does not have to be unique; in fact, foreign keys are often in a many-to-one relationship to a primary key. Foreign key values should be copies of the primary key values; no value in the foreign key except NULL should ever exist unless the same value exists in the primary key. A foreign key may be NULL; if any part of a composite foreign key is NULL, the entire foreign key must be NULL.

full outer join

A type of outer join in which all rows in all joined tables are included, whether they are matched or not. For example, a full outer join between titles and publishers shows all titles and all publishers, even those that have no match.

Compare with inner join, left outer join, and right outer join.

G

global default

A default that is defined for a specific database and is shared by columns of different tables.

Compare with default.

global rule

A rule that is defined for a specific database and is shared by columns of different tables.

Compare with rule .

H

I

index

A database object that provides access to data in the rows of a table, based on key values. Indexes provide quick access to data and can enforce uniqueness on the rows in a table.

inner join

A join in which records from two tables are combined and added to a query's results only if the values of the joined fields meet certain specified criteria. For example, the default join between tables in Query Designer view is an inner join that selects records from both tables only when the values of the joined fields are equal.

Compare with outer join.

input source

Any table, view, or database diagram used as an information source for a query. Some databases may make other input sources available; for example, if you are using the Oracle database server, you can use synonyms as input sources.

Insert query

A query that copies specific columns and rows from one table to another or to the same table. For example, the following Insert query copies the contents of the title_id, title, type, and pub_id columns from the titles table to the archivetitles table:

INSERT INTO archivetitles
SELECT title_id, title, type, pub_id
FROM titles

Insert Values query

A query (SQL statement) that creates a new row and inserts values into specified columns. For example, the following Insert Values query inserts a new row into the titles table:

INSERT INTO titles
title_id, title, type, pub_id, price)
VALUES ('BU0219', 'Web Page Design', 'business', '1389', 29.99)

J

join

As a verb, to combine the contents of two or more tables and produce a result set that incorporates rows and columns from each table. Tables are typically joined using data that they have in common. For example, you can join a titles and publishers table on a common pub_id column to produce a result set that contains both title information and publisher information.

As a noun, the process or result of joining tables, as in the term "inner join" to indicate a particular method of joining tables.

Compare with inner join, and outer join.

join condition

A comparison clause that specifies how tables are related via their join fields. The most common join condition is equivalence (an equijoin) in which the values of the join fields must be the same. For example, you can join the titles and publishers tables by finding values that match in their respective pub_id columns. However, any comparison operator can be part of a join condition.

join operator

A comparison operator in a join condition that determines how the two sides of the condition are evaluated and which records are returned. The most common comparison operator is equivalence (=).

junction table

A table that has associations with two other tables and is used indirectly as an association between those two tables. Also called linking table.

K

key

A column used to identify a record, often used as the index column for a table.

L

left outer join

A type of outer join in which all rows from the first-named table (the left table, which appears leftmost in the JOIN clause) are included. Unmatched rows in the right table do not appear. For example, you can create a left outer join between titles and the publishers tables to include all titles, even those you don't have publisher information for.

Compare with inner join, outer join, and right outer join.

linking table

A table that has associations with two other tables and is used indirectly as an association between those two tables. Also called junction table.

locale

The set of information that corresponds to a specific language and country. A locale indicates specific settings such as decimal separators, date and time formats, and character-sorting order.

M

machine DSN

Stores connection information for a database in the system registry. The connection information consists of parameters and corresponding values that the ODBC Driver Manager uses to establish a connection.

Compare with data source name.

Contrast with file DSN.

Make Table query

A query (SQL statement) that creates a new table and then creates rows in it by copying rows from an existing table. For example, the following make table query copies rows from the titles table to the titlesCooking table:

SELECT title_id, title, type, pub_id, price
INTO titlesCooking
FROM titles
WHERE type = 'cooking'

many-to-many relationship

A relationship between two tables in which rows in each table have multiple matching rows in the related table. For example, a many-to-many relationship is possible between the authors table and the titles table in the pubs sample database because each author can have written many titles, and each title can have many authors. Many-to-many relationships are maintained by using a third table called a junction table.

memo

A type of column containing long strings of unstructured text (typically more than 255 characters).

N

O

object

One of the components of a database: a table, index, trigger, view, key, constraint, default, rule, user-defined data type, or stored procedure. Also called a database object.

ODBC (Open Database Connectivity)

A standard protocol for database servers providing a common language for Windows® applications to gain access to a database on a network. You install ODBC drivers for various databases that enable you to connect to the databases and access their data.

one-to-many relationship

A relationship between two tables in which a single row in the first table can be related to one or more rows in the second table, but a row in the second table can be related to only one row in the first table. A typical one-to-many relationship is between the publishers table and the titles table in the pubs sample database, in which each publisher can be related to several titles, but each title can be related to only one publisher.

one-to-one relationship

A relationship between two tables in which a single row in the first table can be related to only one row in the second table, and a row in the second table can be related to only one row in the first table. This type of relationship is unusual. An example is the relationship between an employee table and a mailboxes table used to store information about email addresses in a company. The tables have a one-to-one relationship because each employee has one mailbox, and each mailbox is assigned to only one employee.

outer join

A join that includes records even if they do not have related records in the joined table. You can create three variations of an outer join to specify the unmatched rows to be included: left outer join, right outer join, and full outer join.

Compare with inner join.

P

parameter

A value given to a variable. A parameter acts as placeholder in a query or stored procedure that can be filled in when the query or stored procedure is executed. Parameters allow you to use the same query or stored procedure many times, each time with different values.

For example, you can create a query with a parameter for a last name, then when you run the query, have it prompt you for the last name to find. Parameters can be used for any literal value, and in some databases, for column references as well.

pass-through query

A query you can use to work directly with tables on a server that understands a dialect of SQL that is different from the SQL processed by the client application. You can use a pass-through query to return a snapshot of rows or execute non-row-returning commands.

persistence

Storage of objects and data structures that involves converting complex data structures into a format suitable for file storage. Persistent data is retained by the computer between sessions.

primary key

A column or combination of columns that uniquely identifies a row in a table. It cannot allow null values and must always have a unique index. A primary key is used to relate a table to foreign keys in other tables.

property

A named attribute of an object. Properties define object characteristics, such as size and name, or the state of an object, such as enabled or disabled. Properties can be set for tables, columns, indexes, constraints, keys, and relationships.

property pages

A tabbed dialog box where you can identify the characteristics of tables, relationships, indexes, constraints, and keys. Every object in a database diagram has a set of properties that determine the definition of a database object. Each set of tabs shows only the properties specific to the selected object. If multiple objects are selected, the property pages show the properties of the first object you selected.

Q

query

A specific request or set of instructions for retrieving, modifying, inserting, or deleting data in a database.

R

record

A term used in some database systems to mean "row". Although record and row have slightly different meanings in formal database theory, in most instances they are meant synonymously.

referential integrity (RI)

Ensures that for each row in a foreign key table, a corresponding row exists in the primary key table. It also prevents a row in a primary key table from being deleted when a relationship exists to a foreign key table. In database diagrams, the relationship between tables must be deleted before primary key columns can be deleted.

reflexive relationship

A relationship from a column or combination of columns in a table to other columns in that same table. Reflexive relationships are used to compare rows within the same table. For example, you can create a reflexive relationship to find all publishers that are in the same city and have the same postal code. In queries, this is called a self-join.

relationship

A link between tables that references the primary key in one table to a foreign key in another table. The relationship line is represented in a database diagram by a solid line if referential integrity between tables is enforced, or a dashed line if referential integrity is not enforced for INSERT and UPDATE transactions. The endpoints of a relationship line show a primary key symbol [image] to denote a primary key-to-foreign key relationship or an infinity symbol [image] to denote the foreign key side of a one-to-many relationship.

result set

A virtual table that is produced by a query, representing all the columns and rows returned by the query in the order you specified.

right outer join

A type of outer join in which all rows in the second-named table (the right table, the one that appears rightmost in the JOIN clause) are included. Unmatched rows in the left table are not included. For example, a right outer join between titles and publishers tables will include all publishers, even those who have no titles in the titles table.

Compare with inner join, outer join, and left outer join.

row

In a table, a set of related columns of information that are treated as a unit and that describe a specific entity. A row is the logical equivalent of a record.

rule

A database object that is bound to a column or to a user-defined data type and that specifies what data can be entered in that column.

Compare with global rule.

S

schema

A description of a database to the database management system (DBMS), generated using the data definition language provided by the DBMS. A schema defines attributes of the database, such as tables, columns, properties.

Compare with database diagram.

search condition

A comparison clause used in a query to specify the rows to return or update. For example, you can use a search condition to specify that a query displays only the authors who live in London.

Select query

A query that returns rows into a result set from one or more tables. A Select query can contain specifications for the columns to return, the rows to select, the order to put the rows in, and how to group (summarize) information.

Contrast with Delete query, Insert query, and Update query, all of which change data in a table.

self-join

A join that compares rows within the same table. For example, you can use a self-join to find all publishers that are in the same city and have the same postal code. In database diagrams, a self-join is called a reflexive relationship.

server

A computer on a network that controls access to data.

Compare with client/server.

set function

A function that generates a single value from a group of values, often used with Group By and Having clauses. Aggregate functions include Avg, Count, Max, Min, and Sum. Also known as an aggregate function.

SQL

Structured Query Language, a database query and programming language.

stored procedure

A precompiled collection of SQL statements and optional control-of-flow statements stored under a name and processed as a unit. Stored procedures are stored within a database; can be executed with one call from an application; and allow user-declared variables, conditional execution, and other powerful programming features.

subquery

A SELECT statement defined within a query. The result set of the embedded SELECT statement becomes part of the search condition for the second query. For example, the following query uses a subquery to find all suppliers in Sweden, then uses the results in a WHERE clause to find all products with the selected suppliers:

WHERE supplier_id IN
    (SELECT supplier_id
    FROM supplier
    WHERE (country = 'Sweden'))

subset

A selection of tables and the relationship lines between them that is part of a larger database diagram. This selection can be copied to a new database diagram. This is called subsetting the diagram.

surrogate key

A unique identifier for a row within a database table. A surrogate (or candidate) key can be made up of one or more columns. By definition, every table must have at least one surrogate key (in which case it automatically becomes the primary key for a table), but it is possible for a table to have more than one surrogate key (in which case one of them must be designated as the primary key). Any surrogate key that is not the primary key is called an alternate key.

T

table

A data structure containing a collection of rows (or records) that have associated columns (or fields). It is the logical equivalent of a database file.

transaction log

A storage area reserved by the database to keep track of transactions made to the database.

trigger

A special form of a stored procedure that is carried out automatically when data in a specified table is modified. Triggers are often created to enforce referential integrity or consistency among logically related data in different tables.

U

unenforced relationship

A link between tables that references the primary key in one table to a foreign key in another table, and that doesn't check referential integrity during INSERT and UPDATE transactions. An unenforced relationship is represented in a database diagram by a dashed line.

Union query

A query that combines two tables by performing the equivalent of appending one table onto the other.

unique constraint

A constraint that enforces entity integrity on a non-primary key. It ensures no duplicate values are entered in the columns on which the constraint is placed. NULL values are allowed as long as rows are unique in the table.

UNC (Universal Naming Code)

A naming convention for files which provides a machine-independent means of locating the file. A UNC name will usually include a reference to a shared folder and file name accessible over a network rather than specifying a drive letter and path. For example, to access a database named Northwind.mdb on a shared directory named Samples on the computer called MyWorkstation, you could use the UNC name \\MyWorkstation\Samples\Northwind.mdb.

UNC naming conventions are particularly useful in Web-based applications because they allow reference to data that is not necessarily stored on a particular Web server.

Update query

A query (SQL statement) that changes the values in columns of one or more rows in a table. For example, the following Update query for the titles table adds 10% to the price of all books for a particular publisher:

UPDATE titles
SET price = price * 1.1
WHERE pub_id = '1389'

user-defined data type

A definition of the type of data a column can contain. It is created by the user and defined in terms of existing system data types. Rules and defaults can be bound to user-defined data types but not to system data types.

V

view

A virtual table generated by a query whose definition is stored in the database. For example, a view might be defined as containing three out of five available columns in a table, created to limit access to certain information. Views can be treated as tables for most database operations, including Select queries, and under some circumstances, Update, Insert, and Delete queries. Any operations performed on views actually affect the data in the table or tables on which the view is based.

W

wildcard character

A character that represents one or more other characters. For example, in SQL you can use the wildcard character "%" to mean "any number of characters," and can use it to search for parts of a word. The following example shows a search condition that uses the wildcard character "%" to indicate all names words that begin with "Mac":

LIKE 'Mac%'

Compare with escape character.

X

Y

Z


Interface Reference

The following reference information is available for the Visual Database Tools interface.

For information about | See
The objects in the database diagram window | Database Diagram Window
The panes in the Query Designer window | Query Designer Window
Error messages | Troubleshooting Error Messages
Dialog boxes used when working with database diagrams | Database Designer Dialog Boxes
Dialog boxes used when working with queries and views | Query Designer Dialog Boxes
Dialog boxes used to set properties for objects in the database diagram | Database Designer Properties Pages
Dialog boxes used to set properties for objects in the query panes | Query Designer Properties Pages


Database Diagram Window

The Database Diagram window presents a graphic display of the tables and relationships in your database.

In the Database Diagram window, you can:

  • Add tables to the database diagram by dragging them from the tables folder.

  • Remove tables from the diagram or delete them from the database.

  • Save selected tables, or the entire database diagram.

  • Create, edit, or delete relationships between tables.

  • Create, edit, or delete tables and table column definitions.

  • Open the property pages to edit objects shown in the diagram, or to create, edit, or delete database objects, such as indexes and constraints, that are not graphically represented in the diagram:

  • Lay out the objects shown in the diagram by changing the table view. Five pre-defined table views are available as shown below. For more information, see Changing a Table View.

  • Change the arrangement of the objects in the database diagram by automatically arranging the tables, expanding and collapsing the tables by changing the column view, and by rearranging relationship lines. For more information, see Formatting a Database Diagram.

When you save a database diagram, the database is updated to match your diagram. The diagram is saved in your project directory and shown in the Database Diagrams folder in Data View. The diagram is also saved in the dtproperties or MicrosoftDTProperties table of your database.

Before you save a diagram, you can view an SQL change script to see the SQL statements that will be applied to the database when you save the diagram. If you close a diagram without saving it, the underlying database remains unchanged.

For more information about database diagrams, see Working in Database Diagrams.


Query Designer Window

The Query Designer provides a series of panes in which you can design, edit, and test your query. The panes are synchronized so that changes you make in one are reflected in the others, providing you with both a graphical and textual version of your query at all times.

Each pane provides different features for creating your query. For details about how each pane is used, see the topics listed in the following table

To | See
Add tables or views to your query, select columns to work with, and join tables | Diagram Pane
Specify options for displaying columns, sorting the results, searching, and grouping results | Grid Pane
Enter SQL commands directly | SQL Pane
View the results of your most recent Select query, and edit data directly | Results Pane


Diagram Pane

The Diagram pane presents a graphic display of the input sources (tables, views, or other queries) you have selected from the data connection. It also shows any join relationships among them.

In the Diagram pane you can:

  • Add or remove input sources and specify data columns for output.

  • Specify columns for ordering the query.

  • Specify that you want to group rows in the result set.

  • Create or modify joins between input sources.

When you make a change in the Diagram pane, the Grid pane and SQL pane are updated to reflect your change. For example, if you select a column for output in an input source window in the Diagram pane, the Query Designer adds the data column to the Grid pane and to the SQL statement in the SQL pane.

In this topic, you can find information about:

  • Resizing Input Source Windows

  • Working with Joined Tables

About the Diagram Pane

Each input source appears as a separate window in the Diagram pane. The icon in the title bar of each window indicates what type of input source the window represents, as illustrated in the following table.

Icon | Input source type
 | Table
 | Query or View
 | Linked Table
 | Subquery (in FROM clause)
 | Linked View

Note If you are working with an Oracle database, you can also use synonyms as input sources. For details, see Query Designer Considerations for Oracle Databases.

The input source’s data columns are listed in its window. Check boxes and symbols appear next to the names of columns to indicate how the columns are being used in the query. ToolTips display information such as data type and size for columns.

The following table lists the check boxes and symbols used in input source windows.

Check box or symbol Description

Specifies whether a data column appears in the query result set (Select query) or is used in an Update, Insert, Make Table, or Insert Values query. Select the column to add it to the results. If (All Columns) is selected, all data columns appear in the output.

Note Oracle does not permit you to combine the "*" operator with individual column names. For details, see Query Designer Considerations for Oracle Databases.

The icon used with the check box changes according to the type of query you are creating. (When creating a Delete query, you cannot select individual columns.)

Indicates that the data column is being used to order the query results (is part of an ORDER BY clause). The icon appears as A-Z if the sort order is ascending or Z-A if sort order is descending.
Indicates that the data column is being used to create a grouped result set (is part of a GROUP BY clause) in an aggregate query.
Indicates that the data column is included in a search condition for the query (is part of a WHERE or HAVING clause).
Indicates that the contents of the data column are being summarized for output (are included in a SUM, AVG, or other aggregate function).

Note The Query Designer will not display data columns for an input source if you do not have sufficient access rights to it or if the database driver cannot return information about it. In such cases, the Query Designer displays only a title bar for the input source.

Resizing Input Source Windows

If you need more room in the Diagram pane, you can resize individual input source windows as you would any window. In addition, you can collapse them so that only the input source names are visible. When you want to work with columns in an input source whose window has been collapsed, you can expand that input source again.

To collapse an input source window

  1. Select the input source.

  2. From the View menu, choose Tables, and then choose Name Only.

    –or–

    Click the Minimize button in the window’s title bar.

To expand a collapsed input source window

  1. Select the input source.

  2. From the View menu, choose Tables, and then choose Column Names.

    –or–

    Click the Restore button in the window’s title bar.

Working with Joined Tables

If the query involves a join, a join line appears between the data columns involved in the join. If the joined data columns are not displayed (for example, the input source window is minimized or the join involves an expression), the Query Designer places the join line in the title bar of the input source window. The Query Designer displays one join line for each join condition.

The shape of the icon in the middle of the join line indicates how the input sources are joined. If the join clause uses an operator other than equal (=), the operator is displayed in the join line icon. The following table lists the icons that can be displayed in a join line.

Join line icon | Description
 | Inner join (created using equal sign).
 | Inner join based on the "greater than" operator. (The operator displayed in the join line icon reflects the operator used in the join.)
 | Outer join in which all rows from the table represented on the left will be included, even if they do not have matches in the related table.
 | Outer join in which all rows from the table represented on the right will be included, even if they do not have matches in the related table.
 | A full outer join in which all rows from both tables will be included, even if they do not have matches in the related table.

Note Oracle databases do not support full outer joins. For details, see Query Designer Considerations for Oracle Databases.

Icons on the ends of the join line indicate the type of join. The following table lists the types of joins and the icons that can be displayed on the ends of the join line.

Icon on ends of join line | Description
 | One-to-one join
 | One-to-many join
 | Query Designer cannot determine join type


Grid Pane

The Grid pane allows you to specify query options — such as which data columns to display, how to order the results, and what rows to select — by entering your choices into a spreadsheet-like grid. In the Grid pane you can specify:

  • Columns to display and column name aliases

  • The table that a column belongs to

  • Expressions for calculated columns

  • The sort order for the query

  • Search conditions

  • Grouping criteria, including aggregate functions to use for summary reports

  • New values for Update or Insert Values queries

  • Target column names for Insert queries

Changes you make in the Grid pane are automatically reflected in the Diagram pane and SQL pane. Similarly, the Grid pane is updated automatically to reflect changes made in the other panes.

In this topic, you can find information about:

  • Navigating in the Grid Pane

  • Resizing Grid Columns

  • Editing Values in Cells

  • Adding and Removing Data Columns in the Grid Pane

  • Reordering Grid Rows

About the Grid Pane

The rows in the Grid pane display the data columns used in your query; columns in the Grid pane display query options.

The specific information that appears in the Grid pane depends on the type of query you are creating. If you are creating a Select query, the Grid pane contains different columns than if you are creating an Update query.

The following table lists the grid columns that can appear in the Grid pane.

Column | Query type | Description
Column | All | Displays either the name of a data column used for the query or the expression for a computed column. This column is locked so that it is always visible as you scroll horizontally.
Alias | Select, Insert, Update, Make Table | Specifies either an alternate name for a column or the name you can use for a computed column.
Table | Select, Insert, Update, Make Table | Specifies the name of the input source for the associated data column. This column is blank for computed columns.
Output Select, Insert, Make Table Specifies whether a data column appears in the query output.

Note If the database allows, you can use a data column for sort or search clauses without displaying it in the result set.
Sort Type | Select, Insert | Specifies that the associated data column is used to sort the query results and whether the sort is ascending or descending.
Sort Order | Select, Insert | Specifies the sort priority for data columns used to sort the result set. When you change the sort order for a data column, the sort order for all other columns is updated accordingly.
Group By Select, Insert, Make Table Specifies that the associated data column is being used to create an aggregate query. This grid column appears only if you have chosen Group By from the Tools menu or have added a GROUP BY clause to the SQL pane.

By default, the value of this column is set to Group By, and the column becomes part of the GROUP BY clause.

When you move to a cell in this column and select an aggregate function to apply to the associated data column, by default the resulting expression is added as an output column for the result set.
Criteria All Specifies a search condition (filter) for the associated data column. Enter an operator (the default is "=") and the value to search for. Enclose text values in single quotation marks.

If the associated data column is part of a GROUP BY clause, the expression you enter is used for a HAVING clause.

If you enter values for more than one cell in the Criteria grid column, the resulting search conditions are automatically linked with a logical AND.

To specify multiple search condition expressions for a single database column (for example, (fname > 'A') AND (fname < 'M'), add the data column to the Grid pane twice and enter separate values in the Criteria grid column for each instance of the data column.
Or … | All | Specifies an additional search condition expression for the data column, linked to previous expressions with a logical OR. You can add more Or … grid columns by pressing the TAB key in the rightmost Or … column.
Append | Insert | Specifies the name of the target data column for the associated data column. When you create an Insert query, the Query Designer attempts to match the source to an appropriate target data column. If the Query Designer cannot choose a match, you must provide the column name.
New Value | Update, Insert Values | Specifies the value to place into the associated column. Enter a literal value or an expression.

Navigating in the Grid Pane

You can move from cell to cell in the Grid pane using the mouse or by pressing the TAB or arrow keys. As you scroll, the leftmost grid column (Column) is locked so that you can always see the data column name you are working with.

Resizing Grid Columns

You can resize grid columns to make more room for entries.

To resize a grid column

  • Move the mouse over the divider between grid column headers until it changes to a double-headed arrow, and then either drag the grid column header until the column is the size you want or double-click to auto-size the column.

Editing Values in Cells

You can specify query options by entering values in the appropriate cell of the Grid pane. Certain grid columns — for example, Column or Sort Type — display drop-down lists when you navigate to them.

The check box in the Output grid column indicates whether a data column appears in the result set of the query. If this check box is selected, the data column will appear in the output. If it is not selected, the data column will be used for ordering or searching, but will not appear in the result set.

To remove a query option

  • Move to the appropriate cell, select the value, and then press DELETE.

You can also remove all values in the Grid column at once.

To remove all the values in a Grid column

  • Select the column by clicking its header, and then press DELETE.

Adding and Removing Data Columns in the Grid Pane

You can add and remove data columns to the grid to make them part of the query. If you are displaying data columns using a Select query, the order in which you add them to the query determines the order they appear in the Results pane. Adding a data column to the query puts it rightmost in the Results pane.

If you are creating an Update, Insert, or Make Table query, the order in which you add data columns dictates the order in which the data is processed.

To control more precisely where a data column appears in the output or is used in queries, you can insert a data column between existing grid columns.

To add a data column to the grid

  • Drag the column name from the Diagram pane onto the Column column.

    –or–

  • Navigate to a blank cell at the bottom of the Columns column, and then choose the name of a column to add from the drop-down list.

To insert a data column in the grid

  1. Select the row by clicking the box to the left of the Column column.

  2. Press INSERT to insert a blank row.

  3. In the Column column, select the data column to use in the grid.

To remove a data column from the grid

  • Select the row containing the column by clicking the box to the left of the Column column, and then press DELETE. You can select and delete multiple rows at one time.

    The Query Designer removes the selected data column as an output column, sort column, and search condition for the query.

Reordering Grid Rows

The order in which columns appear in the Grid pane determines their order in the result set. The data column that is topmost in the grid appears leftmost in the result set. The bottom row in the grid contains the data column that appears rightmost in the result set.

If you are creating an Update or Insert query, the order in which you add data columns dictates the order in which the data is processed.

To control where a data column appears or is used, you can move the corresponding row in the Grid pane.

To reorder grid rows

  1. Select the row by clicking the button to the left of the row.

  2. Drag the row to the new location.

Tip You can also insert a data column into the grid at a specific location by inserting a blank row, and then specifying the data column to insert. For details, see "Adding and Removing Data Columns in the Grid Pane" earlier in this topic.


SQL Pane

The SQL pane displays the SQL statement for the current query. It is updated automatically as you build your query and reformatted to be easy to read.

In the SQL pane you can:

  • Create new queries by entering SQL statements.

  • Modify the SQL statement created by the Query Designer based on settings you make in the Diagram and Grid panes.

  • Enter statements that take advantage of features specific to the database you are using.

Note Be sure you know the rules for identifying database objects in the database you are using. For details about SQL Server, see Query Designer Considerations for SQL Server Databases. For details about Oracle, see Query Designer Considerations for Oracle Databases.

Entering Statements in the SQL Pane

You can edit the current query directly in the SQL pane. When you move to another pane, the Query Designer automatically formats your statement, and then changes the Diagram and Grid panes to match your statement.

Note You can enter optimizer hints for SQL statements, but the Query Designer might reformat them. For details about SQL Server, see Query Designer Considerations for SQL Server Databases. For details about Oracle, see Query Designer Considerations for Oracle Databases.

If your statement cannot be represented in the Diagram and Grid panes, and if those panes are visible, the Query Designer displays an error and then offers you two choices:

  • Return to the SQL pane and edit the statement.

  • Discard your changes and revert to the most recent version of the SQL statement.

If you return to the SQL pane and continue editing the statement, the Query Designer dims the other panes to indicate that they no longer reflect the contents of the SQL pane.

You can also use the SQL pane to enter SQL statements that cannot be represented graphically in the Query Designer. In such cases, the Query Designer displays the same behavior as it does when it detects an error — it dims the Diagram and Grid panes to indicate that they do not represent the current statement. You can continue to edit the statement and execute it as you would any SQL statement. For details about unsupported query types in SQL Server, see Query Designer Considerations for SQL Server Databases. For details about unsupported query types in Oracle, see Query Designer Considerations for Oracle Databases.

Note If you enter an SQL statement, but then make further changes to the query by changing the Diagram and Grid panes, the Query Designer rebuilds and redisplays the SQL statement. In some cases, this action results in an SQL statement that is constructed differently from the one you originally entered (though it will always yield the same results). This difference is particularly likely when you are working with search conditions that involve several clauses linked with AND and OR.


Results Pane

The Results pane shows the results of the most recently executed Select query. (The results of other query types are displayed in message boxes.)

In the Results Pane you can:

  • View the result set for the most recently executed Select query in a spreadsheet-like grid.

  • Edit the values in individual columns in the result set, add new rows, and delete existing rows. For details, see Editing Rows in the Results Pane.

If you change the query definition (for example, add another output column to the query), the Query Designer dims the Results pane to indicate that it no longer reflects the current query. However, you can still navigate in the Results pane grid to edit, add, or delete rows.

In this topic, you can find information about:

  • Viewing the Result Set

  • Navigating Through the Results Pane Grid

  • Resizing Grid Rows and Columns

  • Clearing the Results Pane

Viewing the Result Set

When you execute a Select query, the Query Designer displays the result set in the Results pane grid. The Query Designer fetches and displays results incrementally so that you can begin viewing data immediately and perform other tasks while the query is being executed.

The Query Designer uses these conventions when it displays data in the grid:

  • Columns containing no value display the word <NULL>.

  • Columns containing binary data display the word <Binary>. You cannot edit the contents of these of columns.

  • Columns containing long varchar-type data display up to 900 characters of data. If the data is longer, the cell displays <Long Text>.

  • Number, currency, time, and date information is formatted according to the options set in the Regional Settings dialog box in the Microsoft® Windows® Control Panel.

Navigating Through the Results Pane Grid

To see all of the result set, you can navigate through the Results pane grid. You can use commands on the shortcut menu in the Results pane. In addition, you can use keys or the mouse to navigate through the Results pane grid.

To navigate through the Results pane grid

  • Move from cell to cell using the mouse or by pressing TAB, the HOME or END keys, the arrow keys, or CTRL or SHIFT plus any of these keys. For details about how to navigate, see Navigating in the Query Designer.

    –or–

  • Use the vertical and horizontal scrollbars in the grid.

    –or–

  • Right-click to display the shortcut menu, and then choose First, Last, Next, or Previous, or choose Row to move to a specific row in the grid.

Resizing Grid Rows and Columns

If all of the data for a query does not fit on your screen, you can resize the grid rows and columns.

To resize grid rows

  • Move the mouse over the divider between grid rows in the leftmost column until it changes to a double-headed arrow, and then drag the row until it is the size you want. When you resize one row, all other rows are resized at the same time.

To resize a grid column

  • Move the mouse over the divider between grid column headers until it changes to a double-headed arrow, and then drag the grid column header until the column is the size you want or double-click to auto-size the column.

Note The width of the Results pane grid columns has no relationship to the width of the corresponding data columns. Resizing the Results pane grid column does not change the width of the data column in the table.

Clearing the Results Pane

If the Results pane grid contains out-of-date information, you can clear it.

To clear the Results pane grid

  • Right-click to display the shortcut menu, and then choose Clear Results.


Dialog Boxes

For information about the dialog boxes used by the Visual Database Tools, see the following topics:

Database Designer Dialog Boxes

Query Designer Dialog Boxes


Database Designer Dialog Boxes

Documentation is available for the following Database Designer user interface elements:

  • Choose Name Dialog Box

  • Column Selection Dialog Box

  • Create Relationship Dialog Box

  • Database Changes Detected Dialog Box

  • Datatype Change Required Dialog Box

  • Print Setup Dialog Box

  • Save Change Script Dialog Box

  • Save Dialog Box

  • Save Incomplete Dialog Box

  • Unsaved Changes Exist Dialog Box


Choose Name Dialog Box

Enables you to change the system-assigned name of a new table that has not yet been created in the database. This dialog box appears when you:

  • Right-click the Tables folder and choose New Table from the shortcut menu.

  • Right-click the database diagram background and choose New Table from the shortcut menu.

    –or–

  • Click the New Table button [image] on the toolbar.

Options

Enter a name for the table

Displays the system-assigned name of the table. Type a new name for the table in the text box.

OK

Creates the table in your database diagram with the name you specified. The table is created in the database when you save the table or diagram.

Cancel

Cancels the creation of the new table.

For more information about creating tables, see Adding a Table to a Database Diagram.


Create Relationship Dialog Box

Enables you to confirm the related columns and to set properties for a new relationship. This dialog box appears when you draw a relationship line between two tables in your database diagram.

Options

Relationship name

Displays the system-assigned name of the relationship. To rename the relationship, type a new name in the text box.

Primary key table

Shows the name of the primary key table in the relationship, followed by the columns that make up the primary key. You can select different columns to match the columns shown under Foreign key table.

Foreign key table

Shows the name of the foreign key table in the relationship, followed by the columns that make up the foreign key. You can select different columns to match the columns shown under Primary key table.

Check existing data on creation

Applies the constraint to existing data in the foreign key table when the relationship is created. An error message will notify you of any data that violates the constraint if this box is selected.

Enable relationship for INSERT and UPDATE

Applies the constraint when data is added to or updated in the foreign key table using these statements.

Enable relationship for replication

Copies the constraint whenever the foreign key table is copied to a different database.

OK

Creates the relationship in your database diagram and sets the properties you selected.

Cancel

Erases the relationship line from your database diagram. The relationship is not created.

For more information about creating relationships between tables, see Creating a Relationship Between Tables.


Column Selection Dialog Box

Enables you to change the Custom view for tables in the database diagram. Custom view shows only the column properties identified by the user. This dialog box appears when you right-click a table and then choose Modify Custom View from the shortcut menu.

Options

Available columns

Lists all columns existing in the selected database table. The columns listed here depend on the properties of the database table and the type of database. Highlight the desired column and use the arrow buttons to move the columns to the Selected columns box.

Selected columns

Displays the column properties currently defined for the Custom view. Add column properties you want to display and remove those that you do not want to display. Sort the column in this list to determine the order they will be displayed in the table.

Sort

Use the arrows to move highlighted columns up or down in the Selected columns list. The columns will be displayed in the table in the order shown in the Selected columns list.

Save as default

Replaces the current Custom view with the columns selected in this dialog box. If not selected, the column selection specified in the dialog box will be applied to the selected table in the database diagram.

OK

Creates the new Custom view. The selected table is redrawn to display those columns listed in the Selected columns box.

Cancel

Cancels the modification of Custom view.

For more information about Custom views, see Changing a Table View.


Database Changes Detected Dialog Box

Appears if you attempt to save a database diagram or selected tables but some of the database objects that will be affected by the save action are out of date with the database. Accepting the changes shown in this dialog box updates the database to match your diagram and overwrites other users' changes.

Options

Yes

Updates the database with all the changes shown in the list.

No

Cancels the save action.

Save Text File

Saves the list of database changes in a text file in the project directory and displays a message box with the fully qualified file name of the text file. This file provides a record of the changes you made.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the table or diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about saving database objects that have changed since you began working in the Database Designer, see Reconciling a Database Diagram with a Modified Database.


Datatype Change Required Dialog Box

Appears when you change the data type, length, scale, or precision of a column that participates in a relationship.

Options

Yes

Changes the data type property of the related columns shown in the list so that existing relationships are preserved.

No

Cancels the data type change and restores the previous data type to the column you just changed.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the table or diagram. You can discard any unsaved changes by closing all open diagrams without saving them.


Page Setup Dialog Box

Use this dialog box to specify printer settings, such as orientation, scale, and paper size, for a diagram. The print setup options you set for a diagram are saved with the diagram file. When you set the Print scale and Orientation options for the diagram, the page breaks for the diagram are automatically updated.

Options

Name

Specifies the name of the default printer and lists the printers that are set up on your computer.

Properties

Sets the options for the selected printer. The options available depend on the features of the printer.

Status

Shows information about the selected printer.

Type

Displays the model and make information for the selected printer.

Where

Displays the network path or serial port information for the selected printer.

Comment

Displays additional information about the selected printer.

Paper

Size

Specifies the size of the paper or envelope you want to use.

Source

Specifies where the paper you want to use is located in the printer. Different printer models support different paper sources, such as the upper tray, envelope feed, and manual feed.

Orientation

Portrait

Sets a taller-than-wide layout for the document on the page.

Landscape

Sets a wider-than-tall layout for the document on the page.

Print Scale

Percent

Sets the size of the diagram based on the settings as applied to a 100-percent diagram. Choose a percentage between 10 and 400.


Save Change Script Dialog Box

Displays a change script whenever there are unsaved database changes in your table or database diagram and enables you to save the change script as a text file with an .sql extension in the project directory. This dialog box appears when you choose Save Change Script from the File menu or click the Save Change Script button [image] on the Database Designer toolbar. If you have selected to have a change script created automatically each time you save, this dialog box will not appear whenever you save your database diagram.

Options

Yes

Saves the SQL change script in the project directory. A message box will appear indicating where the change script file has been saved.

No

Cancels the save action.

Automatically generate change script on every save

Select this option to create a change script each time you save the database diagram or selected tables. This provides a record of all changes made to the database.

For more information about saving SQL change scripts, see Saving a Change Script.


Save Dialog Box

Appears when you attempt to save a database diagram or selected tables, enabling you to confirm the tables that will be saved. This dialog box does not appear when your diagram contains only one modified table.

Options

Yes

Saves all the tables shown in the list.

No

Cancels the save action.

Save Text File

Saves the list of tables in a text file in the project directory and displays a message box with the fully qualified file name of the text file. This file provides a record of the tables that were affected by the changes you made.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the table or diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about the effects of saving tables and diagrams, see Controlling Database Changes.


Save Incomplete Dialog Box

Appears when errors have been encountered while you were trying to save a database diagram or selected tables. This dialog box lists the following: the objects that were successfully saved in the database, the objects that were not saved, and the errors that were encountered.

Options

OK

Returns to the diagram.

Save Text File

Saves the information shown in a text file in the project directory and displays a message box with the fully qualified file name of the text file. This file provides a record of the database changes that were successfully saved as well as the changes that could not be saved due to errors.

For more information about the errors that can occur, see:

  • Error modifying column properties

  • Invalid cursor state

  • Unable to add constraint

  • Unable to create index

  • Unable to create relationship

  • Unable to modify table

  • Unable to preserve trigger

If the error you want to troubleshoot does not appear in this list, see System errors for additional messages returned by Microsoft® SQL Server™.

Error modifying column properties

Appears when your constraint expression contains an error.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]The name '[column value]' is illegal in this context. Only constants, constant expressions, or variables allowed here. Column names are illegal.

Cause

A default value defined for a character column is not enclosed in single quotation marks (').

Recommended solution

Enclose the value in single quotation marks in the database column's Default Value cell. and then save the table.

Invalid cursor state

Appears when Microsoft® SQL Server™ runs out of resources while attempting to save selected tables or a database diagram.

ODBC error text

[Microsoft][ODBC SQL Server Driver]Invalid cursor state.

Cause

There is insufficient space in your database or transaction log to complete the save process.

Recommended solution

Check to see if the database or the transaction log is full. If so, increase the size of the database to accommodate the change. Check other system resources or contact your System Administrator.

For more information about increasing the size of your database, see "Expanding or Shrinking Databases" in SQL Server Books Online.

Unable to add constraint

Appears when a new constraint has failed on existing data or your constraint expression contains an error. Compare the ODBC error text that appears in the Save Incomplete dialog box with the error text shown below to determine the appropriate solution.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Data exists in table '[table name]', database '[database name]', that violates CHECK constraint '[constraint name]' being added. ALTER command has been aborted.

[Microsoft][ODBC SQL Server Driver][SQL Server]Unable to create constraint. See previous errors.

Cause

Existing data does not match the check constraint.

Recommended solution

Change the data (for example, by using Query Designer) to match the constraint. For details, see Query Designer.

-or-

Clear the Check existing data on creation check box in the Tables property page for the check constraint in question. For more information about disabling this property, see Checking Existing Data when Creating a Relationship.

-or-

Change the constraint expression in the Tables property page for the check constraint in question.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column '[column name]' specified in constraint definition.

[Microsoft][ODBC SQL Server Driver][SQL Server]Unable to create constraint. See previous errors.

Cause

The text value in the check constraint expression on the Tables property page is not enclosed in single quotation marks (').

-or-

A column that participates in the check constraint has been renamed. For example, if the original constraint had the expression (cityname = 'Paris') and you renamed the column to city, you would see the same error except that 'cityname' would be the invalid column shown in the error message.

Recommended solution

Correct the expression and save the table.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Line [line number]: Incorrect syntax near '[operator]'.

Cause

The expression defined for the check constraint (in the Tables property page) or the default constraint (in the Default Value cell) is not valid SQL syntax. For example, the check constraint expression 'city equals Paris' was typed instead of 'city = Paris'.

Recommended solution

Correct the expression and save the table.

For more information about constraints, see Constraints.

Unable to create index

Appears when a new index has failed on existing data.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Create unique index aborted on duplicate key. Primary key is '[primary key data]'

[Microsoft][ODBC SQL Server Driver][SQL Server]Unable to create constraint. See previous errors.

Cause

A unique index was created in the Indexes/Keys property page but duplicate data exists in the database. The value after the phrase "Primary key is" is the first duplicate value that Microsoft® SQL Server™ found as it created the index.

Recommended solution

Remove duplicate data from the database (for example, by using Query Designer). For more information, see Designing Queries.

-or-

Change the option in the Indexes/Keys property page to allow duplicate rows in the index.

For more information about creating unique indexes, see Creating a Unique Index.

Unable to create relationship

Appears when a new constraint has failed on existing data.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Data exists in table '[table name]', database '[database name]', that violates FOREIGN KEY constraint '[constraint name]' being added. ALTER command has been aborted.

[Microsoft][ODBC SQL Server Driver][SQL Server]Unable to create constraint. See previous errors.

Cause

Existing data fails the foreign key constraint.

Recommended solution

Change the data that fails the foreign key constraint by running a query to show all the foreign key values that do not match primary key values. For example, to find foreign key values in the job_id column of the employee table that do not match primary key values in the jobs table, run a query with this SQL syntax:

SELECT  employee.emp_id, employee.job_id
FROM  employee LEFT OUTER JOIN jobs ON employee.job_id = jobs.job_id
WHERE (jobs.job_id IS NULL)

For more information, see Creating Queries.

-or-

Clear the Check existing data on creation check box in the Relationships property page. For more information, see Checking Existing Data when Creating a Relationship.

Unable to modify table

Appears when a new constraint has failed on existing data. Compare the ODBC error text that appears in the Save Incomplete dialog box with the two ODBC errors shown below to determine the appropriate solution.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]The column [column name] in table Tmp_ [table name] may not be null.

Cause

A new database column has been added that doesn't allow null values and doesn't provide a default value. The table name in question appears after "Tmp_".

Recommended solution

Change the column properties. Either select the Allow Nulls property or type a Default Value setting. For more information about setting properties for database columns, see Column Properties.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Attempt to insert the value NULL into column '[column name]', table '[database name] TMP_ [table name]'; column does not allow nulls. INSERT fails.

[Microsoft][ODBC SQL Server Driver][SQL Server]Command has been aborted.

Cause

The Allow Nulls property on an existing database column has been cleared, but the column has existing null values in it. The table name in question appears after "TMP_".

Recommended solution

Go to the column and select the Allow Nulls property.

For more information about setting properties for database columns, see Column Properties.

Unable to preserve trigger

Appears when your trigger text references a column that has been renamed, deleted, or assigned a different data type.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid column name '[column name]'.
- Unable to preserve trigger '[trigger name]'.

Cause

A change to the table required the table to be recreated. When a table is recreated, the triggers attached to that table are automatically recreated as well.

Recommended solution

The recommended solution depends on the type of change made to the column referenced by the trigger.

To preserve a trigger that references a renamed column

  • Rename the column to its original name and then save the table. This action will allow the table to be recreated. You can now rename the column, save the table again, and then edit the trigger to fix the renamed columns.

To preserve a trigger that references a deleted column

  1. Expand the table that the trigger is attached to.

  2. Right-click the trigger you want to change and choose Open from the shortcut menu.

  3. Edit the trigger text and save the trigger.

  4. Save the table or database diagram.

To preserve a trigger that references a column whose data type changed

  1. In your database diagram, click the Save Change Script button [image] in the Database Diagram toolbar. For more information, see Saving a Change Script.

  2. Open the change script.

  3. In Data View, expand the table that the incorrect trigger is attached to.

  4. Delete the incorrect trigger. For details, see Deleting a Trigger.

  5. Create a new trigger for the table. For details, see Creating a Trigger.

  6. In the change script, select the trigger text. The set of statements that creates the trigger begins with a CREATE TRIGGER statement.

  7. Copy the selected text into the Trigger window.

  8. On the toolbar, click the Save button. This action saves the trigger in the database and adds the trigger to the table in the Tables folder.

  9. Repeat steps 3 through 8 for each trigger you want to recreate.

For more information about triggers, see Triggers and your database documentation.

System errors

Two system errors can appear in the Save Incomplete dialog box when you exceed Microsoft® SQL Server™ limitations that are not controlled by the Database Designer.

ODBC error text

[Microsoft][ODBC SQL Server Driver][SQL Server]Can't allocate space for object 'Syslogs' in database 'Guest' because the 'logsegment' segment is full. If you ran out of space in Syslogs, dump the transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase the size of the segment.

Cause

This error occurs because there is insufficient log space to complete the transaction.

Recommended solution

Follow the recommendation in the message and delete the transaction log. (Typically this action will not entirely solve the problem.)

-or-

Increase the size of the database to accommodate the change. With large databases, changes that require the recreation of tables (for example, changing a column data type or size) may not be possible using the Database Designer. You may need to use methods of transferring data that don't require transactions, such as BCP.

ODBC error text

[Microsoft][ODBC SQL Server Driver]Timeout expired.

Cause

The timeout can occur when you're updating the database with any Transact-SQL changes.

Recommended solution

Try again later to save the diagram or selected tables.

-or-

Save a change script and apply it to the database at a later time. For more information, see Saving a Change Script.

-or-

Increase the SQL Query Time-out value and try to save the diagram or selected tables again.

To increase the SQL Query Time-out value

  1. From the Tools menu, choose Options.

  2. In the left pane, click Data Tools, and then click Data View.

  3. Type a new value in the SQL query time-out box.

For additional information about Microsoft SQL Server errors, see SQL Server Books Online.


Unsaved Changes Exist Dialog Box

Appears if you attempt to close the last table of a database diagram or the diagram itself in the Database Designer when there are unsaved tables in memory.

Options

Yes

Saves all the tables shown in the list.

No

Closes the diagram without saving the changes.

Save Text File

Saves the list of unsaved tables in a text file in the project directory and displays a message box with the fully qualified file name of the text file. This file provides a record of the tables that were affected by the changes you made.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the table or diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about canceling unsaved changes that exist in memory, see Rolling Back Unsaved Database Changes.


Query Designer Dialog Boxes

Documentation is available for the following Database Designer user interface elements:

Database Changes Detected Dialog Box

Define Query Parameters Dialog Box

Delete Table Dialog Box

Go To Row Dialog Box

Insert Into Table Dialog Box

Insert Values Dialog Box

Make Table Dialog Box

Query Definitions Differ Dialog Box

Returning Query Results Dialog Box

Returning Query Results (Edit) Dialog Box

SQL Syntax Errors Encountered Dialog Box

Update Table Dialog Box


Database Changes Detected Dialog Box

Notifies you that the data row you are editing in the Results pane is no longer current. This dialog box appears when you attempt to save changes to a row by moving to another row in the Results pane and the Query Designer determines that the corresponding row in the database has changed. This situation occurs most often when another user has edited the row and saved the changes since you executed your query.

The dialog box displays a message asking how you want to proceed.

Options

Yes

Choose this button to specify that you want to save your changes and overwrite the changes made by the other user.

No

Choose this button to discard the changes you have made and fetch the most current version of the row. The Query Designer returns you to the Results pane after rereading the row from the database.

Cancel

Choose this button to return to the Results pane without saving the row and without discarding your changes. If you choose this option, you can attempt to save the row again or make further changes, such as matching your edits to the version of the row in the database.

Tip To see the most current version of the row without discarding your changes, execute a second query against the data you are editing.


Define Query Parameters Dialog Box

Allows you to enter values for the parameters defined in the query. This dialog box appears when you execute a query that contains parameters to be filled in at run time.

Options

Parameter name

Lists the parameters defined for the query being executed. If the query contains named parameters, the names appear in the list. If the query contains unnamed parameters, a question mark appears for each parameter in the query.

Parameter value

Enter the value for each parameter listed under Parameter name. The value used most recently appears as the default parameter value.


Delete Table Dialog Box

Allows you to specify the table to delete rows from. This dialog box appears if more than one table is displayed in the Diagram pane when you start a Delete query.

Select the table to delete rows from, and then choose OK.

Note A Delete query removes entire rows from the table. If you want to clear values from individual data columns, use an Update query. If you want to delete columns from a table definition, or delete the table itself, use the Database Designer or the database design tools for your database.


Go To Row Dialog Box

Allows you to navigate to a specific row in the Results pane. This dialog box appears when you right-click in the Results pane and choose Row.

Options

Row

Enter the row number of the row you want to navigate to. If the query has finished fetching query results, the total number of rows in the result set is displayed. If you enter a number higher than the total number of rows in the result set, the Query Designer moves to the last row.


Insert Into Table Dialog Box

Allows you to specify a table to insert new rows into. This dialog box appears when you start an Insert query.

Options

Append to:

Table name

Select from the list the name of the table to add rows to. You can specify only one table for the Insert query.

Note You can change the table to insert rows into in the Properties window. For details, see Query Tab, Properties Window.


Insert Values Dialog Box

Allows you to specify the table to add a row to. This dialog box appears if more than one table is displayed in the Diagram pane when you start an Insert Values query.

Select the table to add a row to, and then choose OK.


Make Table Dialog Box

Allows you to name a table that will be created and that you will copy rows to. This dialog box appears when you start a Make Table query.

Options

Make

Table Name

Type the name of the table to create. The Query Designer does not check whether the name is already in use or whether you have permission to create the table.

To create a destination table in another database, specify a fully qualified table name, including the name of the target database, the owner (if required), and the name of the table.

Note Before you execute the query you can change the table to create in the Property Pages window. For details, see Query Tab, Properties Window.


Returning Query Results (Edit) Dialog Box

Notifies you that the Query Designer cannot save changes to the row you have edited because a query is still in progress. This dialog box appears when you execute a query, and then before the query has been completed, you edit a row in the Results pane and attempt to save it by moving to another row in the grid.

When working with some databases, the Query Designer waits until the query is finished before it saves the row you have edited and moves to the requested row. To help you estimate how long you must wait, the dialog box displays a progress counter.

Cancel

Choose this button to specify that you want to cancel your attempt to move to another row. The Query Designer returns you to the row you have edited, and you can save the changes later when the query is complete.

If you do not choose Cancel, the Query Designer saves your changes after the query has finished.


Returning Query Results Dialog Box

Notifies you that the Query Designer cannot perform the requested action because a query is still in progress. This dialog box appears when you have executed a query, and then before the query has been completed, you attempt one of the following operations:

  • To go to a result-set row that has not yet been returned.

  • To insert a new row in the Results pane.

  • To delete one or more rows in the Results pane.

  • To use the Copy command to place selected columns on the Clipboard.

Cancel

Cancels the attempted operation and leaves you at the row you were on when you requested the operation.


Query Definitions Differ Dialog Box

Notifies you that your query cannot be represented graphically in the Diagram and Grid panes and that you will be able to edit your query only in the SQL pane. This dialog box appears when you enter or edit an SQL statement in the SQL pane; and then switch to another pane, verify the query, or attempt to execute the query; and one of the following conditions applies:

  • The SQL command is incomplete or contains one or more syntax errors.

  • The SQL command is valid but is not supported in the graphical panes (for example, a Union query).

  • The SQL command is valid but contains syntax specific to the data connection you are using.

    Tip You can check whether a statement is valid using the Verify SQL Statement button on the Query toolbar.

The dialog box displays a message with the reason that the SQL statement cannot be represented, and then asks how you want to proceed.

Note The Query Definitions Differ dialog box does not appear if you have hidden the Diagram and Grid panes, because the Query Designer assumes that you are editing only in the SQL pane.

Options

Yes

Choose this button to specify that you want to accept the SQL statement, either to edit it further or to execute it. If you accept the statement, the Query Designer dims the Diagram and Grid panes to indicate that they do not represent the statement in the SQL pane.

Note If the statement is correct but not supported graphically by the Query Designer, you can execute it even though it cannot be represented in the Diagram and Grid panes. For example, if you enter a Union query, the statement can be executed but not represented in the other panes.

No

Choose this button to discard the changes in the SQL pane and revert to the most recent SQL statement that can be represented in the Diagram and SQL panes.


SQL Syntax Errors Encountered Dialog Box

Notifies you that the Query Designer cannot parse the SQL statement in the SQL pane. This dialog box appears when you enter or edit an SQL statement in the SQL pane; and then switch to another pane, verify the query, or attempt to execute the query; and one of the following conditions applies:

  • The SQL command is incomplete or contains one or more syntax errors.

  • The SQL command is valid but is not supported in the graphical panes (for example, a Union query).

  • The SQL command is valid but contains syntax specific to the data connection you are using.

Tip You can check whether a statement is valid using the Verify SQL Statement button on the Query toolbar.

The dialog box displays a message with the reason that the SQL statement cannot be parsed. Choose OK to proceed.

Tip If you suspect that your SQL statement contains errors, choose the Verify SQL Syntax button on the Query toolbar to check the statement.


Update Table Dialog Box

Allows you to specify the table to be updated. This dialog box appears if more than one table is displayed in the Diagram pane when you start an Update query.

Select the table to update, and then choose OK.


Properties Pages

For information about the properties pages used by the Visual Database Tools, see the following topics:

Database Designer Properties Pages

Query Designer Properties Pages


Database Designer Properties Pages

The Database Designer provides property pages where you can set options that affect the database objects in your database diagram.

To | See
Set properties for database tables, including attaching constraints to the table or table columns | Tables Property Page
Set properties for relationships between tables, including choosing primary and foreign keys for the relationship | Relationships Property Page
Set properties for indexes, primary keys, and unique constraints attached to a table | Indexes/Keys Property Page


Indexes/Keys Property Page

This property page contains a set of properties for the indexes, primary keys, and unique constraints attached to the tables in your database diagram. Indexes and constraints are not graphically represented in database diagrams.

Options

Selected index

Shows the name of the first index for the selected table in your diagram. If more than one table is selected in your diagram, only the name of the first index for the first table is visible. To choose a different index to show properties for, expand the Selected index drop-down list.

Type

Shows the index/key object type for the selected table: index, primary key, or unique.

New

Choose this button to create a new index for the selected database table. Enter properties for the index. For more information, see Creating an Index.

Delete

Choose this button to remove the selected index from the table. For more information, see Deleting an Index.

Note You cannot delete a primary key without removing any relationships between tables dependent upon the primary key.

Column name

Shows the list of columns in the index, primary key, or unique constraint. You can add, change, or remove column names in this list.

Index name

Shows the name of the selected index. You can rename the index by entering a new name in this box. For more information, see Renaming an Index.

Create UNIQUE

Select this option to create a unique constraint or index for the selected database table. Specify whether you are creating a constraint or index by selecting either the Constraint or Index button.

  • Ignore duplicate key If you create a unique index, you can set this option to ensure each value in an indexed column is unique.

Fill factor

Shows the fill factor that specifies how full each index page can be. If a fill factor is not specified, the database’s default fill factor is used. For more information, see Specifying a Fill Factor for an Index.

Create as CLUSTERED

Select this option to create a clustered index for the selected database table. For more information, see Creating a Clustered Index.

Sort Data Options

Identify how the data is ordered in the index as records are added to the index.

  • Sort data (the default) Organizes data in ascending order.

  • Data already sorted Accepts the order of existing data.

  • Reorganize sorted data Reorganizes the data in ascending order. Select this option, for example, when the table becomes fragmented or to rebuild nonclustered indexes.

Duplicate Row Options

Identify how the index should handle duplicate rows.

  • Disallow duplicate rows (the default) Prevents the index from being saved if duplicate rows exist. If duplicate rows exist, an error message will appear.

  • Ignore duplicate rows Deletes duplicate rows from the index as it is being created.

  • Allow duplicate rows Creates the index, even though duplicate rows exist.


Relationships Property Page

This property page contains a set of properties for the relationships between the tables in your database diagram.

Options

Selected relationship

Shows the name of the selected relationship in your diagram. If more than one relationship is selected in your diagram, only the name of the first relationship in your selection is visible. Expand the list to choose a different relationship to show properties for.

Relationship name

Shows the name of the selected relationship. You can rename the relationship by entering a new name in this box. For more information, see Renaming a Relationship.

Primary key table

Shows the name of the primary key table in the relationship, followed by the columns that make up the primary key. For information about changing the primary key, see Modifying a Primary Key.

Foreign key table

Shows the name of the foreign key table in the relationship, followed by the columns that make up the foreign key. For information about changing the foreign key, see Modifying a Foreign Key.

Check existing data on creation

Applies the constraint to data that already exists in the database when the relationship is added to the foreign key table.

Enable relationship for INSERT and UPDATE

Applies the constraint to data that is inserted into or updated in the foreign key table. Also prevents a row in the primary key table from being deleted when a matching row exists in the foreign key table.

Enable relationship for replication

Applies the constraint when the foreign key table is copied to a different database.


Tables Property Page

This property page contains a set of properties for the tables in your database diagram and their check constraints.

Selected table

Shows the name of the selected table in your diagram. If more than one table is selected in your diagram, only the name of the first table in your selection is visible. Expand the list to choose a different table to show properties for.

Table name

Shows the name of the selected table. To rename the table, enter a new name in this box. For more information, see Renaming a Table.

Check constraints for table and columns

You can add or edit a check constraint in this dialog box. For more information about adding check constraints, see Attaching a New Check Constraint to a Table or Column.

  • Selected constraint Shows a list of the check constraints attached to the selected table.

  • New Creates a new check constraint for the selected table.

  • Delete Deletes the selected check constraint from the database.

  • Constraint expression Shows the SQL syntax of the selected check constraint. For new constraints, you must enter the SQL syntax before exiting this box. You can also edit existing check constraints. For more information, see Defining a Check Constraint Expression.

  • Constraint name Shows the name of the selected constraint. You can rename the constraint by entering a new name in this box.

  • Check existing data on creation When selected, this option ensures that all data that exists in the table before the constraint was created is verified against the constraint.

  • Enable constraint for INSERT and UPDATE Applies the constraint when data is inserted into or updated in the table.

  • Enable constraint for replication Applies the constraint when the table is copied in a different database.


Query Designer Properties Pages

Query Designer provides property pages to set options that affect the how queries will be executed against your database.

To | See
Control the behavior of your query by setting its properties using the Query Designer | Query Tab, Properties Window (Query Designer)
Control the behavior of your query by setting its properties using the View Designer | Query Tab, Properties Window (View Designer)
Mark parameters in your query with special characters | Parameters Tab, Properties Window
Specify options for the joining of tables in a multitable query | Join Line Tab, Properties Window


Query Tab, Properties Window (Query Designer)

Contains options for controlling the behavior of the query you are building or modifying.

Options

Query name

Displays the name for the current query. You cannot change the query name in this box. To assign a new name, use the Save As command from the File menu.

Output all columns

Specifies that all columns from all tables in the current query will be in the result set. Choosing this option is equivalent to specifying an asterisk (*) in place of individual column names.

DISTINCT values

Specifies that the query will filter out duplicates in the result set. This option is useful when you are using only some of the columns from a table and those columns might contain duplicate values, or when the process of joining two or more tables produces duplicate rows in the result set. Choosing this option is equivalent to inserting the word DISTINCT into the statement in the SQL pane.

Destination table

Specifies the name of the table into which you are inserting rows. This list appears if you are creating an Insert query or Make Table query. For an Insert query, select a table name from the list.

For a Make Table query, type the name of the table to create. The Query Designer does not check whether the name is already in use or whether you have permission to create the table. To create a destination table in another database, specify a fully qualified table name, including the name of the target database, the owner (if required), and the name of the table.

GROUP BY extension

Specifies that additional options for views based on aggregate queries are available. These options are available only for Microsoft® SQL Server™.

WITH CUBE

(Microsoft SQL Server only.) Specifies that the aggregate query should produce summary values for groups specified in the GROUP BY clause. The groups are created by cross-referencing columns included in the GROUP BY clause, and then applying the query's aggregate function to produce summary values for the additional super-aggregate rows. The With CUBE option is multidimensional, creating summaries from all combinations of aggregate functions and columns in the query.

WITH ROLLUP

(Microsoft SQL Server only.) Specifies that the aggregate query should produce summary values for the groups specified in the GROUP BY clause. The With ROLLUP option is similar to the With CUBE option, but creates only one type of summary for each combination of column and aggregate function.

ALL

(Microsoft SQL Server only.) Specifies that the aggregate query will include any duplicate rows in the summary.


Query Tab, Properties Window (View Designer)

Contains options for controlling the behavior of the view you are building or modifying.

Options

View name

Displays the name for the current query. If you have not yet saved your view, the default name is displayed. You cannot change the name in this box. To assign a name, use the Save or Save As commands from the File menu.

Output all columns

Specifies that all columns from all tables currently displayed will be in the view. Choosing this option is equivalent to specifying an asterisk (*) in place of individual column names.

DISTINCT values

Specifies that the query will filter out duplicates in the view. This option is useful when you are using only some of the columns from a table and those columns might contain duplicate values, or when the process of joining two or more tables produces duplicate rows in the result set. Choosing this option is equivalent to inserting the word DISTINCT into the statement in the SQL pane.

Encrypt view

(Microsoft SQL Server only.) Encrypts the view when you save it. You will continue to be able to work with the view until you close the View Designer.

Important After you close an encrypted view, you will no longer be able to open it in the View Designer.

GROUP BY extension

(Microsoft SQL Server only.) Specifies that additional options for views based on aggregate queries are available.

WITH CUBE

(Microsoft SQL Server only.) Specifies that the aggregate query should produce summary values for groups specified in the GROUP BY clause. The groups are created by cross-referencing columns included in the GROUP BY clause, and then applying the query's aggregate function to produce summary values for the additional super-aggregate rows. The With CUBE option is multi-dimensional, creating summaries from all combinations of aggregate functions and columns in the query.

WITH ROLLUP

(Microsoft SQL Server only.) Specifies that the aggregate query should produce summary values for the groups specified in the GROUP BY clause. The With ROLLUP option is similar to the With CUBE option, but creates only one type of summary for each combination of column and aggregate function.

ALL

(Microsoft SQL Server only.) Specifies that the aggregate query will include any duplicate rows in the summary.


Parameters Tab, Properties Window

Specifies options for marking parameters in the query.

To include a parameter in a query, you must mark the parameter using special characters so that the Query Designer does not mistake your parameter name for text data. For example, if you specify square brackets ( [ and ] )as parameter markers, you can enter a parameter by specifying a search expression such as the following:

= [last_name]

When you run the query, the Query Designer prompts you for a value, and then substitutes the value you provide for the parameter last_name.

For more information about using parameters in queries, see Parameter Queries.

Options

Prefix characters

Specifies the character or characters that mark the beginning of a parameter.

Suffix characters

Specifies the character or characters that mark the end of a parameter.

Escape character

Specifies an escape character that is used to indicate that a parameter marker character in a name is meant literally. For example, if you specify "%" as a parameter marker, you would not normally be able to include that character in a parameter name such as "% complete." However, you can specify "\" as an escape character, and then use the following string as the parameter name:

%\% complete%

Tip To create parameter prompts that function like those in Microsoft® Access, set the prefix character to "[" and the suffix character to "]".


Join Line Tab, Properties Window

Specifies options for the joining of tables in a multitable query.

By default, related tables are joined using an inner join that creates a result set based on rows containing matching information in the join columns. By setting options in the Join Line tab, you can specify a join based on a different operator, and you can specify an outer join.

For more information about joining tables, see Querying Using Multiple Tables.

Options

Table

The names of the tables involved in the join. You cannot change the names of the tables here — this information is displayed for information only.

Column

The names of the columns used for joining the tables. The operator in the Operator list specifies the relationship between the data in the columns. You cannot change the names of the tables here — this information is displayed for information only.

Operator

Specifies the operator used to relate the join columns. To specify an operator other than equal (=), select it from the list. When you close the dialog box, the operator you selected will appear in the diamond graphic of the join line, as in the following diagram:

Include rows

Specifies whether unmatched rows appear in the Results pane.

All rows from <table1>

Specifies that all the rows from the left table appear in the output, even if there are no corresponding matches in the right table. Columns with no matching data in the right table appear as null. Choosing this option is equivalent to specifying LEFT OUTER JOIN in the SQL statement.

All rows from <table2>

Specifies that all the rows from the right table appear in the output, even if there are no corresponding matches in the left table. Columns with no matching data in the left table appear as null. Choosing this option is equivalent to specifying RIGHT OUTER JOIN in the SQL statement.

Selecting both options is equivalent to specifying FULL OUTER JOIN in the SQL statement.

Note Some databases, such as Oracle, do not support full outer joins. For details, see Query Designer Considerations for Oracle Databases.

When you select an option to create an outer join, the diamond graphic in the join line changes to indicate that the join is a left outer, right outer, or full outer join.

Note The words "left" and "right" do not necessarily correspond to the position of tables in the Diagram pane. "Left" refers to the table whose name appears to the left of the keyword JOIN in the SQL statement, and "right" refers to the table whose name appears to the right of the JOIN keyword. If you move tables in the Diagram pane, you do not change which table is considered left or right.


Troubleshooting Error Messages

You may encounter message boxes while using the Microsoft® Visual Database Tools. For more information about those messages, browse the following topics.

Database Designer Troubleshooting Errors

Query Designer Troubleshooting Errors

Note The Visual Database Tools are dependent upon many other applications and components. If you receive an error message not listed in the Visual Database Tools documentation, search your product documentation and your server documentation.


Database Designer Troubleshooting Errors

Error messages may occur during the process of saving a database diagram or selected tables in a diagram. For more information about those messages, see the Save Incomplete dialog box.

For information about additional Visual Database Tools error messages, see Query Designer Troubleshooting Errors.

Note The Visual Database Tools are dependent upon many other applications and components. If you receive an error message not listed in the Visual Database Tools documentation, search your product documentation and your server documentation as well.


A pair of matching columns is required to create a relationship.

You must select matching columns from both tables participating in a foreign key relationship. The columns you have selected don’t match, so they cannot be related.

Choose two columns that match, then attempt to establish the relationship. In order to match, there must be the same number of columns and each partner in a pair of columns must have a comparable data type.

For more information, see Foreign Key and Creating a Relationship Between Tables.


A primary key can't be created on column '<0s>' because it allows null values.

The primary key is used to relate the table to foreign keys in other tables. All columns participating in a primary key must contain defined values other than NULL.

To create a primary key on the selected column, first clear the Allow Nulls check box for the column.

For more information, see Primary Key and Changing the Null Option Assigned to a Column.


A primary key or index cannot be created on columns with a datatype of <0s>.

A column’s datatype defines what kind of information can be stored in a column. Some datatypes such as TEXT or Image cannot be used in an index because servers will not allow indexes on these types of data.

For more information, see Indexes, Creating a Unique Index, and Defining a Primary Key.


A primary key or index cannot have more than <0d> columns.

Microsoft® SQL Server™ does not allow more than 16 columns in an index. Because a primary key has an associated index, there can be no more than 16 columns in a primary key.

For more information, see Indexes and Defining a Primary Key.


A primary key or unique constraint must be defined for table '<0s>' before it can participate in a relationship.

In order to create a foreign key relationship, at least one of the two tables must have a primary key or unique constraint defined. To create the relationship you are attempting to create, first create a primary key for one of the tables.

For more information, see Defining a Primary Key and Creating a Relationship Between Tables.


A relationship cannot contain more than '<0d>' columns.

Select fewer than 16 columns when defining the foreign key relationship.

For more information, see Creating a Relationship Between Tables.


An index already exists for table '<0s>' with the columns '<1s>'.

Oracle only allows one index for each ordered set of columns.

As a rule, you should create an index only if the data in the selected columns will be queried frequently. Indexes take up disk space and can slow the adding, deleting, and updating of rows.

In most cases, the benefits of indexes will far outweigh the performance overhead, but if your application updates data very frequently, or if you have disk space constraints, you might also want to limit the number of indexes.

For more information, see Indexes and Creating an Index.


An index can't exist on a blank column.

An index must contain at least one column, and that column must contain unique data values if you are creating a unique index. The column names selected must be entered under Column name in the Selected index box.

For more information, see Indexes and Creating an Index.


Are you sure you want to delete the current selection from your database?

This will permanently delete the table and all its data from your database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to permanently delete table '<0s>' from your database?

This will permanently delete the table and all its data from the database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to permanently delete the selected tables from your database?

The table and all its data will be deleted from the database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to remove the selected table from the diagram?

This will remove the table from the diagram but leave the table in the database.

For more information, see Removing a Table from a Database Diagram.


Are you sure you want to remove the selected tables from the diagram?

This will remove the table from the diagram, but not from your database.

For more information, see Removing a Table from a Database Diagram.


Both sides of a relationship must have the same number of columns.

When creating a composite foreign key relationship, both sides of the relationship must have the same number of columns. Make sure the number of columns you’ve selected matches the number of columns in the target table.

For more information, see Creating a Relationship Between Tables.


Column '<1s>' in table '<0s>' participates in index '<2s>'. Columns with a datatype of '<3s>' cannot participate in indexes or primary keys.

You have attempted to change the datatype of a column that is part of an index or a primary key. Indexes and primary keys cannot be created for columns with datatypes such as TEXT or IMAGE. To change the datatype, first remove the index or primary key.

For more information see Indexes, Creating a Unique Index, and Defining a Primary Key.


Editing this default will permanently unbind the named default.

Changing from a named default to a default constraint is not allowed on Microsoft® SQL Server™. Refer to the Microsoft SQL Server online documentation for more information.


Identity column '<0s>' in table '<1s>' must have a datatype of int, smallint, tinyint, decimal or numeric with scale of 0.

Only certain datatypes can be used for Identity columns. Columns that are Identity columns contain system-generated, sequential values that uniquely identify each row within a table.

For more information, see Changing a Column’s Identity Properties.


Invalid name. You must provide a name for this object.

An object name is required to continue. Valid names begin with an underscore (_) or a character and contain a combination of characters, numbers, and underscores.

The maximum length for a name based on the server is 32 for Microsoft® SQL Server™ 6.5 and earlier and 32 for Oracle.

In general, avoid names that contain periods.

For more information, see Uniquely Naming Database Objects.


ODBC error: <Os>

An ODBC error has been generated. You might have deleted a record that has a foreign key value related to it, or you might have violated a check constraint.

For details, refer to your ODBC documentation.


One or more selected tables are already on the diagram.

You can only have one copy of any table on a diagram. If you want to create a new table that has some of the same columns as an existing table, you can duplicate an existing table as the first step in creating a new table.

For more information, see Duplicating Tables.


Only one clustered index can be created on table '<0s>'.

A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore only one clustered index can be created on each table.

To create a second index on the same table, change the Clustered property setting before creating the second index.

For more information, see Indexes and Creating a Clustered Index.


Only one ROWGUID column is allowed per table.

You have attempted to assign more than one ROWGUID. The ROWGUID is a special property similar to IDENTITY and only one ROWGUID is allowed per table.

For more information, see Setting Column Properties.


Relationship '<0s>' was modified or deleted since the diagram was loaded.

A modified relationship is about to be saved. It is possible that a table involved in the relationship has been deleted from the database by another user.

Verify whether this relationship is meant to be modified. Changing or deleting a relationship for a table may affect other tables.

For more information about relationships, see Table Relationships and Deleting a Relationship.


Table '<0s>' is marked for deletion and was not added to the diagram.

A table that has been removed from the diagram will be deleted from the diagram when the changes are saved. The table will not, however, be deleted from the database.

For more information, see Removing a Table from a Database Diagram.

-or-

The table has been deleted from the database by another user and cannot be added to your diagram.

For more information, see Deleting a Table from a Database Diagram and the Database.


Table '<0s>' no longer exists in the database.

The table has been deleted from the database and cannot be used in your diagram.

For more information, see Deleting a Table from a Database Diagram and the Database.


The Allow Nulls property can't be set on a column that is part of the primary key.

All columns that are part of a table’s a primary key must contain aggregate unique values other than NULL. To add the column to a primary key, first clear the Allow Nulls check box on the Column Property dialog box.

For more information, see Changing the Null Option Assigned to a Column.


The Allow Nulls property can't be set on column '<0s>' because it is an identity column.

All identity columns must contain unique values other than NULL. To make the column an identity column, first clear the Allow Nulls check box on the Column Property dialog box.

For more information, see Changing the Null Option Assigned to a Column.


The columns in table '<0s>' do not match an existing enabled primary key or UNIQUE constraint.

At least one table participating in a relationship must have either a Primary Key or a Unique Constraint. After setting up a Primary Key or a Unique constraint for one of the tables you’ve selected, you can then define other relationships for that table.

For more information, see Creating a Unique Constraint and Defining a Primary Key.


The columns in table '<0s>' do not match an existing primary key or UNIQUE constraint.

The columns on the primary key side of a foreign key relationship must participate in either a Primary Key or a Unique Constraint. After setting up a Primary Key or a Unique constraint for one of the tables you’ve selected, you can then define other relationships for that table.

For more information, see Creating a Unique Constraint and Defining a Primary Key.


The datatype of column '<1s>' in the '<0s>' table can't be changed because it participates in index '<2s>'.

The sum of the lengths of all columns in an index can not exceed 256 bytes. Changing to the specified datatype would exceed the maximum index size of <3d> bytes.

For more information, see Changing the Data Type Assigned to a Column and Creating an Index.


The datatype or size property of '<0s>.<1s>' doesn't match '<2s>.<3s>'.

When creating a foreign key relationship, the datatypes of selected columns must match. Select a column with the same datatype and size as the related column.

For more information, see Checking Existing Data when Creating a Relationship.


The Default Value property can't be set on column '<0s>' because it is an identity column.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have default values.

For more information, see Changing a Column’s Identity Properties and Assigning a Default Value to a Column.


The existing relationship must have at least one pair of related columns.

There must be matching columns on both sides of a foreign key relationship. Deleting a column that is part of a relationship will disable the relationship.

For more information, see Creating a Relationship.


The Identity property can't be set on column '<0s>' because it allows null values.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have null values.

For more information, see Changing a Column’s Identity Properties and Changing the Null Option Assigned to a Column.


The Identity property can't be set on column '<0s>' because it has a default value.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have default values.

For more information, see Changing a Column’s Identity Properties and Assigning a Default Value to a Column.


The number of selected columns exceeds the number of columns in the target table.

You cannot create a compound foreign key relationship using more columns than exist in the target table. Make sure the number of columns you’ve selected matches the number in the target table.

For more information, see Creating a Relationship Between Tables.


The primary key or UNIQUE constraint cannot be changed until its existing relationships are deleted.

You cannot change a table’s primary key or unique constraint while other foreign key relationships are still in place. To change a table’s primary key or unique constraint, first delete all existing relationships for the table.

For more information, see Deleting a Relationship.


The primary key or Unique constraint cannot be changed while relationships to the existing primary key or Unique constraint are enforced.

You cannot change a table’s primary key or unique constraint while other foreign key relationships are still in place. To change a table’s primary key or unique constraint, first delete all existing relationships for the table.

For more information, see Deleting a Relationship.


The total size of an index or primary key cannot exceed 256 bytes.

The sum of the lengths of all columns in an index can not exceed 256 bytes. Changing to the specified datatype would exceed the maximum index size of <3d> bytes.

For more information, see Indexes, Changing the Data Type Assigned to a Column, and Creating an Index.


You are not logged in as the database owner or system administrator. You will not be able to save changes to tables that you do not own.

In Microsoft® SQL Server™, each database has a database owner (dbo). The dbo is the creator of the database and has system administrator privileges inside the database. It is the dbo who determines the access and capabilities provided to other users.

If you are not the dbo, you will still be able to create diagrams showing any tables that you have permissions to see, however you won’t be able to perform all edits. Certain edits require SQL Server CREATE TABLE permission.

For more information, see Working in a Multi-User Environment.


A blank constraint expression is not allowed

You must enter a constraint in the Constraints Expression dialog box before continuing to define properties for your table.

For more information, see Creating a Unique Constraint.


Are you sure you want to delete the selected relationship from your database?

Answering YES will delete the selected relationship.

For more information about relationships, see Table Relationships and Deleting a Relationship.


Query Designer Troubleshooting Errors

This section contains a list of possible messages returned while creating and running queries using the Query Designer. These errors often occur while trying to save or execute a query.

For information about additional Microsoft Visual Database Tools error messages, see Database Designer Troubleshooting Errors.

Note The Visual Database Tools are dependent upon many other applications and components. If you receive an error message not listed in the Visual Database Tools documentation, search your product documentation and your server documentation as well.


(+) operator ignored

The Oracle outer join operator that you entered is not appropriate and will be ignored.

See Types of Joins, Creating Outer Joins, and Query Designer Considerations for Oracle Databases for more information.


(+) table reference may not be joined with more than one table.

There is an error in the way that you are attempting to join a table reference. This table reference can only be joined with one other table.

For more information, see Types of Joins.


<Os> in expression is not part of the query.

An expression within your query is not properly formed. This often occurs when the criteria expression that you entered doesn't match the available columns for the input sources. Clear the value out and then type in a column reference that matches your input sources.

For more information, see Using Expressions in Queries.


<Os> is not supported.

The syntax you entered is valid but is not supported visually by the Query Designer. Be sure to verify your syntax before saving.

For more information, see Supported Query Types.


<Os> may not be used in this query type.

The action you are attempting is not permitted with the type of query you have selected. Verify the syntax in your query or change the query type.

For more information, see Supported Query Types.


<Os> support is not available in this server version.

You have attempted to use a feature that isn’t supported by your server software.

For more information, see What’s New in Visual Database Tools.


Ambiguous outer join (+) operator

The Query Designer requires that you follow specific rules when designing queries. The Query Designer is unable to process the outer join operator you have entered. Check the syntax in your SQL statement.

For more information, see Creating Outer Joins.


Appropriate SQL cannot be generated.

The Microsoft Visual Database Tools Query Designer requires that you follow specific rules when designing queries. This error may appear if you have used the Diagram or Grid pane to create a query that cannot be expressed in an SQL statement. Verify the query options you have selected.

For more information, see Creating Queries and Specifying Search Criteria.


Bad top value

The top value in your query is invalid or out of range. The value for the top clause must be an integer value if the PERCENT clause is not used. To use the PERCENT clause, just type in the word PERCENT after the numeric value in the cell.

For more information, see Entering Search Values.


Cannot add this expression to the select list.

There are limitations to what expressions are allowed in the select list. The expression you are trying to add may be invalid. Verify that the syntax in the expression is correct. It is possible that the type of expression is invalid.

For more information, see Using Expressions in Queries.


Cannot assign an alias to this field.

An alias can only be created for a suitable column or table. The field you have chosen is not valid. Verify that the settings for the field are correct.

For more information, see Creating Column Aliases or Creating Table Aliases.


Cannot convert entry to valid date/time value.

The Microsoft Visual Database Tools Query Designer requires that you follow specific rules when designing queries. Verify that the entry is correct.

For more information, see Modifying Data in Tables.


Cannot convert to proper type.

The Microsoft Visual Database Tools Query Designer requires that you follow specific rules when converting values. The query cannot be converted. Verify that the information in the query and the query type are appropriate.

For more information, see Functions for Expressions.


Cannot delete rows with unknown keys.

The row you’ve attempted to delete has an unknown key. This row cannot be deleted at this time.

For more information, see Deleting Rows in the Results Pane.


Cannot edit rows with unknown keys.

The row you’ve attempted to edit has an unknown key.

For more information, see Editing Rows in the Results Pane.


Cannot edit this cell.

The cell you’ve selected cannot be edited. It may be the result of a calculation or part of a joined table.

For more information, see Modifying Data in Tables.


Cannot filter this expression.

The expression you’ve entered cannot be filtered. This typically occurs when the user types in a criteria against the * or a criteria against a field that is blank in the QBE. The user should only enter criteria against fields that are already in the QBE.

For more information, see Specifying Search Criteria.


Cannot insert into this expression.

You cannot insert data into the selected expression. This function is not supported at this time.

For more information, see Creating Insert Queries.


Cannot open encrypted <Os> <1s>.

After a view has been encrypted and closed it can’t be opened again.

For more information, see Creating Views with the View Designer.


Cannot update this expression.

The selected expression cannot be updated.

For more information, see Using Expressions in Queries.


Cannot use column with IMAGE or TEXT data type in this context.

The Microsoft Visual Database Tools Query Designer requires that you follow specific rules when designing queries.

For more information, see Creating Queries and Specifying Search Criteria.


Cannot use LONG data type in this context.

The Microsoft Visual Database Tools Query Designer requires that you follow specific rules when designing queries.

For more information, see Creating Queries and Specifying Search Criteria.


Column list is not supported for Make Table queries.

The Query Designer does not support inclusion of the optional column list for the Oracle Make Table query. Remove the column list and use column aliases in your select statement instead.

For more information, see Creating Make Table Queries.


Column with (+) operator does not reference a valid table.

The operator you’ve used in the query column must reference a valid table. The Query Designer cannot validate the table currently referenced. Verify that the table exists in the database and that the Query Designer has access to it.

For more information, see Specifying Search Conditions.


Data source alias is read only.

Read-only values cannot be edited. To use this data source, you need a write-enabled version of the data source available to the Query Designer.

For more information, see Modifying Data Using Queries.


Data source base name is read only.

Read-only values cannot be edited. To use this data source, you need a write-enabled version of the data source available to the Query Designer.

For more information, see Modifying Data Using Queries.


Data type error in expression

Expressions with different data types can generate errors. To work with different data types in a single expression, you need to convert to the same data type.

For more information, see Creating an Expression.


Data type mismatch - no conversion possible

To work with different data types in a single expression, you need to convert to the same data type. The selected data types cannot be converted.

For more information, see Using Expressions in Queries.


Data type mismatch - use the CONVERT function

To work with different data types in a single expression, you need to convert to the same data type. One of the data types must be converted before you can continue.

For more information, see Using Expressions in Queries.


Do you want to suppress further error messages telling you why records can't be pasted?

If you answer Yes, you will not receive messages explaining why records cannot be pasted correctly.


Error after function '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error after predicate near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error before EXISTS clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error before EXISTS clause: '<Os>" not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error before FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error following UNION operator

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in column list

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in column list: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in destination table specification

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For best results, do not include periods in the destination table specification.

For more information, see Specifying Search Criteria and Creating Queries.


Error in FROM clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in GROUP BY clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Summarizing and Grouping.


Error in GROUP BY clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Summarizing and Grouping.


Error in HAVING clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


Error in HAVING clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


Error in INSERT statement

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in INSERT statement: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in join expression

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying Using Multiple Tables.


Error in join expression: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying Using Multiple Tables.


Error in list of function arguments: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values in IN clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values in IN clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in ON clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in optional FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in ORDER BY clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in ORDER BY clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in SELECT clause: alias '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in SELECT clause: alias not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in SELECT clause: expression near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in set list in UPDATE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in DELETE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in DELETE clause: <Os>' not recognized.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in INSERT clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in INSERT clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in UPDATE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in text following query statement: '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in values list in INSERT INTO clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in values list in INSERT INTO clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

Make sure the number of items in the Column list matches the number of items in the Values list.

For more information, see Specifying Search Criteria and Creating Queries.


Error in WHERE clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


Function argument count error

A function in your query has the wrong number of arguments. Review you query syntax to locate the function.

For more information, see Functions for Expressions and Specifying Search Criteria.


Ignoring illegal use of ALL

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Although the query will run, you should review your query syntax and correct the error.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Ignoring ODBC syntax

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Illegal expression list usage

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Illegal sequence use

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Illegal use of outer join operator

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins.


Incomplete column list

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Incomplete SET clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Incomplete values list

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid entries must be resolved before you can exit this pane.

Exiting a pane causes other panes to be updated. If there is an invalid entry in the pane you are editing, you need to change or delete it.


Invalid escape character

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

Your escape character must be a single character.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid identifier: '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid or missing expression

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid or missing expression near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid prefix or suffix characters

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid row index: Goto failed

You have entered a non-numeric value into the GoTo record field. Enter a numeric value instead. Entering a number that is greater than the number of rows in the table, goes to the last record.

For more information, see Specifying Search Criteria.


Invalid text or symbol

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid view name

The View name you’ve specified is not valid. Valid names begin with an underscore (_) or a character and contain a combination of characters, numbers and underscores.

The maximum length for View names is 32 for Microsoft® SQL Server™ 6.5, 32 for Oracle, and 128 for SQL Server 7.0. Do not use names with a period.

For more information, see Working With Database Views in Data View.


Missing escape character in LIKE predicate.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM keyword near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing INTO keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing INTO keyword near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing or incomplete SELECT clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing pattern in LIKE predicate

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing SET keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing subquery

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


Missing subquery correlation name

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


Missing subquery or the operator you entered requires parenthesis.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


Must enter either TRUE or FALSE.

When specifying a criteria for the EXISTS statement, you must use either True for EXISTS or False for NOT EXISTS.

For more information, see Specifying Search Criteria.


Object <Os> does not exist in the database.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Oracle does not allow full outer joins.

You have entered a join syntax that is not supported by Oracle.

For more information, see Creating Outer Joins. Consult your Oracle documentation for details about using outer joins with an Oracle database.


Oracle does not support this join syntax.

You have used a join syntax that is not supported by Oracle.

For more information, see Querying Using Multiple Tables. Consult your Oracle documentation for details about using joins with an Oracle database.


Outer join column may not be used with an IN predicate or subquery.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins.


Query Designer cannot open this query file.

Query Designer cannot open the specified query file. Verify that file is a query file. The file may be corrupt or from a non-supported version of the Query Designer.

For more information, see Supported Query Types.


Row limit value should be between <xxx> and <xxx>.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Entering Search Values.


SQL statement could not be parsed.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


Syntax error in table reference

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries and Specifying Search Criteria.


Syntax error in table reference: '<Os>' not recognized.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


The current version of the ODBC driver is not valid.

Your ODBC driver is not current. For best results, use the ODBC driver provided with the Microsoft Visual Database Tools installation.

For more information refer to your ODBC documentation.


The Group By function is not supported in WHERE clauses.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Querying on Groups of Rows.


The NOT keyword may not be used in a column cell.

When entering a NOT EXIST subquery into the Column cell, enter just the EXIST clause. Then go to the Criteria cell and enter False for it.

For more information, see Specifying Search Criteria.


The ORDER BY function is not supported for CREATE TABLE queries.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Reordering Output Columns.


The outer join operator (+) cannot be used as an OR operand.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins and Specifying Search Criteria.


The outer join operator (+) cannot be used in QBE.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins.


The query cannot be executed because some files are missing or not registered.

Query Designer cannot locate your query files and cannot run your query. You may need to reinstall the product.


The Query Designer does not support the critical ODBC APIs.

The API you are attempting to use is not supported. Refer to your ODBC driver documentation. Use Microsoft provided ODBC drivers whenever possible.


The Query Designer does not support the current ODBC API.

The API you are attempting to use is not supported. Refer to your ODBC driver documentation. Use Microsoft provided ODBC drivers whenever possible.


The Query Designer supports no more than one data source for this type of query.

Only one data source can be used with this query type.

For more information, see Supported Query Types.


The specified OR group number is already in use.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


The value you entered is not consistent with the data type of the column.

Entered values must match the column data types.

For more information, see Entering Search Values.


There are not enough columns to match the subquery select list.

The SELECT statement needs to include the same number of columns that the embedded subquery returns.

For more information, see Creating Subqueries.


There are not enough columns to match the value list.

An UPDATE or INSERT statement contains more values than the table being updated. Verify your SQL statement to make sure the number of columns matches the table.


There is no unique table in this query.

The query needs to unambiguously identify which table to return values from.


This ALIAS name is already being used.

Alias names must be unique. Enter a different alias name.

For more information, see Creating Table Aliases and Creating Column Aliases.


This cell contains the text string "<NULL>" which may not be processed correctly.

Use NULL or NOT NULL for comparing null data. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


This IS operator can only be used with NULL or NOT NULL.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


This operator cannot be used with columns with data type "uniqueidentifier".

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


This table is not in the query definition.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


Too many characters for field width.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


Unable to locate data source.

The specified data source cannot be found. Check the data source location and the entered location.


Unable to parse expression.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unable to parse query text.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unable to parse statement.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unknown column

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unknown conversion specification

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unnecessary use of CONVERT function

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unsupported SQL

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


View already exists in the database.

Views must have unique names within the database. Enter a different name for the view.

For more information, see Creating Views With the View Designer.


You may not use a link server object as a destination with this query type.

The selected query type does not support using link server objects as destinations.

For more information, see Creating Queries.


You may not use ALL with CUBE or ROLLUP.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


You may not use an openrowset as a destination with this query type.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


You must enter an expression in the Column cell before continuing.

Enter an expression in the column cell.

For more information, see Using Expressions in Queries.


Your entry cannot be converted to a valid datetime value.

In general, the ANSI standard date format is used with databases that represent dates using a true date data type. In contrast, the datetime format is used with databases that support a datetime data type.

For more information, see Entering Search Values.


A number of rows were affected

The query executed successfully. The specified rows were affected by a make table process.


SQL Verification

The SQL verified successfully.

For more information, see Creating Queries and Specifying Search Criteria.


Query has executed successfully

The query executed successfully.


DELETE statement conflicted with COLUMN REFERENCE constraint

A conflict occurred while your query attempted to execute. The QueryDesigner has tried to locate the direct source of the conflict. Please check the syntax of your query to attempt to resolve the conflict.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.


Database Designer Error

No specific help is available for this error. If the text in the error message does not provide enough information for you to solve the problem, please consider the following options:

  • Verify that your settings are correct and try the action again.

  • Use the index to search for keywords related to the error message.

  • If the problem is due to external applications or software, consult the documentation for that area. For example, errors may be caused by your database software, your server setup, or even the network you are using.

  • For database modification errors, such as invalid parameters in a database table, consult your database software for details.

  • Check the Readme for late-breaking information concerning the error.


Query Designer Error

No specific help is available for this error. If the text in the error message does not provide enough information for you to solve the problem, please consider the following options:

  • Verify that your settings are correct and try the action again.

  • Use the index to search for keywords related to the error message.

  • If the problem is due to external applications or software, consult the documentation for that area. For example, errors may be caused by your database software, your server setup, or even the network you are using.

  • For SQL statement errors, consult your database software to ensure you are using the appropriate syntax for your database.

  • Check the Readme for late-breaking information concerning the error.


Visual Database Tools Error

No specific help is available for this error. If the text in the error message does not provide enough information for you to solve the problem, please consider the following options:

  • Verify that your settings are correct and try the action again.

  • Use the index to search for keywords related to the error message.

  • If the problem is due to external applications or software, consult the documentation for that area. For example, errors may be caused by your database, your server, or even the network you are using.

  • Check the Readme for late-breaking information concerning the error.

If you are still unable to resolve the problem, contact Microsoft Support Online at

http://www.microsoft.com/support/.