如何在Select Query中使用REPLACE? (SQL SERVER)

时间:2011-06-07 10:57:07

标签: sql-server-2008 select replace

我可以有条件地使用REPLACE功能吗? 例如我有一个问题:

SELECT diag_type FROM DIAGNOSIS

它返回AXIS,AXISI,AXISII,AXIS-C等。我想如果它返回一个有AXIS的结果,它会使它成为AXISIII。可以吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

;with DIAGNOSIS(diag_type) as
(
  select 'AXIS' union all
  select 'AXISI' union all
  select 'AXISII' union all
  select 'AXIS-C'
)

select
  case diag_type
    when 'AXIS' then 'AXISIII'
    else diag_type
  end as diag_type
from DIAGNOSIS

结果:

diag_type
---------
AXISIII
AXISI
AXISII
AXIS-C

答案 1 :(得分:0)

如果您只想要返回AXISIII,您可以写下:

SELECT 'AXISIII' FROM DIAGNOSIS WHERE diag_type = 'AXIS'

您还可以使用CASE语句添加更多选项(如果需要)。

SELECT  CASE(diag_type)
    WHEN 'AXIS' THEN 'AXISIII'
    WHEN 'AXIS-C' THEN'AXISIII-C'
    WHEN 'AXISII' THEN'AXISII'
    ELSE    'Something'
    END
FROM DIAGNOSIS