一、字符串比较函数
1-- 比较两个字符串中包含的数据项是否相同的用户定义函数:
CREATE FUNCTION dbo.f_CompareSTR(
@s1 varchar(8000), --要比较的第一个字符串
@s2 varchar(8000), --要比较的第二个字符串
@split varchar(10) --数据分隔符
)RETURNS bit
AS
BEGIN
IF LEN(@s1)<>LEN(@s2) RETURN(0)
DECLARE @r1 TABLE(col varchar(100))
DECLARE @r2 TABLE(col varchar(100))
DECLARE @splitlen int
SET @splitlen=LEN(@split+'a')-2
WHILE CHARINDEX(@split,@s1)>0
BEGIN
INSERT @r1 VALUES(LEFT(@s1,CHARINDEX(@split,@s1)-1))
SET @s1=STUFF(@s1,1,@s1)+@splitlen,'')
END
INSERT @r1 VALUES(@s1)
WHILE CHARINDEX(@split,@s2)>0
BEGIN
INSERT @r2 VALUES(LEFT(@s2,@s2)-1))
SET @s2=STUFF(@s2,@s2)+@splitlen,'')
END
INSERT @r2 VALUES(@s2)
RETURN(CASE
WHEN EXISTS(SELECT * FROM @r1 a FULL JOIN @r2 b ON a.col=b.col WHERE a.col IS NULL OR b.col IS NULL)
THEN 0 ELSE 1 END)
END
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_CompareSTR]') and xtype in (N'FN',N'IF',N'TF'))
drop function [dbo].[f_CompareSTR]
GO
2--比较两个字符串中包含的数据项是否有任意一个相同
CREATE FUNCTION dbo.f_CompareSTR(
@s1 varchar(8000), --要比较的第二个字符串
@split varchar(10) --数据分隔符
)RETURNS bit
AS
BEGIN
DECLARE @splitlen int
SET @splitlen=LEN(@split+'a')-2
WHILE CHARINDEX(@split,@s1)>0
BEGIN
IF CHARINDEX(@split+LEFT(@s1,@s1)-1)+@split,@split+@s2+@split)>0
RETURN(1)
SET @s1=STUFF(@s1,'')
END
RETURN(CASE WHEN CHARINDEX(@split+@s1+@split,@split+@s2+@split)>0 THEN 1 ELSE 0 END)
END
二、非法字符串处理
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_replace]') and xtype in (N'FN',N'TF'))
drop function [dbo].[f_replace]
GO
去掉字符串中,小于32的字符 保留 TAB char(9) 换行 char(10) 回车 char(13) 如果上述字符也不需要,则将函数中的注释删除 create function f_replace( @str varchar(8000) )returns varchar(8000) as begin select @str=replace(@str,a,'') from(select a=N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' -- union all select N' ' --TAB char(9) -- union all select N' -- ' --换行 char(10) union all select N' ' union all select N' ' -- union all select N' -- ' --回车 char(13) union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'' union all select N'