sql - 如何在sql server中从长度为n的单词构建2^n个已更改的单词

标签 sql sql-server string sql-server-2008 tsql

我需要 sql server 中的一个函数来构建下面示例中所有已更改的单词; 对于长度为 n 的输入单词,必须构建 2^n 个已更改的单词; 例如,如果函数的输入是

"I"

函数的输出应该是

I
-   

函数的输入是

"am"

函数的输出应该是

am
-m
a-
--

函数的输入是

"sql"

函数的输出应该是

sql
-ql
s-l
sq-
--l
s--
-q-
--- 

最佳答案

您可以使用数字表 (master..spt_values) 和 stuff 来完成此操作循环中。

declare @Word varchar(10) = 'sql'

declare @T table
(
  Word varchar(10)
)

insert into @T values (@Word)

while not exists(select *
                 from @T 
                 where Word = replicate('-', len(@Word)))
begin              
  insert into @T(Word)
  select distinct stuff(T.Word, N.number, 1, '-')
  from @T as T
    cross join
       master..spt_values as N
  where N.type = 'P' and
        N.number between 1 and len(@Word) and
        stuff(T.Word, N.number, 1, '-') not in (select Word from @T)
end        

select *
from @T

https://data.stackexchange.com/stackoverflow/q/122334/

或者您可以使用要求的 CTE

declare @Word varchar(10) = 'sql'

;with C as
(
  select @Word as Word,
         0 as Iteration
  union all
  select cast(stuff(Word, N.number, 1, '-') as varchar(10)),
         Iteration + 1
  from C
    cross join
       master..spt_values as N
  where N.type = 'P' and
        N.number between 1 and len(@Word) and
        Iteration < len(@Word)
)
select distinct Word
from C

https://data.stackexchange.com/stackoverflow/q/122337/

更新

正如 OP 在评论中指出的那样,递归 CTE 版本确实很慢。使用包含 7 个字母的单词,CTE 返回 960800 行。

关于sql - 如何在sql server中从长度为n的单词构建2^n个已更改的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8585831/

相关文章:

sql-server - 更改系统时间是否会对 SQL Server 产生不利影响

运行时不依赖于数据内容的字符串算法

sql - 如何使用嵌套关联查询 STI 驱动的模型?

php - 比较运算符 Sql 查询与 php

c# - SqlBulkCopy 多个表在单个事务下插入或 Entity Framework 和经典 Ado.net 之间的批量插入操作

c - 字符数组有问题?

c - 在C中的字符串中为每个单词的结尾添加空格

MySQL表设计,一行还是多pr用户?

mysql - 使用多个计数语句进行查询

sql - 需要 SQL 数据透视帮助,因为我没有聚合列