Tuesday, March 6, 2012

"Order by" clause

I run the script below in sql2005 and am receiving the error msg 209. Do I
need a prefix to order by either STATE, TAXAMNT, or SUBTOTAL because I want
them displyed in front.
Thank you.
Charlie
select STATE, TAXAMNT, SUBTOTAL, *
from sop30200
where state in('NJ','NY','WA','CO','CA','ME','OK','VA','PA','T N')
AND SOPTYPE IN (3,4)
AND DOCDATE between '2007-02-01 00:00:00.000' and '2007-02-28 00:00:00.000'
--AND TAXEXMT1 = ' '
AND SUBTOTAL <> 0
--AND SOPNUMBE LIKE 'NCINV%'
AND VOIDSTTS = 0
AND SOPNUMBE NOT IN
(SELECT INVNO
FROM VERTEX..REGPRERETURNSTBL
WHERE COMPCD = 'ABS'
and invno between '20070201' and '20070228')
--AND SHIPTOGEOCODE LIKE '31%')
ORDER BY STATE DESC
Msg 209, Level 16, State 1, Line 1
Ambiguous column name 'STATE'.
While there is no actual ambiguity, the parser is not so sure.
Your select list contains the STATE column twice: once
explicitly as the first column and once again in the *. The
parser does not know whether you want to sort on the
source column sop30200.STATE or on the output column
STATE. They are the same in this query, but there are
queries where they could be different because some
output expression or column is aliased as STATE. The
parser does not try to figure out the meaning of the query.
There are two solutions. One is to specify
ORDER BY sop30200.STATE
and the other is to list all the columns you want in the output
separately and one each, not using the * notation. The second
solution is the better one, at least in production, because neither
* nor duplicate columns in the output are typically a good idea.
But if this is just a quick ad hoc query, the first solution is fine.
-- Steve Kass
-- Drew University
-- http://www.stevekass.com
chas2006 wrote:

>I run the script below in sql2005 and am receiving the error msg 209. Do I
>need a prefix to order by either STATE, TAXAMNT, or SUBTOTAL because I want
>them displyed in front.
>Thank you.
>Charlie
>select STATE, TAXAMNT, SUBTOTAL, *
>from sop30200
>where state in('NJ','NY','WA','CO','CA','ME','OK','VA','PA','T N')
>AND SOPTYPE IN (3,4)
>AND DOCDATE between '2007-02-01 00:00:00.000' and '2007-02-28 00:00:00.000'
>--AND TAXEXMT1 = ' '
>AND SUBTOTAL <> 0
>--AND SOPNUMBE LIKE 'NCINV%'
>AND VOIDSTTS = 0
>AND SOPNUMBE NOT IN
>(SELECT INVNO
>FROM VERTEX..REGPRERETURNSTBL
>WHERE COMPCD = 'ABS'
>and invno between '20070201' and '20070228')
>--AND SHIPTOGEOCODE LIKE '31%')
>ORDER BY STATE DESC
>
>Msg 209, Level 16, State 1, Line 1
>Ambiguous column name 'STATE'.
>

No comments:

Post a Comment