2014-06-24 65 views
0

我需要用查詢中的一些文本替換數字。sql替換1行中的值

我使用此代碼

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

plz發佈所需的輸出和完整的查詢。如果你創建一個sqlfiddle –

+0

並且完整的查詢 –

+0

返回的行數取決於你的'WHERE'子句,那將會更好。發佈剩餘的查詢。 – Coderchu

回答

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] 
+0

非常感謝。這是我需要的。我沒有考慮'時間'的情況。 – Tom

+0

我寧願寫一個函數,它會返回一個單一的值。也可以在多個選擇查詢中使用.. :) –

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] 

您可以在任何select查詢中使用此function,並且無需再次寫入Case聲明。

如果你想修改結果,你必須修改function而不是所有的select查詢你在哪裏使用這個操作的case語句。

希望這可以幫助你和其他人..!:)