SQL字符串处理问题

hchen1982 2011-01-04 04:23:47
怎么给某张表的某个字段,判断此字段如果前后无逗号,则前后夹加逗号(,);如果前后有逗号了或者为null,或者“”则不加
比如:有表A,其中有一个字段users
如果users的值为 ,a,b, 则值不变
如果users 的值为null或者“” 则值也不变
如果users的值为 a,b 则更新为 ,a,b,
...全文
142 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
飘零一叶 2011-01-04
  • 打赏
  • 举报
回复
create table tb
(
users varchar(10)
)
insert into tb
select ',a,b ' union all
select ' ,a,b, ' union all
select 'ab ' union all
select ' a,b' union all
select 'a,b' union all
select ' ' union all
select ' ' union all
select null

UPDATE tb SET users=replace(' '+LTRIM(RTRIM(replace(LTRIM(RTRIM(users)),',',' ')))+' ',' ',',')
from tb where users is not null and users<>''

SELECT * FROM TB
-----------
users
,a,b,
,a,b,
,ab,
,a,b,
,a,b,


NULL
gogodiy 2011-01-04
  • 打赏
  • 举报
回复

select case when users is null or users ='""' or (left(users,1)=',' and right(users,1)=',') then users
else ','+users+',' end as users from t1
快溜 2011-01-04
  • 打赏
  • 举报
回复
 update A set users=replace(' '+users+' ',' ',',') where user is not null or user <>''
hchen1982 2011-01-04
  • 打赏
  • 举报
回复
我需要对A表的users字段进行更新到数据库
快溜 2011-01-04
  • 打赏
  • 举报
回复
select case when user=null or user ='' then user else replace(' '+users+' ',' ',',') end

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧