Deleting Items by Using a Recordset
Topic Last Modified: 2007-02-16
To delete all items in a folder, you can use a Recordset object's Delete method.
Example
Description
The following example deletes all the items in a folder, except for subfolders that are stipulated by a WHERE clause.
Code
<job id="delete_record">
<reference object="adodb.record"/>
<script language='vbscript'>
Dim Info
Dim InfoNT
Dim sFolderUrl
Dim sQuery
Set Info = CreateObject("ADSystemInfo")
Set InfoNT = CreateObject("WinNTSystemInfo")
Dim Conn
Set Conn = CreateObject("ADODB.Connection")
Conn.Provider = "ExOLEDB.DataSource"
sFolderUrl = "http://" & InfoNT.Computername & "." & Info.DomainDNSName & "/public/test_folder2/"
Conn.Open sFolderUrl
' Delete all non-folder items from folder.
sQuery = "SELECT * FROM scope('shallow traversal of " & Chr(34) & sFolderUrl & Chr(34) & "')" & _
" WHERE ""DAV:isfolder"" = FALSE"
Dim cItems
cItems = deleteItemsMatchSQL(sQuery, Conn)
wscript.echo "Deleted " & cItems & " Items from " & sFolderUrl
' Close connection
Conn.Close
Function deleteItemsMatchSQL(sQuery, Conn )
Dim Rs
Dim cItems
Set Rs = CreateObject("ADODB.Recordset")
With Rs
.Open sQuery, Conn
.MoveFirst
cItems = .RecordCount
While Not Rs.EOF
.Delete 1 ' Current record
.MoveNext
Wend
.Close
End With
deleteItemsMatchSQL = cItems
End Function
</script>
</job>
Example
#import <msado15.dll> no_namespace
#import <cdoex.dll> no_namespace
void deleteitems(bstr_t url, bstr_t sqlCondition) {
_RecordsetPtr Rs(__uuidof(Recordset));
_ConnectionPtr Conn(__uuidof(Connection));
Conn->Provider = "ExOLEDB.DataSource";
bstr_t sqlStatement;
sqlStatement = "select \"DAV:href\" from scope('shallow traversal of \"";
sqlStatement += url;
sqlStatement += "\"') ";
sqlStatement += sqlCondition;
try {
Conn->Open(url, bstr_t(), bstr_t(),-1);
Rs->Open(
variant_t(sqlStatement),
variant_t((IDispatch*)Conn, true),
(CursorTypeEnum)-1,
(LockTypeEnum) -1,
-1
);
}
catch(_com_error e) {
// handle error or throw...
throw e;
}
long numRec = Rs->RecordCount;
cout << "Record count: " << numRec << endl;
try {
Rs->MoveFirst();
for(long i = 1 ; i <= numRec; i++ ) {
Rs->Delete(adAffectCurrent);
Rs->MoveNext() ;
}
}
catch(_com_error e) {
cerr << "Error deleting item using Recordset." << endl;
}
// Close connection
Conn->Close();
}