is of a type that is invalid for use as a key column in an index

后端 未结 5 2016
我在风中等你
我在风中等你 2020-11-29 21:57

I have an error at

Column \'key\' in table \'misc_info\' is of a type that is invalid for use as a key column in an index.

where key is a n

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 22:36

    There is a limitation in SQL Server (up till 2008 R2) that varchar(MAX) and nvarchar(MAX) (and several other types like text, ntext ) cannot be used in indices. You have 2 options:
    1. Set a limited size on the key field ex. nvarchar(100)
    2. Create a check constraint that compares the value with all the keys in the table. The condition is:

    ([dbo].[CheckKey]([key])=(1))
    

    and [dbo].[CheckKey] is a scalar function defined as:

    CREATE FUNCTION [dbo].[CheckKey]
    (
        @key nvarchar(max)
    )
    RETURNS bit
    AS
    BEGIN
        declare @res bit
        if exists(select * from key_value where [key] = @key)
            set @res = 0
        else
            set @res = 1
    
        return @res
    END
    

    But note that a native index is more performant than a check constraint so unless you really can't specify a length, don't use the check constraint.

提交回复
热议问题