简体   繁体   中英

Dynamic SQL with computed fields

Good morning SQL professionals,

It is about the dynamic creation of complex SQL queries with MS SQL 2012. The task description is abstracted / simplified for better understanding. The following example would solve the problem but does not work:

Select 
   Left (Kunden ,10) AS Result01,
   Right (Result01,5) AS Result02
from tbl_Kunden

Please note: I want to use the result of the "Left" function in "Right" function (left and right are only placeholders for several other functions). However, this is due to an error: Invalid column name 'Result01'. Does anyone have an idea how to create a dyn. SQL query so that I can use the previously inserted named fields in the succeeding functions?

Thanks in advance, henuit

With subquery:

SELECT
    t.Result01,
    Right(t.Result01, 5) AS Result02
FROM
(
    SELECT
        Left(Kunden, 10) AS Result01,
    FROM tbl_Kunden
) as t

assuming that the output of the first function is compatible with the input of the second function you could do something like this.

Select 
   Left (Kunden ,10) AS Result01,
   Right (Left (Kunden ,10),5) AS Result02
from tbl_Kunden

Essentially SQL will evaluate a statement from the inner most nesting of a statement to the outermost so nesting the statements should get you where you need to be. Now if the output of the inner most or any inner statement for that matter is not compatible with the encapsulating function you may need to incorporate nested top 1 selects or cast's but without knowing the complete story of the process it is impossible to say what you might need to do.

/****************************Edit*****************************************************************************/ Based on you most recent comment I would suggest using a having statement. These will evaluate after the where clause and completion of the query. Used for evaluating aggregate functions. I would causion on over using this technique because it is taxing on processing with extremely large data sets because it executes after the completion of the query.

select foo, count(bar)
from table
where value = value
group by foo
having count(bar) >= number

this will allow you to evaluate the selected values without putting it in a sub query. This may or may not solve all of your issues but does serve its purpose when necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM