SQL Server字符串组合

时间:2011-03-09 04:10:40

标签: sql-server-2008

我想返回一个行表,其中包含MS SQL 2008中字符串的所有可能组合。例如字符串“01-02-03-04”:

  1. 01 - 02 - 03 - 04
  2. 02 - 03 - 04
  3. 01 - 03 - 04
  4. 01 - 02 - 04
  5. 01 - 02 - 03
  6. 01 - 02
  7. 01 - 03
  8. 01 - 04
  9. 02 - 03
  10. 02 - 04
  11. 03 - 04

1 个答案:

答案 0 :(得分:2)

DECLARE @s varchar(150);
SET @s = '01-02-03-05-10';
WITH split AS (
  SELECT
    CAST(SUBSTRING(@s, number * 3 + 1, 2) AS varchar(150)) AS item,
    rn = number
  FROM master..spt_values
  WHERE type = 'P' AND number between 0 AND LEN(@s) / 3
),
combined AS (
  SELECT
    item,
    rn,
    itemcnt = 1
  FROM split
  UNION ALL
  SELECT
    item = CAST(c.item + '-' + n.item AS varchar(150)),
    n.rn,
    itemcnt = c.itemcnt + 1
  FROM split n
    INNER JOIN combined c ON n.rn > c.rn
)
SELECT *
FROM combined
WHERE itemcnt > 1
ORDER BY 1