我需要用查询中的某些文本替换数字。
我使用此代码
SELECT [hostname]
,[assetTag]
,[business]
,[building]
,replace([Building],'700','ICT') AS BuildingNR
,replace([Building],'879','Sales') AS BuildingNR
FROM [osdDB].[dbo].[all_machines]
这是输出
hostname assetTag business building BuildingNR BuildingNR
ICT103961 A62609 ICT_IMO_E_M 879 879 Sales
ICT107826 A72752 ICT_IMO_SALES 700 ICT 700
ICT108923 A73433 ICT_IMO_SALES 700 ICT 700
ICT113735 A86955A ICT_IMO_IS 879 879 Sales
ICT108071 A73642 ICT_IMO_SALES 706 706 706
ICT110732 A86111 ICT_IMO_SALES 700 ICT 700
ICT108929 A73427 ICT_IMO_SALES 700 ICT 700
ICT109648 A72895A ICT_IMO_MRN 700 ICT 700
ICT110919 A86778 ICT_IMO_SALES 700 ICT 700
ICT102048 B81606A ICT_IMO_SALES 700 ICT 700
但我想要这个输出
hostname assetTag business building
ICT103961 A62609 ICT_IMO_E_M Sales
ICT107826 A72752 ICT_IMO_SALES ICT
ICT108923 A73433 ICT_IMO_SALES ICT
ICT113735 A86955A ICT_IMO_IS Sales
ICT108071 A73642 ICT_IMO_SALES ICT
ICT110732 A86111 ICT_IMO_SALES ICT
ICT108929 A73427 ICT_IMO_SALES ICT
ICT109648 A72895A ICT_IMO_MRN ICT
ICT110919 A86778 ICT_IMO_SALES ICT
ICT102048 B81606A ICT_IMO_SALES ICT
当我使用它时,我会得到很多行。我只想把它全部放在一排。
答案 0 :(得分:1)
您可以使用case when语句而不是替换值
SELECT [hostname],[assetTag],[business],[building],
case [Building]
when 700 then 'ICT'
when 879 then 'Sales'
else 'Value if not 700 or 879'
end as building
FROM [osdDB].[dbo].[all_machines]
答案 1 :(得分:1)
使用函数会更好:
CREATE FUNCTION [dbo].[f_GetBuildingName]
(
@Building int
)
RETURNS nvarchar(200)
AS
BEGIN
DECLARE @value nvarchar(200)
SELECT
@value=case @Building
when 700 then 'ICT'
when 879 then 'Sales'
else 'N/A'
end
FROM [osdDB].[dbo].[all_machines]
RETURN @value
END
在选择查询中使用函数:
SELECT [hostname],[assetTag],[business],[building],
[dbo].[f_GetBuildingName](building) as building
FROM [osdDB].[dbo].[all_machines]
您可以在任何function
查询中使用此select
,无需再次反复写入Case
语句。
如果要修改结果,则必须仅修改function
,而不是修改所有使用case语句进行此操作的select
查询。
希望这对你和其他人也有帮助..!:)