在sql7.0和200中,如何区分一个字符串中字符的大小写

--如果你用的是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 行)
--*/

--====================================================================

--写成比较函数
--比较函数,如果两个字符串安全相同(包括大小写相同),则返回1,否则返回0
create function f_compstr(
@str1 varchar(8000), --要比较的第一个字符串
@str2 varchar(8000) --要比较的第二个字符串
) returns bit
as
begin
return(case when @str1 collate Chinese_PRC_CS_AS_WS =@str2 then 1 else 0 end)
end
go

--调用方法(注意,dbo.不能省略)
select dbo.f_compstr('abc','Abc')
,dbo.f_compstr('abc','abc')
go

---------------------------------------------------------------

--写成存储过程,即为
create proc p_compstr
@str1 varchar(8000), --要比较的第一个字符串
@str2 varchar(8000), --要比较的第二个字符串
@re bit output --返回结果,如果完全一样,返回1,否则返回0
as
set @re=case when @str1 collate Chinese_PRC_CS_AS_WS =@str2 then 1 else 0 end
go

---------------------------------------------------------------

--调用方法:
declre @re bit
exec p_compstr 'abc','abC',@re out
select 比较结果=@re

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus