我希望这对 SQL 专家来说是一个有趣的谜题。
当我运行以下查询时,我希望它不会返回任何结果。
-- Create a table variable Note: This same behaviour occurs in standard tables.
DECLARE @TestResults TABLE (Id int IDENTITY(1,1) NOT NULL, Foo VARCHAR(100) NOT NULL, About VARCHAR(1000) NOT NULL)
-- Add some test data Note: Without space, space prefix and space suffix
INSERT INTO @TestResults(Foo, About) VALUES('Bar', 'No spaces')
INSERT INTO @TestResults(Foo, About) VALUES('Bar ', 'Space Suffix')
INSERT INTO @TestResults(Foo, About) VALUES(' Bar', 'Space prefix')
-- SELECT statement that is filtered by a value without a space and also a value with a space suffix
SELECT
t.Foo
, t.About
FROM @TestResults t
WHERE t.Foo like 'Bar '
AND t.Foo like 'Bar'
AND t.Foo = 'Bar '
AND t.Foo = 'Bar'
结果返回一行:
[Foo] [About]
Bar Space Suffix
问题是人们正在从电子邮件等复制和粘贴值,并且他们以某种方式进入表格。我正在将此作为一个单独的问题进行研究,因为我将 LTRIM(RTRIM(Foo)) 作为 INSERT 和 UPDATE 触发器,但有些人正在以某种方式通过网络。
我需要更多地了解这种行为以及我应该如何解决它。
还值得注意的是 LEN(Foo) 也很奇怪,如下所示:
DECLARE @TestResults TABLE (Id int IDENTITY(1,1) NOT NULL, Foo VARCHAR(100) NOT NULL, About VARCHAR(1000) NOT NULL)
INSERT INTO @TestResults(Foo, About) VALUES('Bar', 'No spaces')
INSERT INTO @TestResults(Foo, About) VALUES('Bar ', 'Space Suffix')
INSERT INTO @TestResults(Foo, About) VALUES(' Bar', 'Space prefix')
SELECT
t.Foo
, LEN(Foo) [Length]
, t.About
FROM @TestResults t
给出以下结果:
[Foo] [Length] [About]
Bar 3 No spaces
Bar 3 Space Suffix
Bar 4 Space prefix
没有任何横向思考,我需要将 WHERE 子句更改为什么才能按预期返回 0 结果?