# Misplaced noalign with datatool and booktabs

I experience a (I’m afraid not so original) “Misplaced noalign” with the following example.

\documentclass{article}
\usepackage{booktabs}
\usepackage{datatool}

\begin{document}
\DTLnewdb{mydb}
\DTLnewrow{mydb}
\DTLnewdbentry{mydb}{column}{entry}
\begin{tabular}{l}
top\\
\DTLforeach*{mydb}{}{3\\}
\bottomrule
\end{tabular}
\end{document}


This produces:

Misplaced \noalign.
\bottomrule ->\noalign
{\ifnum 0=}\fi \@aboverulesep =\aboverulesep \global...
l.25 \bottomrule


and may many more errors that do not seem informative (Missing \cr inserted…).

The error disappears if commenting out the DTL line or replacing it with the content it should produce (namely, 3\\).

I have observed that putting the \\ first instead of last works around the problem. But this generally requires a conditional, using \DTLiffirstrow, as the result of the for each loop should generally not start with \\ (e.g., in the typical case of \DTLforeach immediately following a \toprule command), and makes the code slightly more obscure.

I also expect that building the table out of the tabular environment (following a common advice) would also solve the problem, but at the price of making the code much less readable.

I wonder if I’m doing anything wrong or if anything is wrong with my local installation, as this problem seems to be very seldom observed and the datatool manual suggest that it can be used together with booktabs. (I have seen some similar error message related to using booktabs, but I suspect my problem differs as I do not use the \input command.)

Both approaches feel more like working around the problem than solving it, IMHO. Therefore, my question is: is there a more elegant solution to this problem? (E.g. by patching some booktabs or DTL command in the preamble.)

you are hiding the last \ inside the DTLforeach and this separates it from the \bottomrule. That doesn't work.

Build the rows outside the tabular:

\documentclass{article}
\usepackage{booktabs}
\usepackage{datatool,etoolbox}

\begin{document}
\DTLnewdb{mydb}
\DTLnewrow{mydb}
\DTLnewdbentry{mydb}{column}{entry}

\newcommand\tabrows{}
\DTLforeach*{mydb}{}{\appto\tabrows{3\\}}
\begin{tabular}{l}
top\\
\tabrows
\bottomrule
\end{tabular}
\end{document}
`