我需要 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/