TITLE: When does glueing affine schemes produce affine/separated schemes?
QUESTION [5 upvotes]: Let $X$ be an affine scheme with an open affine subscheme $U\subset X$. Given an automorphism of $U$, we can glue $X$ with itself along $U$ to get a new scheme. Is there a description in terms of commutative algebra of automorphisms such that the resulting scheme is affine/separated? 
If $U=\mathrm{Spec}\:B$, $X=\mathrm{Spec}\:A$, then $B$ is an $A$-algebra of finite presentation so there's a chance to be explicit.
For example, if $X=\mathrm{Spec}\:k[x]$ and $U=\mathrm{Spec}\:k[x, \frac{1}{x}]$ if we take the identity on $U$ the result is non-separated and if we take $x\rightarrow \frac{1}{x}$ the result is separated.
I'm especially interested in what happens for $X$ the spectrum of a discrete valuation ring or a PID.
Here is a commutative algebra description of open immersions between affine schemes (not a very convenient one I'd guess).

REPLY [5 votes]: There is a general criterion that explains when a gluing of two separated schemes is separated. 

Proposition: Let $X_1, X_2$ be a separated $S$-schemes, $U_i$ open subschemes in $X_i$ (for $i=1, 2$), and $f:U_1 \to U_2$ an $S$-isomorphism. Then the $S$-scheme $X$ obtained as a gluing of $X_1$ and $X_2$ along the isomorphism $f$ is separated if and only if the ``diagonal'' morphism
  $$
U_1 \to X_1\times_S X_2
$$
  is a closed immersion.

In the situation $U_1=\operatorname{Spec} A$ and $X_1=X_2=\operatorname{Spec} B$ are affine the criterion says that separtedness of $X$ is equivalent to surjectivity of the map
$$
\phi:B\otimes_{\mathbf Z} B \to A
$$ 
defined by $\phi(a\otimes a')=af^*(b)$.