How to: Fetch Columns Using IRow::GetColumns (OLE DB)

The IRow interface allows direct access to columns of a single row in the result set. Thus, IRow is an efficient way to retrieve columns from a result set with one row.

A code sample is available that showshow to fetch a single row using IRow. In this sample, one column at a time is retrieved from the row. The sample shows:

  • How to fetch a group of columns (in sequence).

  • How to access a column twice. The first time the actual column width is obtained, and later the actual data is accessed. In the DBCOLUMNACCESS structure, if pData is NULL and cbMaxLen is 0, the call to IRow->GetColumns() returns only the actual column length. In this case, IRow->GetColumns() can be called again on the same column to retrieve the actual data.

The complete sample code is in the file FetchColumns_B.cpp. You can download an archive containing the sample from the SQL Server Downloads page on MSDN.

This sample was developed using Microsoft Visual C++ 2005.

The code below creates the sample table used by FetchColumns_B.cpp.

USE AdventureWorks2008R2;
GO

IF EXISTS (SELECT name FROM sysobjects WHERE name = 'MyTable')
     DROP TABLE MyTable;
GO

CREATE TABLE MyTable
(
     col1  int,
     col2  varchar(50),
     col3  char(50),
     col4  datetime,
     col5  float,
     col6  money,
     col7  sql_variant,
     col8  binary(50),
     col9  text,
     col10 image
);
GO
INSERT INTO MyTable
values
(
     10,
     'abcdefghijklmnopqrstuvwxyz',
     'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
     '11/1/1999 11:52 AM',
     3.14,
     99.95,
     CONVERT(nchar(50), N'AbCdEfGhIjKlMnOpQrStUvWxYz'),
     0x123456789,
     REPLICATE('AAAAABBBBB', 500),
     REPLICATE(0x123456789, 500)
);
GO
Security noteSecurity Note

When possible, use Windows Authentication. If Windows Authentication is not available, prompt users to enter their credentials at run time. Avoid storing credentials in a file. If you must persist credentials, you should encrypt them with the Win32 crypto API.

To fetch columns using IRow::GetColumns

  1. Establish a connection to the data source.

  2. Execute the command (in the following example, ICommandExecute::Execute() is called with IID_IRow).

  3. Execute IRow::GetColumns() to fetch one or more columns in the resulting row. If you want to find the actual column size before fetching data, set the pData in DBCOLUMNACCESS to NULL. The call to IRow::GetColumns() returns only the column width. Another call the IRow::GetColumns() will fetch the data.

  4. Execute IRow::GetColumns() until all the columns you need are accessed. The columns must be accessed in sequence.

See Also

Other Resources