开发者

Convert result within statement

开发者 https://www.devze.com 2023-01-09 00:25 出处:网络
Let\'s say I have the following simple query SELECT TOP 1 name FROM months which returns name = \"march\". Is it possible to convert this result? Instead of \"march\" I want name = \"3\". Is SQL ca

Let's say I have the following simple query

SELECT TOP 1 name FROM months

which returns name = "march". Is it possible to convert this result? Instead of "march" I want name = "3". Is SQL capable of doing such things? I'm using a MSSQL databas开发者_StackOverflow社区e.

[update] Corrected the query. While writing this simple example I mixed it up with MySQL [/update]


If you want to map a fixed set of input values against a fixed set of output values, CASE WHEN is your friend:

SELECT
  CASE name
    WHEN 'january'  THEN 1
    WHEN 'february' THEN 2
    WHEN 'march'    THEN 3
    /* ... */
  END as num
FROM
  months


If you just want month number, you could do this:

SELECT
   CASE
      WHEN name = 'January' then 1
      WHEN name = 'February' then 2
      WHEN name = 'March' then 3
      WHEN name = 'April' then 4
      WHEN name = 'May' then 5
      WHEN name = 'June' then 6
      WHEN name = 'July' then 7
      WHEN name = 'August' then 8
      WHEN name = 'September' then 9
      WHEN name = 'October' then 10
      WHEN name = 'November' then 11
      WHEN name = 'December' then 12
   END month_num
FROM months


If you're really using SQL server, you could try the following

SELECT TOP 1 MONTH(CAST('01 ' + name + ' 2000' AS DATETIME))
FROM months

But as others have said, your use of the LIMIT keyword suggests you might be on another RDBMS


In Oracle we use DECODE. But I think in SQL Server you have to go with CASE. Example:

SELECT CASE WHEN name = 'March' THEN '3' 
            WHEN name = 'April' THEN '4' 
            ELSE 'something else' 
       END
FROM months


Try using SQLServer's date conversion functions, like so:

select TOP 1 datepart(month,convert(datetime, left(name,3) + ' 01, 01', 107))
FROM months


Just for variety

SELECT 
CEILING(CHARINDEX(name,'January   February  March     April     May       June      July      August    September October   November  December'
COLLATE sql_latin1_general_cp1_ci_as )/10.0) 
 month_num
 FROM months


I think the best you'll be able to do is a CASE statement.

select case name
           when 'January' then 1
           when 'February' then 2
           ...
           when 'December' then 12
       end as MonthNumber
   from months
0

精彩评论

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