急求一SQL数据更新(或导入)语句(50分)

M

mo

Unregistered / Unconfirmed
GUEST, unregistred user!
表1: table1
ID number
a 35
b 45
c 50
d 60
... ...

表2:table2
ID number
a 50
b 40
ee 35
df 20
... ...

问题:现要求把table1中ID>a,且<d的记录(b,c)导入到table2中,若table2中已有存在
相同的ID号(b,c),则把相应数量相加就可,若不存在将要加入的ID号,则把记录插入到table2
中,用sql语句怎么表达?
附:插入table2后的结果
表2:table2
ID number
a 50
b 85
ee 35
df 20
c 50
 
Insert into table2 (id)
Select id
From table1
Where id>'a' and id<'d' and
id not in (Select id from table2)

Go
Update table2
set number=number+(select number from table1 where id>'a' and id<'d' and id=table2.id)
Go
 
to:QuickSilver
首先谢谢你!试了下,你的方法不对啊,
“Update table2
set number=number+(select number from table1 where id>'a' and id<'d' and id=table2.id)”
把第上面刚Insert into进去的数据也UPDATE掉了
(等于加了两次值啊)

在线等待!
 
把第一句改改

Insert into table2
Select id,0
From table1
Where id>'a' and id<'d' and
id not in (Select id from table2)

 
TO:QuickSilver,
改了后出错了(“Select id,0”,能否告诉我加个”0"有什么用吗),附原代码
create procedure RkdjToXykcAdd ( @rkdjname varchar(30) , @firstID varchar(10) , @endID varchar(10) )
as
begin
declare @sqltxt varchar(300)
set @sqltxt='Insert into XYKC Select WLPH,WLM,XHGG,SL,DW,0 from '+@rkdjname+
' Where RKID > '+@firstID+' and RKID < '+@endID+' and WLPH not in (Select WLPH from XYKC) '
exec(@sqltxt)
set @sqltxt='Update XYKC Set KCSL=KCSL+( select SL from '+@rkdjname+
' Where RKID > '+@firstID+' and RKID < '+@endID+' and WLPH=XYKC.WLPH )'
exec(@sqltxt)
end

执行:
exec rkdjtoxykcadd 'rkdj2002','1','5'
执行后提示信息:
服务器: 消息 8101,级别 16,状态 1,行 1
仅当使用了列的列表,并且 IDENTITY_INSERT 为 ON 时,才能在表 'XYKC' 中为标识列指定显式值。

(所影响的行数为 0 行)
 
Select id,0
防止某些情况下插入数据后得到的是
例:
id number
a null

而null加数字仍然是null

试试改成如下
Insert into table2 Select id,0 as number From table1

Insert into XYKC Select WLPH,WLM,XHGG,SL,DW,0 as 字段名 from ....

其实是多此一举,呵,因为那种情况几乎不可能发生
也可改成
Insert into XYKC (WLPH,WLM,XHGG,SL,DW) Select WLPH,WLM,XHGG,SL,DW from ....
 
TO:QuickSilver
谢谢你!呵呵,其实我也太初心了点
我想只要把“Insert into” 与“Update” 的执行顺序对调下就行了,
(先更新已有的数据,再增加新的记录)
 
还有这句也是需要再改改的:
Update table2
set number=number+(select number from table1 where id>'a' and id<'d' and id=table2.id)

当“(select number from table1 where id>'a' and id<'d' and id=table2.id)”
为空的时候就出错了(我先试试看)
 
Update table2
Set number=AA.number+BB.number
From table2 AA,(select id,number from table1 where id>'a' and id<'d') BB
Where AA.id=BB.id
 
Update Table2 Set Number=Number+A.Number From Table1 A Where A.Id=Id
and A.Id>a And A.Id<d
Go
insert into Table2 select A.Id,A.Number From Table1 A,Table2 B
Where A.Id>a And A.Id<d And A.Id<>B.Id
 
UPDATE BB
SET BB.number=AA.number+BB.number
WHERE AA.ID>A AND AA.ID<D AND AA.ID IN (SELECT ID FROM BB)
GO
INSERT INTO BB(ID,NUMBER)
SELECT ID,NUMBER
FROM AA
WHERE AA.ID NOT IN (SELECT ID FROM BB)
GO


不知道这样行不行,请大家指教。
 
同意liujunzhang的方法
 
还是觉得俺的哪个思路比较清晰。
 
多人接受答案了。
 
顶部