天天看點

19.字元串比較函數

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

--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,CHARINDEX(@split,@s1)[email protected],'')
	END
	INSERT @r1 VALUES(@s1)

	WHILE CHARINDEX(@split,@s2)>0
	BEGIN
		INSERT @r2 VALUES(LEFT(@s2,CHARINDEX(@split,@s2)-1))
		SET @s2=STUFF(@s2,1,CHARINDEX(@split,@s2)[email protected],'')
	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),  --要比較的第一個字元串
@s2  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,CHARINDEX(@split,@s1)-1)[email protected],@[email protected][email protected])>0
			RETURN(1)
		SET @s1=STUFF(@s1,1,CHARINDEX(@split,@s1)[email protected],'')
	END
	RETURN(CASE WHEN CHARINDEX(@[email protected][email protected],@[email protected][email protected])>0 THEN 1 ELSE 0 END)
END