search
HomeDatabaseMysql TutorialSql Server数据库汉字按字母、笔划、拼音首字母、排序

sql server的排序规则平时使用不是很多,也许不少初学者还比较陌生,但有 一个错误大家应是经常碰到: sql server数据库,在跨库多表连接查询时,若两数据 库默认字符集不同,系统就会返回这样的错误: 无法解决 equal to 操作的排序规则冲突。 一.错误分析:

 

sql server的排序规则平时使用不是很多,也许不少初学者还比较陌生,但有
一个错误大家应是经常碰到: sql server数据库,在跨库多表连接查询时,若两数据
库默认字符集不同,系统就会返回这样的错误:
      
           “无法解决 equal to 操作的排序规则冲突。”

一.错误分析:
  这个错误是因为排序规则不一致造成的,我们做个测试,比如:
create table #t1(name varchar(20) collate albanian_ci_ai_ws,  value int)

create table #t2(name varchar(20) collate chinese_prc_ci_ai_ws,  value int )

表建好后,执行连接查询:

select * from #t1 a inner join #t2 b on a.name=b.name

这样,错误就出现了:

           服务器: 消息 446,级别 16,状态 9,行 1
           无法解决 equal to 操作的排序规则冲突。
      要排除这个错误,最简单方法是,表连接时指定它的排序规则,这样错误就不再出现了。语句这样写:

select * from #t1 a inner join #t2 b on a.name=b.name collate chinese_prc_ci_ai_ws

二.排序规则简介:

    什么叫排序规则呢?ms是这样描述的:"在 microsoft sql server 2000 中,
字符串的物理存储由排序规则控制。排序规则指定表示每个字符的位模式以及存
储和比较字符所使用的规则。"
  在查询分析器内执行下面语句,可以得到sql server支持的所有排序规则。

    select * from ::fn_helpcollations()

排序规则名称由两部份构成,前半部份是指本排序规则所支持的字符集。
如:
  chinese_prc_cs_ai_ws
前半部份:指unicode字符集,chinese_prc_指针对大陆简体字unicode的排序规则。
排序规则的后半部份即后缀 含义:
  _bin 二进制排序
  _ci(cs) 是否区分大小写,ci不区分,cs区分
  _ai(as) 是否区分重音,ai不区分,as区分   
  _ki(ks) 是否区分假名类型,ki不区分,ks区分 
    _wi(ws) 是否区分宽度 wi不区分,ws区分 

区分大小写:如果想让比较将大写字母和小写字母视为不等,请选择该选项。
区分重音:如果想让比较将重音和非重音字母视为不等,请选择该选项。如果选择该选项,
         比较还将重音不同的字母视为不等。
区分假名:如果想让比较将片假名和平假名日语音节视为不等,请选择该选项。
区分宽度:如果想让比较将半角字符和全角字符视为不等,请选择该选项

 
三.排序规则的应用:
  sql server提供了大量的windows和sqlserver专用的排序规则,但它的应用往往
被开发人员所忽略。其实它在实践中大有用处。

  例1:让表name列的内容按拼音排序:

create table #t(id int,name varchar(20))
insert #t select 1,中
union all select 2,国
union all select 3,人
union all select 4,阿

select * from #t order by name collate chinese_prc_cs_as_ks_ws
drop table #t
/*结果:
id          name                
----------- --------------------
4           阿
2           国
3           人
1           中
*/

  例2:让表name列的内容按姓氏笔划排序:

create table #t(id int,name varchar(20))

insert #t select 1,三
union all select 2,乙
union all select 3,二
union all select 4,一
union all select 5,十
select * from #t order by name collate chinese_prc_stroke_cs_as_ks_ws 
drop table #t
/*结果:
id          name                
----------- --------------------
4           一
2           乙
3           二
5           十
1           三
*/

四.在实践中排序规则应用的扩展
  sql server汉字排序规则可以按拼音、笔划等排序,那么我们如何利用这种功能
来处理汉字的一些难题呢?我现在举个例子:

          用排序规则的特性计算汉字笔划

  要计算汉字笔划,我们得先做准备工作,我们知道,windows多国汉字,unicode目前
收录汉字共20902个。简体gbk码汉字unicode值从19968开始。
  首先,我们先用sqlserver方法得到所有汉字,不用字典,我们简单利用sql语句就
可以得到:

select top 20902 code=identity(int,19968,1) into #t from syscolumns a,syscolumns b

再用以下语句,我们就得到所有汉字,它是按unicode值排序的:

  select code,nchar(code) as cnword from #t

  然后,我们用select语句,让它按笔划排序。

select code,nchar(code) as cnword
from #t
order by nchar(code) collate chinese_prc_stroke_cs_as_ks_ws,code

结果:
code        cnword
----------- ------
19968       一
20008       丨
20022       丶
20031       丿
20032       乀
20033       乁
20057       乙
20058       乚
20059       乛
20101       亅
19969       丁
..........

   从上面的结果,我们可以清楚的看到,一笔的汉字,code是从19968到20101,从小到大排,但到
了二笔汉字的第一个字“丁”,code为19969,就不按顺序而重新开始了。有了这结果,我们就可以轻
松的用sql语句得到每种笔划汉字归类的第一个或最后一个汉字。
下面用语句得到最后一个汉字:

create table #t1(id int identity,code int,cnword nvarchar(2))

insert #t1(code,cnword)
select code,nchar(code) as cnword  from #t
order by nchar(code) collate chinese_prc_stroke_cs_as_ks_ws,code


select a.cnword
from #t1 a
left join #t1 b on a.id=b.id-1 and a.codewhere b.code is null
order by a.id

得到36个汉字,每个汉字都是每种笔划数按chinese_prc_stroke_cs_as_ks_ws排序规则排序后的
最后一个汉字:

亅阝马风龙齐龟齿鸩龀龛龂龆龈龊龍龠龎龐龑龡龢龝齹龣龥齈龞麷鸞麣龖龗齾齉龘

  上面可以看出:“亅”是所有一笔汉字排序后的最后一个字,“阝”是所有二笔汉字排序后的最后
一个字......等等。
  但同时也发现,从第33个汉字“龗(33笔)”后面的笔划有些乱,不正确。但没关系,比“龗”笔划
多的只有四个汉字,我们手工加上:齾35笔,齉36笔,靐39笔,龘64笔

建汉字笔划表(tab_hzbh):
create table tab_hzbh(id int identity,cnword nchar(1))
--先插入前33个汉字
insert tab_hzbh
select top 33 a.cnword
from #t1 a
left join #t1 b on a.id=b.id-1 and a.codewhere b.code is null
order by a.id
--再加最后四个汉字
set identity_insert tab_hzbh on
go
insert tab_hzbh(id,cnword)
     select 35,n齾
union all select 36,n齉
union all select 39,n靐
union all select 64,n龘
go
set identity_insert tab_hzbh off
go

  到此为止,我们可以得到结果了,比如我们想得到汉字“国”的笔划:

declare @a nchar(1)
set @a=国
select top 1 id
from  tab_hzbh
where cnword>=@a collate chinese_prc_stroke_cs_as_ks_ws
order by id

id         
-----------
8
(结果:汉字“国”笔划数为8)

  上面所有准备过程,只是为了写下面这个函数,这个函数撇开上面建的所有临时表和固
定表,为了通用和代码转移方便,把表tab_hzbh的内容写在语句内,然后计算用户输入一串
汉字的总笔划:

create function fun_getbh(@str nvarchar(4000))
returns int
as
begin
declare @word nchar(1),@n int
set @n=0
while len(@str)>0
begin
set @word=left(@str,1)
--如果非汉字,笔划当0计
set @n=@n+(case when unicode(@word) between 19968 and 19968+20901
then (select top 1 id from (
select 1 as id,n亅 as word
union all select 2,n阝
union all select 3,n马
union all select 4,n风
union all select 5,n龙
union all select 6,n齐
union all select 7,n龟
union all select 8,n齿
union all select 9,n鸩
union all select 10,n龀
union all select 11,n龛
union all select 12,n龂
union all select 13,n龆
union all select 14,n龈
union all select 15,n龊
union all select 16,n龍
union all select 17,n龠
union all select 18,n龎
union all select 19,n龐
union all select 20,n龑
union all select 21,n龡
union all select 22,n龢
union all select 23,n龝
union all select 24,n齹
union all select 25,n龣
union all select 26,n龥
union all select 27,n齈
union all select 28,n龞
union all select 29,n麷
union all select 30,n鸞
union all select 31,n麣
union all select 32,n龖
union all select 33,n龗
union all select 35,n齾
union all select 36,n齉
union all select 39,n靐
union all select 64,n龘
) t
where word>=@word collate chinese_prc_stroke_cs_as_ks_ws
order by id asc) else 0 end)
set @str=right(@str,len(@str)-1)
end
return @n
end

--函数调用实例:
select dbo.fun_getbh(中华人民共和国),dbo.fun_getbh(中華人民共和國)
 
  执行结果:笔划总数分别为39和46,简繁体都行。

    当然,你也可以把上面“union all”内的汉字和笔划改存在固定表内,在汉字
列建clustered index,列排序规则设定为:
    chinese_prc_stroke_cs_as_ks_ws
这样速度更快。如果你用的是big5码的操作系统,你得另外生成汉字,方法一样。
但有一点要记住:这些汉字是通过sql语句select出来的,不是手工输入的,更不
是查字典得来的,因为新华字典毕竟不同于unicode字符集,查字典的结果会不正
确。

  
              用排序规则的特性得到汉字拼音首字母

  用得到笔划总数相同的方法,我们也可以写出求汉字拼音首字母的函数。如下:

create function fun_getpy(@str nvarchar(4000))
returns nvarchar(4000)
as
begin
declare @word nchar(1),@py nvarchar(4000)
set @py=
while len(@str)>0
begin
set @word=left(@str,1)
--如果非汉字字符,返回原字符
set @py=@py+(case when unicode(@word) between 19968 and 19968+20901
then (select top 1 py from (
select a as py,n驁 as word
union all select b,n簿
union all select c,n錯
union all select d,n鵽
union all select e,n樲
union all select f,n鰒
union all select g,n腂
union all select h,n夻
union all select j,n攈
union all select k,n穒
union all select l,n鱳
union all select m,n旀
union all select n,n桛
union all select o,n漚
union all select p,n曝
union all select q,n囕
union all select r,n鶸
union all select s,n蜶
union all select t,n籜
union all select w,n鶩
union all select x,n鑂
union all select y,n韻
union all select z,n咗
) t
where word>=@word collate chinese_prc_cs_as_ks_ws
order by py asc) else @word end)
set @str=right(@str,len(@str)-1)
end
return @py
end

--函数调用实例:
select dbo.fun_getpy(中华人民共和国),dbo.fun_getpy(中華人民共和國)
结果都为:zhrmghg

   你若有兴趣,也可用相同的方法,扩展为得到汉字全拼的函数,甚至还可以得到全拼的读
音声调,不过全拼分类大多了。得到全拼最好是用对照表,两万多汉字搜索速度很快,用对照
表还可以充分利用表的索引。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL's Place: Databases and ProgrammingMySQL's Place: Databases and ProgrammingApr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL: From Small Businesses to Large EnterprisesMySQL: From Small Businesses to Large EnterprisesApr 13, 2025 am 12:17 AM

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?What are phantom reads and how does InnoDB prevent them (Next-Key Locking)?Apr 13, 2025 am 12:16 AM

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.

MySQL: Not a Programming Language, But...MySQL: Not a Programming Language, But...Apr 13, 2025 am 12:03 AM

MySQL is not a programming language, but its query language SQL has the characteristics of a programming language: 1. SQL supports conditional judgment, loops and variable operations; 2. Through stored procedures, triggers and functions, users can perform complex logical operations in the database.

MySQL: An Introduction to the World's Most Popular DatabaseMySQL: An Introduction to the World's Most Popular DatabaseApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

The Importance of MySQL: Data Storage and ManagementThe Importance of MySQL: Data Storage and ManagementApr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system suitable for data storage, management, query and security. 1. It supports a variety of operating systems and is widely used in Web applications and other fields. 2. Through the client-server architecture and different storage engines, MySQL processes data efficiently. 3. Basic usage includes creating databases and tables, inserting, querying and updating data. 4. Advanced usage involves complex queries and stored procedures. 5. Common errors can be debugged through the EXPLAIN statement. 6. Performance optimization includes the rational use of indexes and optimized query statements.

Why Use MySQL? Benefits and AdvantagesWhy Use MySQL? Benefits and AdvantagesApr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Describe InnoDB locking mechanisms (shared locks, exclusive locks, intention locks, record locks, gap locks, next-key locks).Apr 12, 2025 am 12:16 AM

InnoDB's lock mechanisms include shared locks, exclusive locks, intention locks, record locks, gap locks and next key locks. 1. Shared lock allows transactions to read data without preventing other transactions from reading. 2. Exclusive lock prevents other transactions from reading and modifying data. 3. Intention lock optimizes lock efficiency. 4. Record lock lock index record. 5. Gap lock locks index recording gap. 6. The next key lock is a combination of record lock and gap lock to ensure data consistency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools