Question: I have this code, i'm trying to set the identity seed by a varable

```
DECLARE @iKeyX INT

SELECT @iKeyX = MAX(KeyX) FROM Temporales..tmp_Orders

IF (@iKeyX = NULL)
   SET @iKeyX = 1
ELSE
   SET @iKeyX = @iKeyX + 1

IF OBJECT_ID('tempdb..#tmp_Orders','U') IS NOT NULL
   DROP TABLE #tmp_Orders

SELECT  IDENTITY(INT, @iKeyX, 1) AS KeyX,
        0 AS Valido, 
        OrderNumber, 
        OrderType, 
        Code, 
        Size, 
INTO #tmp_Orders
FROM TableWithData

```

Why SQL keeps telling me "Incorrect syntax near '@ iKeyX'"?

Answer: 
For the sake a completion:

In rails 3 you could actually get away with only one query, but they recommend using joins as well: 
User.includes(:event\_patrons).where("event\_patrons.event\_id", 1)

Source: [Specifying Conditions on Eager Loaded Associations](http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations)

I was confused with joins and includes in the beginning as well, but there is a big difference:

* include basically does an eager loading on the association. This is useful when you're going to do something like this:

```
@users.each do |user|
  user.event_patrons.first.event_id
end

```

If you have 100 users then you'll you've just generated 100 extra queries (the 1+N problem).
* sometimes you need to specify a condition on the association (like in your case) and this is where joins are useful, but don't over-abuse it, or you'll run into the cartesian product overload problem.

A great article on all this: can be found here, might be for rails 2.1 but still applicable for Rails 3 as well: <http://akitaonrails.com/2008/05/25/rolling-with-rails-2-1-the-first-full-tutorial-part-2>
Rails does that on purpose. You should use the query like this:

```
User.all(:joins => :event_patrons, 
         :conditions => {:event_patrons => {:event_id => 1}}
         :include => :event_patrons)

```

That will generate 2 queries. One for the users:

```
SELECT `users`.* FROM `users` 
INNER JOIN `event_patrons` ON `event_patrons`.`user_id` = `users`.`id` 
WHERE `event_patrons`.`event_id` = 1

```

And one for the associated event\_patrons:

```
SELECT `event_patrons`.* FROM `event_patrons` WHERE `event_patrons`.`id` IN (1,2,3...)

```

You could do what you want, by specifying the :select option, but I wouldn't advise this, because then it doesn't construct the event\_patrons models, it leaves the data in the users model.