SQL喜欢带通配符的单个字母

时间:2015-03-26 13:28:13

标签: sql-server

我对SQL数据库的SQL查询有问题。我不能简单地找出原因。

我想得到ShortName包含'A'的所有行。

ShortName列的数据类型为nvarchar(max)

我的表格如下:

如果我在数据库上执行此查询: SELECT ID, ShortName FROM Airports where ShortName LIKE '%A%';

结果:

如果我这样查询: SELECT ID, ShortName FROM Airports where ShortName LIKE '%AA%';

结果:

你可以看到它不占用所有行,shortname包含'A'。 但为什么?我已经找到了答案,但我找不到它。

4 个答案:

答案 0 :(得分:4)

由于您在斯堪的纳维亚半岛,您的数据库默认排序很可能是Danish_Norwegian_CI_AS。这将导致AA作为Å

进行插入

因此,要使查询正常工作,请使用:

SELECT ID, ShortName FROM Airports 
where ShortName LIKE '%A%' 
COLLATE Latin1_General_CI_AS;

答案 1 :(得分:1)

归结为您在数据库中使用哪种排序规则,我猜是因为AA可以在某种语言中以不同的方式相互关联(例如丹麦语)
如果您执行以下操作,则每个选项都会得到不同的结果。

DECLARE @t TABLE (v VARCHAR(max))
INSERT INTO @t VALUES ('AAR')
SELECT * FROM @t WHERE v COLLATE SQL_Latin1_General_CP1255_CS_AS LIKE '%A%' COLLATE SQL_Latin1_General_CP1255_CS_AS

SELECT * FROM @t WHERE v COLLATE Danish_Norwegian_CI_AI LIKE '%A%' COLLATE Danish_Norwegian_CI_AI

这给了我第一个结果AAR,第二个结果没什么。

答案 2 :(得分:0)

你能编写表和数据的脚本吗?

如果我这样做:

SELECT CAST(1 as int) AS ID, CAST('AAR' AS nvarchar(MAX)) AS ShortName INTO #Airports

INSERT INTO #Airports
SELECT 2, 'CPH' UNION ALL
SELECT 3, 'STA' UNION ALL
SELECT 4, 'AAL' UNION ALL
SELECT 5, 'CNL' UNION ALL
SELECT 6, 'ZGH' UNION ALL
SELECT 7, 'ROD' UNION ALL
SELECT 8, 'KRP' 

SELECT * FROM #Airports a
SELECT ID, ShortName FROM #Airports where ShortName LIKE '%A%';
SELECT ID, ShortName FROM #Airports where ShortName LIKE '%AA%';

我确实得到了预期的结果:

         ID ShortName
----------- ----------------------------------------------------------------
          2 CPH
          3 STA
          4 AAL
          5 CNL
          6 ZGH
          7 ROD
          8 KRP
          1 AAR

(8 row(s) affected)

         ID ShortName
----------- ----------------------------------------------------------------
          3 STA
          4 AAL
          1 AAR

(3 row(s) affected)

         ID ShortName
----------- ----------------------------------------------------------------
          4 AAL
          1 AAR

(2 row(s) affected)

答案 3 :(得分:-1)

很奇怪,当我执行你的第一个查询时:

CREATE TABLE  testtt
(
ID int IDENTITY(1,1) NOT NULL PRIMARY KEY,
ShortName nvarchar(max),
);

insert into testtt (ShortName) values ('AAR');
insert into testtt (ShortName) values ('BLL');
insert into testtt (ShortName) values ('CPH');
insert into testtt (ShortName) values ('EBJ');
insert into testtt (ShortName) values ('KRP');
insert into testtt (ShortName) values ('ODE');
insert into testtt (ShortName) values ('RKE');
insert into testtt (ShortName) values ('RNN');
insert into testtt (ShortName) values ('SGD');
insert into testtt (ShortName) values ('SKS');
insert into testtt (ShortName) values ('TED');
insert into testtt (ShortName) values ('STA');
insert into testtt (ShortName) values ('AAL');
insert into testtt (ShortName) values ('CNL');
insert into testtt (ShortName) values ('WGH');


SELECT ID, ShortName
FROM testtt
WHERE ShortName LIKE '%A%'

SELECT * FROM Testtt

虽然我得到了理想的结果。