我需要更改应用程序,我需要的第一件事就是更改数据库表中的字段。 在这张表中我现在有1到6个单字符,即'abcdef' 我需要将其更改为'[a] [b] [c] [d] [e] [f]'
[编辑]它意味着留在同一个领域。所以在field ='abcdef'之前和在field ='[a] [b] [c] [d] [e] [f]'之后。
这样做的好方法是什么?
RG。 埃里克
答案 0 :(得分:2)
DECLARE @text NVARCHAR(50)
SET @text = 'abcdef'
DECLARE @texttable TABLE (value NVARCHAR(1))
WHILE (len(@text) > 0)
BEGIN
INSERT INTO @texttable
SELECT substring(@text, 1, 1)
SET @text = stuff(@text, 1, 1, '')
END
select * from @texttable
答案 1 :(得分:2)
您可以使用以下功能将字符串拆分为单独的字符:
create function ftStringCharacters
(
@str varchar(100)
)
returns table as
return
with v1(N) as (
select 1 union all select 1 union all select 1 union all select 1 union all select 1
union all
select 1 union all select 1 union all select 1 union all select 1 union all select 1
),
v2(N) as (select 1 from v1 a, v1 b),
v3(N) as (select top (isnull(datalength(@str), 0)) row_number() over (order by @@spid) from v2)
select N, substring(@str, N, 1) as C
from v3
GO
然后将其应用为:
update t
set t.FieldName = p.FieldModified
from TableName t
cross apply (
select (select quotename(s.C)
from ftStringCharacters(t.FieldName) s
order by s.N
for xml path(''), type).value('text()[1]', 'varchar(20)')
) p(FieldModified)
答案 2 :(得分:0)
不使用功能:
declare @t table(C varchar(18))
insert @t values('abc'), ('1234'), (' 1234a')
;with CTE as
(
select C, '[' + substring(c, a.n, 1) + ']' v, rn from
(select 1 n union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6) a
cross apply
(select c, row_number() over (order by C) rn from @t group by c) b
where a.n <= len(C)
)
update t3
set C = t4.[value]
FROM @t t3
JOIN
(
select C,
(
select v
from CTE t1
where t1.rn = t2.rn
for xml path(''), type
).value('.', 'varchar(18)') [value]
from CTE t2
group by t2.rn, C
) t4
ON t3.C = t4.C
SELECT * FROM @t