有一排数据 1,22.0+2,33.0+4,25.0
其中 1,22.0 这样是一组数据,每组以+分隔, 1表示ID,22.0是单价...
现在从前台传一组数据过来,然后按照+号拆分以后,在拆分,,
这样把 1 22.0
2 33.0
4 25.0
这三条数据插入表 Tmp里面...
其中要求 如果表Tmp里面 没有这个ID,则插入该数据,如果有ID,则修改该ID下的价格值...
在不用 while 循环的情况下 能不能实现
注,不需要实现 字符串拆分函数
假设系统有两个 函数
fn_getStr(str,split,index) 意思是把str按照split拆分后,返回index所在的值..如 fn_getStr('2222+333','+',1) 返回 2222 下标从1开始
fn_getTable(str,split) 意思是吧str按照split拆分,返回被拆分后组成的表 如 fn_getTable(‘2222+3333’,'+')返回
2222
3333
这个表
上面两个假设已经实现好了的
------解决思路----------------------
-- 大概如下,你自己改改
with
x as (select ROW_NUMBER() over(order by getdate()) rn ,id from fn_getStr()) ,
y as (select ROW_NUMBER() over(order by getdate()) rn ,price from fn_getTable()) ,
m as (select x.id , y.price from x ,y where x.rn = y.rn)
merge into test
using m on text.id = m.id
when matched then update set test.price = m.price
when not matched then insert (id,price) values(m.id,m.price)
go
------解决思路----------------------
假设这组数据: 1,22.0+2,33.0+4,25.0根据协议已经提取到表source,在sql server 2008 + 可使用merge,参考:
select * from temp
select * from source
Merge into temp as t
using source as s
on t.id = s.id
when matched then update set t.price = s.price
when not matched then insert values(s.id,s.price);
select * from temp

------解决思路----------------------
在08以下的版本可以两步:
--1 insert 新ID
insert into temp
select s.id,s.price
from source s left join temp t on s.id = t.id and t.id is null
--2 update 已存ID
update t
set t.price = s.price
from temp t
inner join source s on t.id = s.id