在case语句中分配多个列?

时间:2014-09-01 17:18:39

标签: sql-server tsql case

您有没有办法在案例陈述中分配多个列?

我正在尝试从另一列的案例陈述中分配两列数据,

SELECT 
  [FileName],
  CASE 
    WHEN [FileName] LIKE 'ATE_%' THEN CAST(SUBSTRING([FileName],5,5) + '/' + 'ABTA' AS nvarchar(100))
    WHEN [FileName] LIKE '%Adhoc%' THEN CAST([FileName] + ' ' + [SheetName] + '/' + 'FileSheet' AS nvarchar(100))
    WHEN [FileName] LIKE 'AdvantageData%' THEN CAST([SheetName] + '/' + 'Sheet' AS nvarchar(100))
  END AS ABTA_LookUp

这可行,但它会放

   FileName SheetName/FileSheet 

   SheetName/Sheet

   89765/ABTA

进入ABTALookUp

我希望将这些值拆分出来并在可能的情况下放在同一语句中的单独列中,即

    ABTALookUp = FileName SheetName
    ABTASource = FileSheet

    ABTALookUp = SheetName
    ABTASource = Sheet

    ABTALookUp = 89765
    ABTASource = ABTA

2 个答案:

答案 0 :(得分:4)

我认为您的样本所需输出并不清楚,但也许这就是您想要的?

SELECT 
  [FileName],
  CASE 
    WHEN [FileName] LIKE 'ATE_%' THEN CAST(SUBSTRING([FileName],5,5) AS NVARCHAR(100))
    WHEN [FileName] LIKE '%Adhoc%' THEN CAST([FileName] + ' ' + [SheetName] AS NVARCHAR(100))
    WHEN [FileName] LIKE 'AdvantageData%' THEN [SheetName] 
  END AS ABTALookUp,
  CASE 
    WHEN [FileName] LIKE 'ATE_%' THEN 'ABTA' 
    WHEN [FileName] LIKE '%Adhoc%' THEN 'FileSheet'
    WHEN [FileName] LIKE 'AdvantageData%' THEN 'Sheet' 
  END AS ABTASource

答案 1 :(得分:-7)

我感谢你的帮助

    INSERT INTO ABTA_LookUp
    SELECT  [FileName]
    ,CASE   WHEN [FileName] LIKE 'ATE_%' THEN CAST(SUBSTRING([FileName],5,5)+ '/'+ 'ABTA' AS nvarchar(100))
            WHEN [FileName] LIKE '%Adh%' THEN CAST([FileName] + ' ' + [SheetName] + '/' + 'FileSheet' AS nvarchar(100)) 
            WHEN [FileName] LIKE 'Adva%' THEN CAST([SheetName] + '/' + 'Sheet' AS nvarchar(100))
            END AS [ABTA_LookUp]
        ,NULL
        ,NULL
    FROM  dbo.BOOK

    UPDATE ABTA_LookUP
    SET ABTASource = 

    (
CASE    WHEN CAST(CHARINDEX('/FileSheet',[ABTA_LookUp],5)AS nvarchar) >1 THEN 'FileSheet'
        WHEN CAST(CHARINDEX('/HQABTA',[ABTA_LookUp],5)AS nvarchar) >1 THEN 'HQABTA'
        WHEN CAST(CHARINDEX('/ABTA',[ABTA_LookUp],5)AS nvarchar) >1 THEN 'ABTA'
        WHEN CAST(CHARINDEX('/',[ABTA_LookUp],5)AS nvarchar) >1 THEN 'HQABTA'
        END 
    )

UPDATE ABTA_LookUp          
SET DEL_SRT_PNT = CHARINDEX('/',[ABTA_LookUp],1)

UPDATE ABTA_LookUp
SET [ABTA_LookUp] = SUBSTRING([ABTA_LookUp],1,[DEL_SRT_PNT]-1)