是否存在SQL查询来将字符串中的偶数字符替换为大写,其余字符替换为小写?
例如,如果字符串为“ sagar”,则结果应类似于
button
什么是合适的解决方案?
答案 0 :(得分:2)
我无法抗拒回答。对于递归CTE来说,这似乎是很自然的:
with t as (
select 'abcdef' as str
),
cte as (
select cast(lower(str) as varchar(max)) as str, 1 as pos
from t
union all
select stuff(str, pos + 1, 1,
(case when pos % 2 = 1 then upper(substring(str, pos + 1, 1))
else lower(substring(str, pos + 1, 1))
end)
) as str, 1 + pos
from cte
where pos < len(str)
)
select top (1) *
from cte
order by pos desc;
答案 1 :(得分:1)
编写下面的代码,效果很好
在主数据库上测试
declare @name nvarchar(50)
declare @i int
set @i=1
set @name='sagar'
while(@i<=LEN(@name))
begin
if(@i%2=0)
begin
print Upper(SUBSTRING(@name,@i,1))
set @i=@i+1
end
else
begin
print Lower(SUBSTRING(@name,@i,1))
set @i=@i+1
end
end
在设置@name参数时给出自己选择的名称,即可获得所需的结果
答案 2 :(得分:1)
使用统计表...
declare @table table ([name] varchar(64))
insert into @table
values
('sAgAr')
,('abcdefghijk')
,('LMNOPQ')
;WITH
E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
cteTally(N) AS
(
SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
select
t.[name]
,lower(left(t.[name],1))
+
STUFF((
SELECT '' + case
when c2.N%2 = 0 then upper(substring(t2.[name],c2.N,1))
else lower(substring(t2.[name],c2.N,1))
end
FROM @table t2
cross apply cteTally c2
where
len(t2.[name]) >= c2.N
and t2.name = t.name
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
@table t
答案 3 :(得分:1)
这是通过分成几行然后再次创建字符串来完成的:
declare @test table ([value] nvarchar(20))
insert into @test values ('sagar'), ('Blueprint'), ('turtLe')
;with cte as (
select [value]
, num
, iif(num % 2 = 0, upper(substring([value], num, 1)), lower(substring([value], num, 1))) as [char]
from @test
cross join (values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12)) numbers(num) --add more for > 12 characters
where num <= len([Value]))
select distinct [Value], [CaseApplied] = STUFF(( SELECT '' + [char]
FROM cte AS c
WHERE c.[value]= cte.value
FOR XML PATH('')
), 1, 0, '')
from cte
答案 4 :(得分:1)
这是一种方法:
DECLARE @mystringLOW varchar(100) = 'sagar'
,@pos int = 2
WHILE @pos <= LEN(@mystringLOW)
BEGIN
SET @mystringLOW = (SELECT STUFF(@mystringLOW, @pos, 1, UPPER(SUBSTRING(@mystringLOW, @pos, 1))))
SET @pos += 2
END
SELECT @mystringLOW AS [my answer]
产生:
my answer
---------
sAgAr