Simplest way to process multiple hardcoded values

2019-06-27 02:02发布

问题:

How would I do this in SQL Server? (I know it won't run as written but it illustrates the question better than I can explain)

SELECT SQRT(number) WHERE number IN (4,9,16,25)

It would return multiple rows of course

回答1:

you can use table value constructor

select sqrt(number) 
from (
    values (4),(9),(16),(25)
) as T(number)

or use union all

select sqrt(number)
from (
    select 4 union all
    select 9 union all
    select 16 union all
    select 25
) as T(number)

sql fiddle demo



回答2:

You could create a derived table:

SELECT SQRT(number)
FROM (
    SELECT 4 AS number
    UNION ALL SELECT 9
    UNION ALL SELECT 16
    UNION ALL SELECT 25
) A