views:

51

answers:

2

I have a query that looks like this:

Insert Into tblX (a,b,c)
Select x as a, y as b
   (select top 1 whatever from tblZ as z where z.aID  = y.aID order by z.s desc) as c
from tblY as y
where y.foo = 'bar'
AND c <> NULL

The problem is that last line. It tells me that c is an invalid column name. using y.c as well, to the same result. I need to not inset rows where that giant inner query is null, because tblX cannot accept nulls there. I feel like I should be able to filter on that column, but I can't quite get the syntax right.

+2  A: 

You will probably need to double-nest this query.

Also, depends on your DBMS, but you should be checking C IS NOT NULL

You are using two tables without a join. If you tell us what you are trying to achieve, we can help better.

Raj More
Works like a charm. Thank you!
CaptnCraig
hmmm. Not too sure what that means. Edited question to clarify.
CaptnCraig
@CaptnCraig: RE: `"Works like a charm. Thank you!"`       Is this question answered or not?
Brock Adams
It was answered, but then edited the solution away. If you could put it back I would accept.
CaptnCraig
@CaptnCraig: Interesting. This answer doesn't show as edited (Raj More might have changed it within a minute or two of 1st posting), so it can't be put back. It's still correct within the level of detail of the question. Mark it answered and/or post the solution that works as your own answer.
Brock Adams
A: 

What ended up working is double nesting the query.

Insert Into tblX (a,b,c)
  Select a,b,c from
    (select x as a,
           y as b,
     (select top 1 whatever from tblZ as z where z.aID  = y.aID order by z.s desc) as c
      from tblY as y where y.foo = 'bar') as foobar
  Where c IS NOT NULL
CaptnCraig