0

我想编写 I 函数来比较逗号分隔值,但我不擅长 sql 我有一个存储的 pro 这工作正常...任何人都可以在 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
4

1 回答 1

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

于 2013-07-16T04:52:36.697 回答