Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and assign to variable in one statement?

I'd like to display the results of a query, and I'd like to capture a column's value at the same time. The FROM and WHERE are the same in both queries. Can I do both in one query, or is it easier/better to just do the query twice, like this?

DECLARE @fooId INT

SET @fooId = (SELECT FooId FROM Bar WHERE SnuhId = 5)

SELECT * FROM Bar WHERE SnuhId = 5
like image 382
Bob Horn Avatar asked Mar 10 '14 14:03

Bob Horn


1 Answers

Unfortunately it has to be done in two operations.

Test:

DECLARE @VAR DATETIME
SELECT @VAR=GETDATE(), GETDATE()

Yields error message 141.

Here's another SO post on this.

like image 143
Dave Cullum Avatar answered Oct 06 '22 22:10

Dave Cullum