我需要更改应用程序,我需要做的第一件事是更改数据库表中的字段。在此表中,我现在有 1 到 6 个单个字符,即 'abcdef' 我需要将其更改为 '[a][b][c][d][e][f]'
[编辑] 它意味着留在同一个领域。所以在 field = 'abcdef' 之前和 field = '[a][b][c][d][e][f]' 之后。
什么是这样做的好方法?
rg. 埃里克
我需要更改应用程序,我需要做的第一件事是更改数据库表中的字段。在此表中,我现在有 1 到 6 个单个字符,即 'abcdef' 我需要将其更改为 '[a][b][c][d][e][f]'
[编辑] 它意味着留在同一个领域。所以在 field = 'abcdef' 之前和 field = '[a][b][c][d][e][f]' 之后。
什么是这样做的好方法?
rg. 埃里克
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
您可以使用以下函数将字符串拆分为单独的字符:
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)
不使用函数:
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