Archives de l’auteur : Nicolas Riousset

À propos Nicolas Riousset

Président et fondateur de NeoLegal, développe des solutions logicielles qui facilitent le quotidien des professionnels du droit des sociétés.

How to delete from a table records which do not exist in another one ?

So, you want to delete records from a table when they are not in another one. To cleanup orphans for example.

The query is easy to write, but depending on the implementation, it may be really slow.

Let’s say you have two tables, A and B, with an « ident » prmary key column in each of them. You want to delete from A records whose « ident » is not in B.

The easiest way is to write :
[code lang= »sql »]
SELECT *
FROM A
WHERE NOT EXISTS ( SELECT * FROM B WHERE B.Ident = A.Ident)
[/code]
Another way :
[code lang= »sql »]
DELETE
FROM A
WHERE A.Ident NOT IN ( SELECT B.Ident FROM B )
[/code]
However, if both queries are corrects, they may be really long execute. That’s because for each record in A, the query must go through all the records in B to ensure there’s no match.

The following query is much faster, since we don’t use a « NOT IN » query, but a « IN » query. The subquery can be constructed once for all, and not for each records, and the comparison stops as soon as the record is found:
[code lang= »sql »]
DELETE
FROM A
WHERE A.Ident IN (SELECT A2.Ident from A A2 LEFT JOIN B on A2.Ident = B.Ident WHERE B.Ident IS NULL)
[/code]
 

Creating a new document in a MDI application

Suppose you want to create a new document manually in your MDI application. The following code allows to do this. It assumes that theApp is a CWinApp derived class holding a pointer m_pMyDocTpl to the CMultiDocTemplate which will instantiate your document. But you can use the CWinApp::GetFirstDocTemplatePosition() and CWinApp::GetNextDocTemplate() functions to select the type of document template.

CMultiDocTemplate* pDocTpl = theApp.m_pDocTpl;
CDocument* pDoc     = pMyDocTpl->CreateNewDocument();
CFrameWnd* pFrame   = pDocTpl->CreateNewFrame( pDoc, NULL);
pDocTpl->InitialUpdateFrame( pFrame, pDoc);

Getting list control events for a CListView

Imagine you have a CView derived view, like a CListView. You would like to do some treatments when events occurs on the list control ,like a double click. Since you don’t know the control ID of the CListCtrl in the CListView, you can’t just do a :

ON_NOTIFY(NM_DBLCLK, IDC_VIEWLISTCTRL, OnDblclkList)

This is the utilitiy of ON_NOTIFY_REFLECT

ON_NOTIFY(NM_DBLCLK, OnDblclkList)

Try it, it’s magic, it works !

Declaring a C++ function pointer type

There are some stuff that I can’t seem able to remember, no matter how hard I try. The C++ syntax of a function pointer type is one of them.

Just one example : a function pointer type for a function returning a bool and taking an int and a char* as parameters :

typedef bool (*FUNCTION_PTR)( int, char*);