A reader asked a question recently, which prompted this mini-article. Here's the email I received:"Hi, I use a tool called Drumbeat 2000 for some of my development. What it allows my to do, is create recordsets with whatever name I like. I've looked at your code and have converted what I like to VBScript. So I have an include file called database.asp that will create my connection and create one recordset, but I would like to be able to pass a name to the function and have the function create a recordset with the name I pass it. I've searched the web, and can't find anyone doing this. Any ideas? |
The answer is shown below. All I had to do was create an object, and use "expando properties" to fill it with recordsets. The function DBGetNamedRecords takes the name of the recordset and the SQL to fill it. "Expando properties" are properties that can be added dynamically at run-time. For example, saying a.name = "hello" is creating a property called name. If you need to create a property containing spaces you can use the alternative syntax a [ "my name" ] = "hello" Read more about expando properties at the Microsoft JScript Reference. <%
// object containing multiple recordsets
var oNamedRS = new Object;
// using my database library in utils/Database.asp
DBInitConnection ( );
// create some named recordsets
DBGetNamedRecords ( 'category' , 'SELECT * FROM ArticleCategories' );
DBGetNamedRecords ( 'articles' , 'SELECT * FROM Articles' );
DBGetNamedRecords ( 'content' , 'SELECT * FROM Content' );
// output a field from each to show it worked
Out ( oNamedRS [ 'category' ]( 0 ) + '<br>' );
Out ( oNamedRS [ 'articles' ]( 0 ) + '<br>' );
Out ( oNamedRS [ 'content' ]( 0 ) + '<br>' );
// release the connection and the named recordsets
DBReleaseConnection ( );
// ============================================
// executes the passed in SQL and adds a named recordset to object
// ============================================
function DBGetNamedRecords ( sName, sSQL )
{
// create recordset and place it in object property
oNamedRS [ sName ] = Server.CreateObject( 'ADODB.Recordset' );
// execute SQL to fill recordset
oNamedRS [ sName ].Open ( sSQL, oConnection, adOpenForwardOnly, adLockReadOnly );
}
%> |
|