Microsoft KB Archive/170117: Difference between revisions

From BetaArchive Wiki
m (Text replacement - ">" to ">")
m (Text replacement - """ to """)
Line 61: Line 61:
=== Creating a GUID field by using SQL DDL ===
=== Creating a GUID field by using SQL DDL ===


Microsoft Access GUID fields can be created using a "CREATE TABLE" SQL DDL statement. The following code will create a table called MyGUIDTable with a GUID field named MyGUIDField in database c:\db1.mdb using SQL DDL.
Microsoft Access GUID fields can be created using a "CREATE TABLE" SQL DDL statement. The following code will create a table called MyGUIDTable with a GUID field named MyGUIDField in database c:\db1.mdb using SQL DDL.
==== Sample code ====
==== Sample code ====


<pre class="codesample">CDaoDatabase db;
<pre class="codesample">CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
db.Execute(_T(&quot;CREATE TABLE MyGUIDTable (MyGUIDField GUID)&quot;));
db.Execute(_T("CREATE TABLE MyGUIDTable (MyGUIDField GUID)"));
                 </pre>
                 </pre>
The DDL method above will also work using the CDatabase::ExecuteSQL method against the Microsoft Access Open Database Connectivity (ODBC) driver.
The DDL method above will also work using the CDatabase::ExecuteSQL method against the Microsoft Access Open Database Connectivity (ODBC) driver.
Line 75: Line 75:


<pre class="codesample">CDaoDatabase db;
<pre class="codesample">CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
// Create new tabledef and create GUID field.
// Create new tabledef and create GUID field.
CDaoTableDef td(&amp;db);
CDaoTableDef td(&amp;db);
td.Create(_T(&quot;MyGUIDTable&quot;));
td.Create(_T("MyGUIDTable"));
td.CreateField(&quot;MyGuidField&quot;, dbGUID, 16);  // Note: field size is 16.
td.CreateField("MyGuidField", dbGUID, 16);  // Note: field size is 16.
// Append table to tabledefs collection to create physical table.
// Append table to tabledefs collection to create physical table.
td.Append();</pre>
td.Append();</pre>
Line 92: Line 92:


<pre class="codesample">CDaoDatabase db;
<pre class="codesample">CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
db.Execute(_T(&quot;INSERT INTO MyGUIDTable (MyGuidField) VALUES
db.Execute(_T("INSERT INTO MyGUIDTable (MyGuidField) VALUES
   ({guid {11223344-1122-1122-1122-AABBCCDDEEFF}})&quot;));</pre>
   ({guid {11223344-1122-1122-1122-AABBCCDDEEFF}})"));</pre>
You can also use a GUID in the SET portion of an UPDATE SQL statement:
You can also use a GUID in the SET portion of an UPDATE SQL statement:
<pre class="codesample">SET MyGuidField = {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}</pre>
<pre class="codesample">SET MyGuidField = {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}</pre>
Line 115: Line 115:
CDatabase db;
CDatabase db;
// Open Microsoft Access database using ODBC.
// Open Microsoft Access database using ODBC.
db.OpenEx( &quot;DSN=NW97;&quot;, CDatabase::noOdbcDialog );
db.OpenEx( "DSN=NW97;", CDatabase::noOdbcDialog );
// Drop and re-create the test table.
// Drop and re-create the test table.
try
try
{
{
     strSQL = &quot;DROP TABLE Literal&quot;;
     strSQL = "DROP TABLE Literal";
     db.ExecuteSQL( strSQL );
     db.ExecuteSQL( strSQL );
}
}
Line 126: Line 126:
     e->Delete();  // Ignore errors.
     e->Delete();  // Ignore errors.
};
};
strSQL = &quot;CREATE TABLE Literal (LinkID GUID, Description TEXT)&quot;;
strSQL = "CREATE TABLE Literal (LinkID GUID, Description TEXT)";
db.ExecuteSQL( strSQL );
db.ExecuteSQL( strSQL );
// Turn off driver scanning for escape clauses to give the raw
// Turn off driver scanning for escape clauses to give the raw
Line 132: Line 132:
::SQLSetConnectOption( db.m_hdbc, SQL_NOSCAN, SQL_NOSCAN_ON );
::SQLSetConnectOption( db.m_hdbc, SQL_NOSCAN, SQL_NOSCAN_ON );
// Run INSERT SQL statements to add two records.
// Run INSERT SQL statements to add two records.
strSQL = &quot;INSERT INTO Literal (LinkID, Description) VALUES &quot;
strSQL = "INSERT INTO Literal (LinkID, Description) VALUES "
         &quot;({guid {11223344-1122-1122-1122-AABBCCDDEEFF}}, 'Guid 1')&quot;;
         "({guid {11223344-1122-1122-1122-AABBCCDDEEFF}}, 'Guid 1')";
db.ExecuteSQL( strSQL );
db.ExecuteSQL( strSQL );
strSQL = &quot;INSERT INTO Literal (LinkID, Description) VALUES &quot;
strSQL = "INSERT INTO Literal (LinkID, Description) VALUES "
         &quot;({guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}, 'Guid 2')&quot;;
         "({guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}, 'Guid 2')";
db.ExecuteSQL( strSQL );
db.ExecuteSQL( strSQL );
// Turn the driver scanning for escape clauses back on.
// Turn the driver scanning for escape clauses back on.
Line 146: Line 146:
::SQLSetStmtOption( rs.m_hstmt, SQL_NOSCAN, SQL_NOSCAN_ON );
::SQLSetStmtOption( rs.m_hstmt, SQL_NOSCAN, SQL_NOSCAN_ON );
// Open recordset using a literal GUID in a WHERE clause.
// Open recordset using a literal GUID in a WHERE clause.
strSQL = &quot;SELECT * FROM Literal WHERE LinkID = &quot;
strSQL = "SELECT * FROM Literal WHERE LinkID = "
         &quot;{guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}&quot;;
         "{guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}";
rs.Open( CRecordset::forwardOnly, strSQL, CRecordset::readOnly );
rs.Open( CRecordset::forwardOnly, strSQL, CRecordset::readOnly );
// Confirm that you found the correct record.
// Confirm that you found the correct record.
rs.GetFieldValue( &quot;Description&quot;, strDescription );
rs.GetFieldValue( "Description", strDescription );
AfxMessageBox( &quot;Found &quot; + strDescription );
AfxMessageBox( "Found " + strDescription );
                 </pre>
                 </pre>
'''Note''' You must add the common language runtime support compiler option ('''/clr:oldSyntax''') in Visual C++ 2005 to successfully compile the previous code sample. To do this, follow these steps:
'''Note''' You must add the common language runtime support compiler option ('''/clr:oldSyntax''') in Visual C++ 2005 to successfully compile the previous code sample. To do this, follow these steps:
Line 173: Line 173:
<pre class="codesample">// Open database and recordset objects.
<pre class="codesample">// Open database and recordset objects.
CDaoDatabase db;
CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
CDaoRecordset rs(&amp;db);
CDaoRecordset rs(&amp;db);
rs.Open(dbOpenTable,_T(&quot;MyGUIDTable&quot;));
rs.Open(dbOpenTable,_T("MyGUIDTable"));
// Create VT_BSTRT variant for GUID.
// Create VT_BSTRT variant for GUID.
COleVariant varGUIDValue(_T(&quot;{guid {11223344-1122-1122-1122-AABBCCDDEEFF}}&quot;), VT_BSTRT);
COleVariant varGUIDValue(_T("{guid {11223344-1122-1122-1122-AABBCCDDEEFF}}"), VT_BSTRT);
// Add a record using CDaoRecordset method.
// Add a record using CDaoRecordset method.
rs.AddNew();
rs.AddNew();
   rs.SetFieldValue(_T(&quot;MyGUIDField&quot;),varGUIDValue);
   rs.SetFieldValue(_T("MyGUIDField"),varGUIDValue);
rs.Update();
rs.Update();
                 </pre>
                 </pre>
Line 199: Line 199:
<pre class="codesample">// Open database.
<pre class="codesample">// Open database.
CDaoDatabase db;
CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
// Create a table called MySeekTable with a GUID primary key field named
// Create a table called MySeekTable with a GUID primary key field named
// ID and a field named Found.
// ID and a field named Found.
db.Execute(_T(&quot;create table MySeekTable (ID guid constraint PKEY primary
db.Execute(_T("create table MySeekTable (ID guid constraint PKEY primary
key, Found text)&quot;));
key, Found text)"));
// Insert a few records using an insert into statement.
// Insert a few records using an insert into statement.
db.Execute(_T(&quot;insert into MySeekTable (ID, Found) values ({guid {11111111-aabb-aabb-aabb-aabbccddeeff}},'Guid1')&quot;));
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {11111111-aabb-aabb-aabb-aabbccddeeff}},'Guid1')"));
db.Execute(_T(&quot;insert into MySeekTable (ID, Found) values ({guid {22222222-aabb-aabb-aabb-aabbccddeeff}},'Guid2')&quot;));
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {22222222-aabb-aabb-aabb-aabbccddeeff}},'Guid2')"));
db.Execute(_T(&quot;insert into MySeekTable (ID, Found) values ({guid {33333333-aabb-aabb-aabb-aabbccddeeff}},'Guid3')&quot;));
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {33333333-aabb-aabb-aabb-aabbccddeeff}},'Guid3')"));
// Open table-type recordset (must use table-type for Seek) and select
// Open table-type recordset (must use table-type for Seek) and select
// index for seek.
// index for seek.
CDaoRecordset rs(&amp;db);
CDaoRecordset rs(&amp;db);
rs.Open(dbOpenTable,_T(&quot;MySeekTable&quot;));
rs.Open(dbOpenTable,_T("MySeekTable"));
rs.SetCurrentIndex(_T(&quot;PKEY&quot;));
rs.SetCurrentIndex(_T("PKEY"));
// Construct the GUID you want to find and seek the GUID.
// Construct the GUID you want to find and seek the GUID.
COleVariant varGUIDValue(_T(&quot;{guid {22222222-aabb-aabb-aabb-aabbccddeeff}}&quot;), VT_BSTRT);
COleVariant varGUIDValue(_T("{guid {22222222-aabb-aabb-aabb-aabbccddeeff}}"), VT_BSTRT);
if (rs.Seek(_T(&quot;=&quot;),&amp;varGUIDValue)) {
if (rs.Seek(_T("="),&amp;varGUIDValue)) {
   // GUID found. Retrieve and display value.
   // GUID found. Retrieve and display value.
   CString strResult = V_BSTRT(&amp;rs.GetFieldValue(_T(&quot;Found&quot;)));
   CString strResult = V_BSTRT(&amp;rs.GetFieldValue(_T("Found")));
   AfxMessageBox(&quot;Seek of guid found '&quot; + strResult + &quot;'&quot;);
   AfxMessageBox("Seek of guid found '" + strResult + "'");
} else {
} else {
   // GUID not found.
   // GUID not found.
   AfxMessageBox(&quot;Seek of guid failed.&quot;);
   AfxMessageBox("Seek of guid failed.");
}</pre>
}</pre>
=== Using GUID fields with MFC ClassWizard-generated recordsets ===
=== Using GUID fields with MFC ClassWizard-generated recordsets ===
Line 227: Line 227:
The MFC ClassWizard automatically binds GUID fields to a CString class member and sets up the proper DoFieldExchange macros. No additional changes are needed to display, insert, and update GUID fields when you use the MFC ClassWizard to create '''CRecordset''' or '''CDaoRecordset''' derived classes. The fields are displayed in the Microsoft Access GUID format:
The MFC ClassWizard automatically binds GUID fields to a CString class member and sets up the proper DoFieldExchange macros. No additional changes are needed to display, insert, and update GUID fields when you use the MFC ClassWizard to create '''CRecordset''' or '''CDaoRecordset''' derived classes. The fields are displayed in the Microsoft Access GUID format:
<pre class="fixed_text">  {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}</pre>
<pre class="fixed_text">  {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}</pre>
=== Creating &quot;AutoNumber&quot; GUID fields programmatically ===
=== Creating "AutoNumber" GUID fields programmatically ===


Microsoft Access also provides an &quot;AutoNumber&quot; type GUID field. You can use this type of field for the primary key of a table and let Access automatically generate each new GUID. The GUIDs are randomly generated by the Microsoft Jet database engine each time a record is inserted into the table using an complex algorithm that will avoid duplicates over all databases in the world until the year 3400 AD.<br />
Microsoft Access also provides an "AutoNumber" type GUID field. You can use this type of field for the primary key of a table and let Access automatically generate each new GUID. The GUIDs are randomly generated by the Microsoft Jet database engine each time a record is inserted into the table using an complex algorithm that will avoid duplicates over all databases in the world until the year 3400 AD.<br />
<br />
<br />
You cannot create an &quot;AutoNumber&quot; type GUID field using SQL DDL, you must use DAO code. The following code demonstrates how to create an &quot;AutoNumber&quot; type GUID field using the '''CDaoTableDef::CreateField''' method.
You cannot create an "AutoNumber" type GUID field using SQL DDL, you must use DAO code. The following code demonstrates how to create an "AutoNumber" type GUID field using the '''CDaoTableDef::CreateField''' method.
==== Sample code ====
==== Sample code ====


<pre class="codesample">// Open database and create tabeldef.
<pre class="codesample">// Open database and create tabeldef.
CDaoDatabase db;
CDaoDatabase db;
db.Open(_T(&quot;c:\\db1.mdb&quot;));
db.Open(_T("c:\\db1.mdb"));
CDaoTableDef td(&amp;db);
CDaoTableDef td(&amp;db);
td.Create(_T(&quot;MyGUIDTable&quot;));
td.Create(_T("MyGUIDTable"));
// Create and fill out a CDaoFieldInfo structure.
// Create and fill out a CDaoFieldInfo structure.
CDaoFieldInfo fi;
CDaoFieldInfo fi;
fi.m_strName = _T(&quot;ID&quot;);
fi.m_strName = _T("ID");
fi.m_nType = dbGUID;
fi.m_nType = dbGUID;
fi.m_lSize = 16;
fi.m_lSize = 16;
Line 248: Line 248:
fi.m_bRequired = FALSE;
fi.m_bRequired = FALSE;
fi.m_lAttributes = dbSystemField;
fi.m_lAttributes = dbSystemField;
fi.m_strValidationRule = _T(&quot;&quot;);
fi.m_strValidationRule = _T("");
fi.m_strValidationText = _T(&quot;&quot;);
fi.m_strValidationText = _T("");
fi.m_strDefaultValue = _T(&quot;GenGUID()&quot;); // This generates the GUID.
fi.m_strDefaultValue = _T("GenGUID()"); // This generates the GUID.
// Create field using CDaoFieldInfo constructor and append table.
// Create field using CDaoFieldInfo constructor and append table.
td.CreateField(fi);
td.CreateField(fi);

Revision as of 11:04, 21 July 2020

Article ID: 170117

Article Last Modified on 1/9/2006



APPLIES TO

  • Microsoft Visual C++ 2005 Express Edition
  • Microsoft Visual C++ .NET 2003 Standard Edition
  • Microsoft Visual C++ .NET 2002 Standard Edition
  • Microsoft Visual C++ 6.0 Service Pack 5
  • Microsoft Visual C++ 5.0 Standard Edition
  • Microsoft Visual C++ 4.2 Professional Edition
  • Microsoft Visual C++ 4.2 Professional Edition
  • Microsoft Visual C++ 4.1 Subscription
  • Microsoft Visual C++ 4.0 Standard Edition
  • Microsoft Visual C++ 4.0 Standard Edition



This article was previously published under Q170117


SUMMARY

Microsoft Access 95 introduced a new GUID (Globally Unique Identifier) data type used for database replication. You can use GUID fields (called Replication ID fields in Access) to store any GUID number in a compact 16-byte binary format that can be indexed and used as a primary key for a table. This article explains how to create and use Microsoft Access GUID data type fields with Visual C++ MFC database classes.

Creating a GUID field by using SQL DDL

Microsoft Access GUID fields can be created using a "CREATE TABLE" SQL DDL statement. The following code will create a table called MyGUIDTable with a GUID field named MyGUIDField in database c:\db1.mdb using SQL DDL.

Sample code

CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
db.Execute(_T("CREATE TABLE MyGUIDTable (MyGUIDField GUID)"));
                

The DDL method above will also work using the CDatabase::ExecuteSQL method against the Microsoft Access Open Database Connectivity (ODBC) driver.

Creating a GUID field by using CDaoTableDef::CreateField

You can also use a CDaoTableDef to create GUID data type field using the CreateField method.

Sample code

CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
// Create new tabledef and create GUID field.
CDaoTableDef td(&db);
td.Create(_T("MyGUIDTable"));
td.CreateField("MyGuidField", dbGUID, 16);  // Note: field size is 16.
// Append table to tabledefs collection to create physical table.
td.Append();

Inserting and updating GUID fields by using SQL

You can both insert and update GUID fields using standard SQL INSERT INTO and UPDATE syntax. GUIDs are commonly displayed in textual format as:

   {11223344-1122-1122-1122-AABBCCDDEEFF}

Microsoft Access requires a similar textual format when using GUIDs in SQL statements:

   {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}

The following code will insert a GUID field into the MyGUIDTable table.

Sample code

CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
db.Execute(_T("INSERT INTO MyGUIDTable (MyGuidField) VALUES
   ({guid {11223344-1122-1122-1122-AABBCCDDEEFF}})"));

You can also use a GUID in the SET portion of an UPDATE SQL statement:

SET MyGuidField = {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}

Note You do not need quotes around the GUID field.

Using literal GUIDs with the Microsoft Access ODBC driver

Because ODBC defines the curly brace as an escape code for vendor specific escape clauses, you must turn off escape clause scanning when you use literal GUIDs in SQL statements with the Microsoft Access ODBC driver. Note that this functionality is not supported in the Microsoft Access ODBC driver that ships with MDAC 2.1 or later.

If you do not turn off the escape clause scanning, you get the following error message from the driver:

Syntax error (missing operator) in query expression 'guid 11223344-1122-1122-1122-AABBCCDDEEFF}'.
State:37000,Native:-3100,Origin:[Microsoft][ODBC Microsoft Access 97 Driver]

The following example demonstrates how to use literal GUIDs with the Microsoft Access ODBC driver.

Sample code

CString strSQL, strDescription;
CDatabase db;
// Open Microsoft Access database using ODBC.
db.OpenEx( "DSN=NW97;", CDatabase::noOdbcDialog );
// Drop and re-create the test table.
try
{
    strSQL = "DROP TABLE Literal";
    db.ExecuteSQL( strSQL );
}
catch(CDBException *e)
{
    e->Delete();  // Ignore errors.
};
strSQL = "CREATE TABLE Literal (LinkID GUID, Description TEXT)";
db.ExecuteSQL( strSQL );
// Turn off driver scanning for escape clauses to give the raw
// SQL to Access.
::SQLSetConnectOption( db.m_hdbc, SQL_NOSCAN, SQL_NOSCAN_ON );
// Run INSERT SQL statements to add two records.
strSQL = "INSERT INTO Literal (LinkID, Description) VALUES "
         "({guid {11223344-1122-1122-1122-AABBCCDDEEFF}}, 'Guid 1')";
db.ExecuteSQL( strSQL );
strSQL = "INSERT INTO Literal (LinkID, Description) VALUES "
         "({guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}, 'Guid 2')";
db.ExecuteSQL( strSQL );
// Turn the driver scanning for escape clauses back on.
::SQLSetConnectOption( db.m_hdbc, SQL_NOSCAN, SQL_NOSCAN_OFF );
// Now use a literal GUID in a WHERE clause of a select
// statement to find the record.
CRecordset rs( &db );
// Turn off scanning for recordset.
::SQLSetStmtOption( rs.m_hstmt, SQL_NOSCAN, SQL_NOSCAN_ON );
// Open recordset using a literal GUID in a WHERE clause.
strSQL = "SELECT * FROM Literal WHERE LinkID = "
         "{guid {11223344-1122-1122-1122-FFFFFFFFFFFF}}";
rs.Open( CRecordset::forwardOnly, strSQL, CRecordset::readOnly );
// Confirm that you found the correct record.
rs.GetFieldValue( "Description", strDescription );
AfxMessageBox( "Found " + strDescription );
                

Note You must add the common language runtime support compiler option (/clr:oldSyntax) in Visual C++ 2005 to successfully compile the previous code sample. To do this, follow these steps:

  1. Click Project, and then click ProjectName Properties.


Note ProjectName is a placeholder for the name of the project.

  1. Expand Configuration Properties, and then click General.
  2. In the right pane, click to select Common Language Runtime Support, Old Syntax (/clr:oldSyntax) in the Common Language Runtime support project settings.
  3. Click Apply, and then click OK.

For more information about common language runtime support compiler options, visit the following Microsoft Web site:

Inserting and updating GUID fields by using CDaoRecordset

When using GUID fields with DAO objects, you create a VT_BSTRT type COleVariant field using the same textual GUID syntax as the SQL method above. This code demonstrates how to insert a GUID field using CdaoRecordset methods.

// Open database and recordset objects.
CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
CDaoRecordset rs(&db);
rs.Open(dbOpenTable,_T("MyGUIDTable"));
// Create VT_BSTRT variant for GUID.
COleVariant varGUIDValue(_T("{guid {11223344-1122-1122-1122-AABBCCDDEEFF}}"), VT_BSTRT);
// Add a record using CDaoRecordset method.
rs.AddNew();
   rs.SetFieldValue(_T("MyGUIDField"),varGUIDValue);
rs.Update();
                

The same process applies to updating GUID fields, except that you would use the Edit rather than the AddNew method.

Note When calling GetFieldValue(), the variant is returned as type VT_BSTR.

Using Seek and FindFirst with GUID fields

Microsoft Access does not allow you to use GUID fields with the Find methods available to CDaoRecordset. If you attempt to use a Find method with a GUID field, the following error message appears:

GUID not allowed in Find method criteria expression

You can use the Seek method with GUIDs.

Sample code

// Open database.
CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
// Create a table called MySeekTable with a GUID primary key field named
// ID and a field named Found.
db.Execute(_T("create table MySeekTable (ID guid constraint PKEY primary
key, Found text)"));
// Insert a few records using an insert into statement.
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {11111111-aabb-aabb-aabb-aabbccddeeff}},'Guid1')"));
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {22222222-aabb-aabb-aabb-aabbccddeeff}},'Guid2')"));
db.Execute(_T("insert into MySeekTable (ID, Found) values ({guid {33333333-aabb-aabb-aabb-aabbccddeeff}},'Guid3')"));
// Open table-type recordset (must use table-type for Seek) and select
// index for seek.
CDaoRecordset rs(&db);
rs.Open(dbOpenTable,_T("MySeekTable"));
rs.SetCurrentIndex(_T("PKEY"));
// Construct the GUID you want to find and seek the GUID.
COleVariant varGUIDValue(_T("{guid {22222222-aabb-aabb-aabb-aabbccddeeff}}"), VT_BSTRT);
if (rs.Seek(_T("="),&varGUIDValue)) {
   // GUID found. Retrieve and display value.
   CString strResult = V_BSTRT(&rs.GetFieldValue(_T("Found")));
   AfxMessageBox("Seek of guid found '" + strResult + "'");
} else {
   // GUID not found.
   AfxMessageBox("Seek of guid failed.");
}

Using GUID fields with MFC ClassWizard-generated recordsets

The MFC ClassWizard automatically binds GUID fields to a CString class member and sets up the proper DoFieldExchange macros. No additional changes are needed to display, insert, and update GUID fields when you use the MFC ClassWizard to create CRecordset or CDaoRecordset derived classes. The fields are displayed in the Microsoft Access GUID format:

   {guid {11223344-1122-1122-1122-AABBCCDDEEFF}}

Creating "AutoNumber" GUID fields programmatically

Microsoft Access also provides an "AutoNumber" type GUID field. You can use this type of field for the primary key of a table and let Access automatically generate each new GUID. The GUIDs are randomly generated by the Microsoft Jet database engine each time a record is inserted into the table using an complex algorithm that will avoid duplicates over all databases in the world until the year 3400 AD.

You cannot create an "AutoNumber" type GUID field using SQL DDL, you must use DAO code. The following code demonstrates how to create an "AutoNumber" type GUID field using the CDaoTableDef::CreateField method.

Sample code

// Open database and create tabeldef.
CDaoDatabase db;
db.Open(_T("c:\\db1.mdb"));
CDaoTableDef td(&db);
td.Create(_T("MyGUIDTable"));
// Create and fill out a CDaoFieldInfo structure.
CDaoFieldInfo fi;
fi.m_strName = _T("ID");
fi.m_nType = dbGUID;
fi.m_lSize = 16;
fi.m_nOrdinalPosition = 0;
fi.m_bAllowZeroLength = FALSE;
fi.m_bRequired = FALSE;
fi.m_lAttributes = dbSystemField;
fi.m_strValidationRule = _T("");
fi.m_strValidationText = _T("");
fi.m_strDefaultValue = _T("GenGUID()"); // This generates the GUID.
// Create field using CDaoFieldInfo constructor and append table.
td.CreateField(fi);
td.Append();

REFERENCES

Microsoft Jet Database Engine Programmer's Guide, p. 246

Keywords: kbhowtomaster kbdatabase KB170117