[英]CHAR behavior with trailing spaces
Given the SQL statements below, I would expect the result of the query to be: 给定下面的SQL语句,我希望查询的结果是:
|testX|5|
|XXXXX|5|
This is because the column is a char(5) and I would expect it to insert blank trailing spaces to fill the remaining space in the column since the inserted values are less than five characters. 这是因为该列是char(5),并且我希望它插入空白尾随空格以填充该列中的剩余空间,因为插入的值少于五个字符。 However, the query actually produces the following result:
但是,查询实际上会产生以下结果:
|test|4|
|X|0|
Can someone please explain this. 有人可以解释一下吗。 Why aren't the values padded with trailing blanks to make them fill up the length 5 column?
为什么不用尾随空格填充值以使它们填满长度5列? Why does the REPLACE function insert a single X for the second value when it is a completely empty string?
为什么当第二个值完全为空字符串时,REPLACE函数会为第二个值插入单个X?
USE Test;
GO
SET ANSI_PADDING ON;
GO
CREATE TABLE BlankTest
(
Value char(5) NOT NULL
);
GO
INSERT INTO BlankTest (
Value
) VALUES (
'test'
);
GO
INSERT INTO BlankTest (
Value
) VALUES (
''
);
GO
SELECT REPLACE(Value, ' ', 'X'), LEN(Value)
FROM BlankTest;
GO
DROP TABLE BlankTest;
REPLACE returns varchar REPLACE返回varchar
Try this for the SELECT 尝试此SELECT
...REPLACE(Value, ' ', 'ZZZZZZZZZ')
This can't be char(5), of course, so what is it 当然不能是char(5),那是什么
...SQL_VARIANT_PROPERTY (REPLACE(Value, ' ', 'ZZZZZZZZZ'), 'MaxLength')...
8000, max of varchar... 8000,最大varchar ...
Edit: 编辑:
My smart alec colleague reminded me that you'd need to use DATALENGTH to include trailing spaces, not LEN. 我聪明的alec同事提醒我,您需要使用DATALENGTH包含尾随空格,而不要使用LEN。 Asked often here
在这里经常问
WHERE value = 'test'
. WHERE value = 'test'
。 'test' here is varchar which has a higher precedence (fixed) than char, so the column is converted to varchar, thus effectively truncating 这里的“测试”是varchar,它的优先级(固定)比char高,因此该列将转换为varchar,从而有效地截断
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.