SQL Server-将字符串添加到文本列(等效于concat)
技术问答
317 人阅读
|
0 人回复
|
2023-09-14
|
如何在SQL Server的列中添加字符串?' O9 S0 m9 V8 \% q
UPDATE [myTable] SET [myText]=' '+[myText]
9 {6 y n+ g9 x% `) c( Q/ y( l- i- ~那是行不通的:3 O$ J% C+ j! Y7 w, A
* N; e6 e% a9 N8 k9 K8 S. E
数据类型varchar和text在add运算符中不兼容。
1 o. w d8 r: M& Y% B/ _- B! T+ E
3 o5 E. r5 O' [( Z您将在MySQL上使用concat,但是如何在SQL Server上使用concat?
* r% }6 g; ~4 ?$ w( Y1 T/ K2 m5 W 2 r+ d8 g/ Z' I/ u; x. ~
解决方案: u. g+ \: D3 y# l1 s/ {$ }
* @7 K$ ^% F% C% V
7 s C+ i: N" W K1 Z5 i9 _" L8 M V, R
如前所述,最好将列的数据类型设置为nvarchar(max),但如果无法做到,则可以使用cast或convert进行以下操作:8 J; s: K/ g) x! |5 @/ \
-- create a test table ; r$ w( R* c b1 H7 Q
create table test (
% L& y) B$ q6 N% v3 i) } a text# ?8 J7 l* a2 N# [! S
) 7 E& b0 t0 i- {: R1 @' k- ]
-- insert test value
9 l- E+ H, m2 y9 H4 f# F! S0 x9 ~) d2 qinsert into test (a) values ('this is a text')
* _ m! T; `; }) v! |+ T/ l-- the following does not work !!!
/ y* P9 b L: s! Y! hupdate test set a = a + ' and a new text added'
/ Q% e: e9 G2 l8 l4 ^-- but this way it works: 5 d: n- t! n9 @2 R. q
update test set a = cast ( a as nvarchar(max)) + cast (' and a new text added' as nvarchar(max) )
5 B7 k, ]3 m* E6 H! `/ u6 P( x-- test result N8 G: K3 i4 `& P S
select * from test6 D1 U: B- c" A9 R, M
-- column a contains:
& [$ U( P2 v0 j: sthis is a text and a new text added$ {8 d4 s: C/ z+ s S. d9 m9 f
希望能有所帮助 |
|
|
|
|
|