查找与其他字符串SQL匹配的字符串部分

时间:2016-06-21 11:29:35

标签: sql-server-2008

我在变量中指定了值@ var1 =' 3,5,6,8'。我有一个表,其中列有一些随机数组合,以逗号分隔。 PFB样本表

enter image description here

我需要除了Id 3以外的所有表值,因为它的组合中有9个' 3,9,8'。

我想得到如下答案。

预期输出应仅包含ID 1,2和4.

原因是,@ var1中存在的任何/所有值都应该出现在Nos中,并且它不应该具有@ var1中不存在的no。 Id 3是后一种情况的一个例子,它包含9,它不是@ var1的一部分。

我的输出应该有1,2和4而不是3。

请你提出一些想法吗?

2 个答案:

答案 0 :(得分:1)

你可以转换为xml并使用xquery:

Sub qwerty()
    Dim N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Range("A1:I" & N).Select
End Sub

答案 1 :(得分:0)

这仍然可以进一步减少,但想法如下,

创建一个SplitString函数,

CREATE FUNCTION SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT

      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END

      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)

            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)

            SET @Input = rtrim(ltrim(SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))))
      END

      RETURN
END
GO

使用以下一系列查询并对其进行自定义

DECLARE @t TABLE (ID INT, Nos VARCHAR(8000))
INSERT @t
VALUES (1,
        '5, 3'), (2,
                  '3, 6, 8'), (3,
                               '3, 9, 8'),(4,
                                           '8') IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
DROP TABLE #Temp
SELECT * INTO #Temp
FROM
  (SELECT ID,
          LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Nos
   FROM
     (SELECT ID,
             CAST('<XMLRoot><RowData>' + REPLACE(Nos,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
      FROM @t)t CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) P
SELECT '3, 5, 6, 8'
SELECT '(1==> 5, 3), (2==> 3, 6, 8), (3 ==> 3, 9, 8),(4 ==> 8)'
SELECT *
FROM #Temp
SELECT Item
FROM dbo.SplitString('3, 5, 6, 8', ',')
SELECT '-- Group By '
SELECT Id,
       Count(Nos) C
FROM #Temp
GROUP BY Id
SELECT Id,
       Count(Nos) C
FROM
  (SELECT Item
   FROM dbo.SplitString('3, 5, 6, 8', ',')) X
JOIN
  (SELECT Id,
          Nos
   FROM #Temp) Y ON X.Item = Y.Nos
GROUP BY Id
SELECT '-- Final check'
SELECT T.*
FROM
  (SELECT Id,
          Count(Nos) C
   FROM #Temp
   GROUP BY Id) P
JOIN
  (SELECT Id,
          Count(Nos) C
   FROM
     (SELECT Item
      FROM dbo.SplitString('3, 5, 6, 8', ',')) X
   JOIN
     (SELECT Id,
             Nos
      FROM #Temp) Y ON X.Item = Y.Nos
   GROUP BY Id) Q ON P.Id = Q.Id
AND P.C = Q.C
JOIN #Temp T ON T.Id = P.Id