SQL Server - index on a computed column?

后端 未结 4 1308
误落风尘
误落风尘 2020-12-10 11:38

I\'m joining to a table dozens of different times, and every time, I join (or filter) based on the results of a SUBSTRING of one of the columns (it\'s a string, but left-pad

4条回答
  •  失恋的感觉
    2020-12-10 12:28

    Assuming you have your fields in this format:

    00Data0007
    000000Data0011
    0000Data0015
    

    , you can do the following:

    • Create a computed column: ndata AS RIGHT(REVERSE(data), LEN(data) - 4)

      This will transform your columns into the following:

      ataD00
      ataD000000
      ataD0000
      
    • Create an index on that column

    • Issue this query to search for the string Data:

      SELECT  *
      FROM    mytable
      WHERE   ndata LIKE N'ataD%'
              AND SUBSTRING(ndata, LEN(N'ataD') + 1, LEN(ndata)) = REPLICATE('0', LEN(ndata) - LEN('ataD'))
      

      The first condition will use an index for coarse filtering.

      The second will make sure that all leading characters (that became the trailing characters in the computed column) are nothing but zeros.

    See this entry in my blog for performance detail:

    • SQL Server: leading wildcard match using an index

    Update

    If you just want an index on SUBSTRING without changing your schema, creating a view is an option.

    CREATE VIEW v_substring75
    WITH SCHEMABINDING
    AS
    SELECT  s.id, s.data, SUBSTRING(data, 7, 5) AS substring75
    FROM    mytable
    
    CREATE UNIQUE CLUSTERED INDEX UX_substring75_substring_id ON (substring75, id)
    
    SELECT  id, data
    FROM    v_substring75
    WHERE   substring75 = '12345'
    

提交回复
热议问题