Tuesday, August 26, 2008

Assign a variable from a Select result with SQL Server

Sometimes will be useful saving a Select query result in a variable, perhaps to reuse it inside another query.
The command to do that is very simple:

DECLARE @variable AS datatype

SELECT @variable = Filed FROM Table WHERE Condition

We only have to comply with certain conditions:
  • datatype must be of the same datatype of Field
  • if the query return more than 1 row, the variable contains the last row value
  • is not possible to use TOP clause

No comments: