我有一个包含计算VARCHAR列的表,最多包含106个字符:
CREATE TABLE report (
report_id INT IDENTITY(1, 1) NOT NULL,
name VARCHAR(100) COLLATE Modern_Spanish_CI_AI NOT NULL,
city_id VARCHAR(6) COLLATE Modern_Spanish_CI_AI,
unique_name AS
CASE
WHEN city_id IS NULL
THEN name
ELSE name + REPLICATE(' ', 100 - LEN(name)) + city_id
END COLLATE Modern_Spanish_CI_AI,
CONSTRAINT report_pk PRIMARY KEY (report_id)
);
/* Report name is unique per city (and among city-less rows) */
CREATE UNIQUE INDEX report_idx1 ON report (unique_name);
但是当我运行声明时,我收到了这个警告:
警告!最大密钥长度为900字节。索引'report_idx1' 最大长度为8000字节。对于一些大的组合 值,插入/更新操作将失败。
有没有办法告诉SQL Server该列不会超过106个字符,所以我摆脱了警告?
答案 0 :(得分:4)
试试CAST(CASE ... END AS VARCHAR(106))
...
CAST(CASE
WHEN city_id IS NULL
THEN name
ELSE name + REPLICATE(' ', 100 - LEN(name)) + city_id
END AS VARCHAR(106)) COLLATE Modern_Spanish_CI_AI
或者完全忽略它......这只是一个警告。