SQLServer数据库使用Function实现根据字段内容的拼音首字母进行数据查询

实现SQL首字母查询分两步,第一步建Function,第二步引用新建的Function。

1. 首先需要自定义一个查询的Function,详细SQL如下:

sql 复制代码
ALTER function [dbo].[GetDataByPY](@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

2. 使用GetDataByPY进行数据查询,其中,SQL中的数字表示根据前几位字符串的首字母去匹配,后面的字符串就代表查询的首字母了,例如:

sql 复制代码
SELECT * FROM <font color=red>表名</font>
WHERE LEFT(dbo.FuncSysGetPY(<font color=red>字段名</font>), 1) = 'a' 

SELECT * FROM <font color=red>表名</font>
WHERE LEFT(dbo.FuncSysGetPY(<font color=red>字段名</font>), 2) = 'ab' 

SELECT * FROM <font color=red>表名</font>
WHERE LEFT(dbo.FuncSysGetPY(<font color=red>字段名</font>), 3) = 'abc' 
		。
		。
		。
		。
相关推荐
ZWZhangYu2 小时前
LangChain 构建向量数据库和检索器
数据库·langchain·easyui
feifeigo1233 小时前
升级到MySQL 8.4,MySQL启动报错:io_setup() failed with EAGAIN
数据库·mysql·adb
火龙谷4 小时前
【nosql】有哪些非关系型数据库?
数据库·nosql
焱焱枫5 小时前
Oracle获取执行计划之10046 技术详解
数据库·oracle
qq_392397127 小时前
Redis常用操作
数据库·redis·wpf
一只fish8 小时前
MySQL 8.0 OCP 1Z0-908 题目解析(17)
数据库·mysql
花好月圆春祺夏安9 小时前
基于odoo17的设计模式详解---装饰模式
数据库·python·设计模式
A__tao9 小时前
SQL 转 Java 实体类工具
java·数据库·sql
m0_653031369 小时前
腾讯云认证考试报名 - TDSQL数据库交付运维专家(TCCE PostgreSQL版)
运维·数据库·腾讯云
小马哥编程10 小时前
【iSAQB软件架构】架构决策记录-ADR
数据库·架构·系统架构·设计规范