查詢區分大小寫
2024-07-21 02:08:24
供稿:網友
在sql2000和7.0的查詢語句中,區分大寫的查詢方法
--sql2000,就用下面的方法.
--就是在字段名后加 collate chinese_prc_cs_as_ws
--區分大小寫、全半角字符的方法
--測試數據
create table 表(fd varchar(10))
insert into 表
select aa='aa'
union all select 'aa'
union all select 'aa' --全角a
union all select 'a,a' --全角a,半角,
union all select 'a,a' --全角a,全角,
go
--查詢
--1.查大寫字母
select * from 表
where fd collate chinese_prc_cs_as_ws like '%a%'
--就是在字段名后加 collate chinese_prc_cs_as_ws
--2.查全角
select * from 表
where fd collate chinese_prc_cs_as_ws like '%a%'
--3.查半角
select * from 表
where fd collate chinese_prc_cs_as_ws like '%,%'
go
--刪除測試數據
drop table 表
/*--測試結果
1.查詢大寫字母的結果
fd
----------
aa
2.查詢全角字符的結果
fd
----------
aa
a,a
a,a
3.查詢半角字符的結果
fd
----------
a,a
(所影響的行數為 1 行)
--*/
================================================================
--sql7.0,就用下面的方法.
--如果是全部比較
--下面是測試
select * from(
select fd='a'
union all select 'a'
) a
where cast(fd as varbinary(8000))=cast('a' as varbinary(8000))
/*--測試結果
fd
----
a
(所影響的行數為 1 行)
--*/
--如果是部分匹配,就用charindex:
--下面是測試
select * from(
select fd='a'
union all select 'a'
union all select 'aaaa'
union all select 'aaaa'
union all select 'ccca'
) a
where charindex(cast('a' as varbinary(8000)),cast(fd as varbinary(8000)))>0
/*--測試結果
fd
----
a
aaaa
ccca
(所影響的行數為 3 行)
--*/