0

我有一个大表,其中包含 x 列,我想将其复制到同一张表中的另一列 y。对此的 SQL 语句是什么?

第一列被调用name,它包含用空格分隔的名字和姓氏。如何将这些移动到新的名字和姓氏列?

4

4 回答 4

1

有时名字有多余的空格,这个脚本会处理这些情况

create table #t(name nvarchar(100), firstname nvarchar(50), lastname nvarchar(50))

insert #t (name) values ('Thomas Clausen')
insert #t (name) values ('  Bill Gates')
insert #t (name) values ('Steven Jobs  ')
insert #t (name) values ('Donald of Duck')
insert #t (name) values ('microsoft')
insert #t (name) values ('')

update #t 
set firstname = nullif(left(ltrim(name), charindex(' ', ltrim(name) + ' ')-1), ''),
lastname = nullif(stuff(rtrim(name), 1,len(rtrim(name))
           - charindex(' ', reverse(rtrim(name))), ''), '')

结果:

FirstName   LastName
Thomas      Clausen
Bill        Gates
Steven      Jobs
Donald      Duck
microsoft   NULL
NULL        NULL
于 2012-08-01T09:28:55.323 回答
0
update  YourTable
set     y = x
于 2012-08-01T06:26:07.610 回答
0

编辑:

UPDATE Table
   SET y = x

编辑:

从对您的问题的修改中,我了解到您有一个类似的列“名称”,John Adams并且想要填充已经存在的两列,FirstName 和 LastName。如果是这种情况,试试这个

UPDATE table
   SET FirstName = PARSENAME(REPLACE(name, ' ', '.'), 2),
       LastName = PARSENAME(REPLACE(name, ' ', '.'), 1)

如果名字和姓氏之间没有空格,则不会遇到错误消息,FirstName 将返回 NULL 值,而整个全名将作为 LastName 返回。

于 2012-08-01T06:29:23.227 回答
0
Select t1.Name,t1.Marks as Maths,t2.Marks as physics,t3.Marks as Chemistry from 
(select T.Name,T.Marks,T.Subjects
from Student as T
where T.Subjects like 'Maths') as t1
inner join 
(select D.Name,D.Marks,D.Subjects
from Student as D
where D.Subjects like 'Physics') as t2
on t1.Name like t2.Name
inner join
(select E.Name,E.Marks,E.Subjects
from Student as E
where E.Subjects like 'Chemistry') as t3
on t2.Name like t3.Name
于 2012-08-01T07:05:43.353 回答