TSQL最佳实践定义可重用变量

时间:2018-02-09 13:50:49

标签: sql sql-server

我想要改编以下查询。

SELECT t1.[Field1], t1.[Field2]     
,CASE
    WHEN t1.[Field3] LIKE '%SOMETEXT1%' THEN 'X1'
    WHEN t1.[Field3] LIKE '%SOMETEXT2%' THEN 'X2'
    WHEN t1.[Field3] LIKE '%SOMETEXT3%' THEN 'X3'
    WHEN t1.[Field3] LIKE '%SOMETEXT4%' THEN 'X4'
    WHEN t1.[Field3] LIKE '%SOMETEXT5%' THEN 'X5'
END
FROM Table1 t1

我希望将t1.[Field3]清理为

LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) AS CleanField3

是否可以将其定义为变量,因此我可以编写类似下面的内容

SELECT t1.[Field1], t1.[Field2]     
,CASE
    WHEN CleanField3 LIKE '%SOMETEXT1%' THEN 'X1'
    WHEN CleanField3 LIKE '%SOMETEXT2%' THEN 'X2'
    WHEN CleanField3 LIKE '%SOMETEXT3%' THEN 'X3'
    WHEN CleanField3 LIKE '%SOMETEXT4%' THEN 'X4'
    WHEN CleanField3 LIKE '%SOMETEXT5%' THEN 'X5'
END
FROM Table1 t1

而不是

SELECT t1.[Field1], t1.[Field2]     
,CASE
    WHEN LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) LIKE '%SOMETEXT1%' THEN 'X1'
    WHEN LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) LIKE '%SOMETEXT2%' THEN 'X2'
    WHEN LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) LIKE '%SOMETEXT3%' THEN 'X3'
    WHEN LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) LIKE '%SOMETEXT4%' THEN 'X4'
    WHEN LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) LIKE '%SOMETEXT5%' THEN 'X5'
END
FROM Table1 t1

我已经看过使用变量,但却看不到让它们以这种方式工作的方法?例如https://technet.microsoft.com/en-us/library/ms187953(v=sql.105).aspx

2 个答案:

答案 0 :(得分:4)

你不能用变量做,你可以用子查询来做:

SELECT  T.[Field1]
,       T.[Field2] 
,       CASE
            WHEN CleanField3 LIKE '%SOMETEXT1%' THEN 'X1'
            WHEN CleanField3 LIKE '%SOMETEXT2%' THEN 'X2'
            WHEN CleanField3 LIKE '%SOMETEXT3%' THEN 'X3'
            WHEN CleanField3 LIKE '%SOMETEXT4%' THEN 'X4'
            WHEN CleanField3 LIKE '%SOMETEXT5%' THEN 'X5'
        END
FROM    (
            SELECT  t1.[Field1]
            ,       t1.[Field2]     
            ,       LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3]))) CleanField3
            FROM    Table1 t1
        ) T

答案 1 :(得分:1)

您可以使用Cross apply来避免子查询:

SELECT t1.[Field1], t1.[Field2]     
,CASE
    WHEN f3 LIKE '%SOMETEXT1%' THEN 'X1'
    WHEN f3 LIKE '%SOMETEXT2%' THEN 'X2'
    WHEN f3 LIKE '%SOMETEXT3%' THEN 'X3'
    WHEN f3 LIKE '%SOMETEXT4%' THEN 'X4'
    WHEN f3 LIKE '%SOMETEXT5%' THEN 'X5'
END
FROM Table1 t1
    CROSS APPLY (SELECT f3 = LEFT(t1.[Field3], LEN(t1.[Field3]) - CHARINDEX('(',REVERSE(t1.[Field3])))) Q