SQL Sever Books Onlines 上的例子不知是否合用
======================================
This example creates a primary key index.
// This CREATE TABLE statement shows the referential integrity and
// PRIMARY KEY constraint on the OrderDetails table that will be created
// by the following example code.
//
// CREATE TABLE OrderDetails
// (
// OrderID int NOT NULL
// ProductID int NOT NULL
// CONSTRAINT PK_OrderDetails
// PRIMARY KEY CLUSTERED (OrderID, ProductID),
// UnitPrice money NOT NULL,
// Quantity int NOT NULL,
// Discount decimal(2,2) NOT NULL
// DEFAULT 0
// )
//
HRESULT CreatePrimaryKey
(
IIndexDefinition* pIIndexDefinition
)
{
HRESULT hr = S_OK;
DBID dbidTable;
DBID dbidIndex;
const ULONG nCols = 2;
ULONG nCol;
const ULONG nProps = 2;
ULONG nProp;
DBINDEXCOLUMNDESC dbidxcoldesc[nCols];
DBPROP dbpropIndex[nProps];
DBPROPSET dbpropset;
DBID* pdbidIndexOut = NULL;
// Set up identifiers for the table and index.
dbidTable.eKind = DBKIND_NAME;
dbidTable.uName.pwszName = L"OrderDetails";
dbidIndex.eKind = DBKIND_NAME;
dbidIndex.uName.pwszName = L"PK_OrderDetails";
// Set up column identifiers.
for (nCol = 0; nCol < nCols; nCol++)
{
dbidxcoldesc[nCol].pColumnID = new DBID;
dbidxcoldesc[nCol].pColumnID->eKind = DBKIND_NAME;
dbidxcoldesc[nCol].eIndexColOrder = DBINDEX_COL_ORDER_ASC;
}
dbidxcoldesc[0].pColumnID->uName.pwszName = L"OrderID";
dbidxcoldesc[1].pColumnID->uName.pwszName = L"ProductID";
// Set properties for the index. The index is clustered,
// PRIMARY KEY.
for (nProp = 0; nProp < nProps; nProp++)
{
dbpropIndex[nProp].dwOptions = DBPROPOPTIONS_REQUIRED;
dbpropIndex[nProp].colid = DB_NULLID;
VariantInit(&(dbpropIndex[nProp].vValue));
dbpropIndex[nProp].vValue.vt = VT_BOOL;
}
dbpropIndex[0].dwPropertyID = DBPROP_INDEX_CLUSTERED;
dbpropIndex[0].vValue.boolVal = VARIANT_TRUE;
dbpropIndex[1].dwPropertyID = DBPROP_INDEX_PRIMARYKEY;
dbpropIndex[1].vValue.boolVal = VARIANT_TRUE;
dbpropset.rgProperties = dbpropIndex;
dbpropset.cProperties = nProps;
dbpropset.guidPropertySet = DBPROPSET_INDEX;
hr = pIIndexDefinition->CreateIndex(&dbidTable, &dbidIndex, nCols,
dbidxcoldesc, 1, &dbpropset, &pdbidIndexOut);
// Clean up dynamically allocated DBIDs.
for (nCol = 0; nCol < nCols; nCol++)
{
delete dbidxcoldesc[nCol].pColumnID;
}
return (hr);
}