开发者

Select statement always execute/select columns in order?

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

Declare 开发者_如何学JAVA@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?


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.


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


put it in a Common Table Expression CTE

CTE = more maintainable/readable queries

https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜