在SP中将SP转换为Function以比较逗号分隔值

时间:2013-07-16 04:44:26

标签: sql sql-server-2008 tsql

我想写比较逗号分隔值的函数但我在sql中不是很好我有一个存储的专业版 这工作正常......任何人都可以在SQL函数中转换此SP并返回true或false(现在返回匹配的单词)

CREATE PROCEDURE CompareCSVInSQL 
 @str1   varchar(1500),
 @srt2  varchar(1500)
AS
BEGIN   
SET NOCOUNT ON;

DECLARE @v1 VARCHAR(1500) = @str1
DECLARE @v2 VARCHAR(1500) = @srt2
DECLARE @v1Words TABLE (word VARCHAR(1000))
DECLARE @v2Words TABLE (word VARCHAR(1000))

;WITH cteSplitV1 AS( 
SELECT CAST('<word>' + REPLACE(@v1,', ','</word><word>') + '</word>' AS XML) AS words) 
INSERT INTO @v1Words(word)
    SELECT word.x.value('.','VARCHAR(100)') AS [word]
    FROM cteSplitV1
    CROSS APPLY words.nodes('/word') AS word(x)

;WITH cteSplitV2 AS( 
SELECT CAST('<word>' + REPLACE(@v2,', ','</word><word>') + '</word>' AS XML) AS words) 
INSERT INTO @v2Words(word)
    SELECT word.x.value('.','VARCHAR(100)') AS [word]
    FROM cteSplitV2 
    CROSS APPLY words.nodes('/word') AS word(x)

SELECT *
FROM @v1Words v1
JOIN @v2Words v2
    ON v1.word = v2.word
END
GO



BEGIN TRAN
BEGIN
   DECLARE @srt1 varchar(1500)
   DECLARE @srt2 varchar(1500)
   set @srt1 = 'hello, world,one,two, yes'
   set @srt2 = 'jump,down, yes, one'
   SELECT dbo.CompareCSVInSQL(@srt1,@srt2) AS 'Matching'
END
ROLLBACK

1 个答案:

答案 0 :(得分:0)

这可能对您有所帮助

CREATE FUNCTION CompareCSVInSQL
(
     @str1   varchar(1500),
 @srt2  varchar(1500)
)
RETURNS BIT
AS
BEGIN
DECLARE @retValue BIT
DECLARE @v1 VARCHAR(1500) = @str1
DECLARE @v2 VARCHAR(1500) = @srt2
DECLARE @v1Words TABLE (word VARCHAR(1000))
DECLARE @v2Words TABLE (word VARCHAR(1000))

;WITH cteSplitV1 AS( 
SELECT CAST('<word>' + REPLACE(@v1,', ','</word><word>') + '</word>' AS XML) AS words) 
INSERT INTO @v1Words(word)
    SELECT word.x.value('.','VARCHAR(100)') AS [word]
    FROM cteSplitV1
    CROSS APPLY words.nodes('/word') AS word(x)

;WITH cteSplitV2 AS( 
SELECT CAST('<word>' + REPLACE(@v2,', ','</word><word>') + '</word>' AS XML) AS words) 
INSERT INTO @v2Words(word)
    SELECT word.x.value('.','VARCHAR(100)') AS [word]
    FROM cteSplitV2 
    CROSS APPLY words.nodes('/word') AS word(x)

IF EXISTS (SELECT 1
          FROM @v1Words v1 JOIN @v2Words v2
                ON v1.word = v2.word)
BEGIN
    SET @retValue=1
END
ELSE
BEGIN
    SET @retValue=0
END
RETURN @retValue
END

如果匹配单词,则返回true。否则返回false