views:

37

answers:

3

Does all the columns in select statement gets selected one after another as listed?

Declare @X, @Y

    SELECT 
    @X = ColumnA*.25 + ColumnB*2.5,
    @Y = ColumnA*.5 + ColumnC*1.33,
    TOTAL = @X + @Y
    FROM SomeTable

Is the above query safe to use? Will total always be selected after @X and @Y are calculated?

+3  A: 

You cannot mix column selection and variable assignments in one query.

If you select the total into a variable:

SELECT  @X = ColumnA*.25 + ColumnB*2.5,
        @Y = ColumnA*.5 + ColumnC*1.33,
        @TOTAL = @X + @Y
FROM    SomeTable

, then yes, @total will be assigned after @x and @y are calculated.

Quassnoi
But using a variable for total will make the total disappear from the output. My query has a lot more columns, joins.
Aseem Gautam
@aseem: again, you cannot mix variable assignments and column output. You should either return everything or assign everything, but not both. Your original query won't even compile.
Quassnoi
Yea... Its not compiling. I have dropped the local variables. Thanks.
Aseem Gautam
+2  A: 

If you intend to return a result set, I don't think this will work. It's better to write this in a portable way:

SELECT X, Y, X + Y AS TOTAL
  FROM (SELECT ColumnA*0.25 + ColumnB*2.5 AS X,
               ColumnA*0.5 + ColumnC*1.33 AS Y,
          FROM SomeTable) xxx
Marcelo Cantos
A: 

put it in a Common Table Expression CTE

CTE = more maintainable/readable queries

http://www.4guysfromrolla.com/webtech/071906-1.shtml

adolf garlic