求救,sql语句从一个字段中选取部分插入数据库中另一个字段中
id tel mobie(该列为空)
1 1234,5678
2 3455,6666
3
4 1234
数据库中字段是这样的。要求是把tel字段中的数据比如1234,5678,提取5678插入列mobile
最后的形式是:
id tel mobile
1 1234 5678
麻烦各位了,这个sql语句该怎么写
[解决办法]
1)判断是否有逗号分隔
2)然后用substring+charindex截取过去
[解决办法]
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-03-14 11:53:33
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
--Jun 17 2011 00:54:03
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([id] int,[tel] varchar(9),[mobie] sql_variant)
insert [huang]
select 1,'1234,5678',null union all
select 2,'3455,6666',null
--------------开始查询--------------------------
select id,SUBSTRING(tel,1,PATINDEX('%,%',tel)-1)[tel], SUBSTRING(tel,PATINDEX('%,%',tel)+1,LEN(tel)+1-PATINDEX('%,%',tel))[mobie]
from [huang]
----------------结果----------------------------
/*
id tel mobie
----------- --------- ---------
1 1234 5678
2 3455 6666
(2 行受影响)
*/