tags:

views:

113

answers:

4

If I want to set a variable to a field in a table I normally use something like

SELECT @UserIdToUpdate = userId FROM #NewUsers

In this case there will be multiple results and I just want the first one so I tried this but it fails and says invalid syntax top

SELECT @UserIdToUpdate = TOP 1 UserId FROM #NewUsers

If this is this case can I just usethe first example without the top? I assume it will just take the first record? I know it seems like on odd thing to do but the command is in a loop so it will select a record, do something with it, delete it then select the next one.

A: 

This should work

SELECT @UserIdToUpdate = userId FROM #NewUsers LIMIT 1
jitter
Just tried that it says invalid syntax near 1, I'm using SQL Server 2005 if that makes a difference
Gavin Draper
LIMIT is valid syntax in some other SQL dialects (not sure which). T-SQL uses TOP.
Christian Hayter
+5  A: 
SELECT @UserIdToUpdate = NULL
SELECT TOP 1 @UserIdToUpdate = userId FROM #NewUsers

The first statement is needed because if the second finds zero rows, then the variable will not get assigned at all and will keep its prior value.

Alternatively,

SELECT @UserIdToUpdate = (SELECT TOP 1 userId FROM #NewUsers)

this will work even if zero rows are found.

Christian Hayter
A: 
SELECT @UserIdToUpdate = (SELECT TOP 1 UserId FROM #NewUsers)

But I believe your first query will work as well, if you then delete this row. And SQL Server should not read all the rows, but actually should select only the first one (in arbitrary order)

van
A: 
SELECT TOP 1 @UserIdToUpdate = UserId FROM #NewUsers
shahkalpesh