难题1,关于同一个表中的查询/插入问题!
表T1如下:
ID Name CID1 CID2
01 Zhao 01
02 Qian 01
03 Sun 04
04 Li 02
要求查询插入的效果是: 如果某一行A的CID1的值和其他某行B的ID的值相同,那么就把B的Name插入到A的CID2列中:结果应该如下所示:
ID Name CID1 CID2
01 Zhao 01
02 Qian 01 Zhao
03 Sun 04 Li
04 Li 02 Qian
不知道怎么写好,请大侠执教!
SELECT * FROM T1
WHERE ...
------解决方案----------------------如果是要查詢
Select
A.ID,
A.Name,
A.CID1,
(Case When A.ID = A.CID1 Then A.CID2 Else IsNull(B.Name, ' ') End) As CID2
From
T1 A
Left Join
T1 B
On A.CID1 = B.ID
--如果是要更新
Update
A
Set
CID2 = (Case When A.ID = A.CID1 Then A.CID2 Else IsNull(B.Name, ' ') End)
From
T1 A
Left Join
T1 B
On A.CID1 = B.ID
Select * From T1
------解决方案--------------------Create Table T1
(ID Char(2),
Name Varchar(10),
CID1 Char(2),
CID2 Varchar(10))
Insert T1 Select '01 ', 'Zhao ', '01 ', ' '
Union All Select '02 ', 'Qian ', '01 ', ' '
Union All Select '03 ', 'Sun ', '04 ', ' '
Union All Select '04 ', 'Li ', '02 ', ' '
Union All Select '05 ', 'Li ', '06 ', ' '
GO
--如果是要查詢
Select
A.ID,
A.Name,
A.CID1,
(Case When A.ID = A.CID1 Then A.CID2 Else IsNull(B.Name, ' ') End) As CID2
From
T1 A
Left Join
T1 B
On A.CID1 = B.ID
--如果是要更新
Update
A
Set
CID2 = (Case When A.ID = A.CID1 Then A.CID2 Else IsNull(B.Name, ' ') End)
From
T1 A
Left Join
T1 B
On A.CID1 = B.ID
Select * From T1
GO
Drop Table T1
--Result
/*
ID Name CID1 CID2
01 Zhao 01
02 Qian 01 Zhao
03 Sun 04 Li
04 Li 02 Qian
05 Li 06
*/
------解决方案--------------------if object_id( 'pubs..t1 ') is not null
drop table t1
go
create table t1(ID varchar(10),Name varchar(10),CID1 varchar(10),CID2 varchar(10))
insert into t1(ID,Name,CID1,CID2) values( '01 ', 'Zhao ', '01 ', ' ')
insert into t1(ID,Name,CID1,CID2) values( '02 ', 'Qian ', '01 ', ' ')
insert into t1(ID,Name,CID1,CID2) values( '03 ', 'Sun ' , '04 ', ' ')
insert into t1(ID,Name,CID1,CID2) values( '04 ', 'Li '