如何使用列y的值更新列x的值?

时间:2012-08-01 06:24:18

标签: sql tsql sql-server-2005

我有一个带有列x的大表,我希望将其复制到同一个表中的另一列y。什么是SQL语句?

第1列称为name,它包含以空格分隔的名字和姓氏。如何将这些列移到新的名字和姓氏列?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

update  YourTable
set     y = x

答案 2 :(得分: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返回。

答案 3 :(得分: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