SQL Server2008中CROSS APPLY的应用范例(一)
——将多个不同值更新到不同条件匹配的记录中
有一个库存表,需要写一个SQL语句,一次将所有变更的库存全部写进去
输入数据格式:
goods_id1=goods_amount1,goods_id2=goods_amount2[,goods_id3=goods_amount3[,...]]
具体做法:
将输入数据格式解析到一个表变量里,关联该表变量,实现全部更新
语句如下:
DECLARE @tblActual TABLE
(
A_ID BIGINT,
A_Amount BIGINT
);
INSERT INTO @tblActual SELECT B.ID, B.Amount FROM (
SELECT [value] = CONVERT(XML , '<v>' + REPLACE(@GoodsCountLst , ',' , '</v><v>') + '</v>')) A
CROSS APPLY (SELECT ID = SUBSTRING(N.v.value('.' , 'varchar(100)'), 1, charindex( '=', N.v.value('.' , 'varchar(100)')) - 1 ), Amount = SUBSTRING(N.v.value('.' , 'varchar(100)'), charindex( '=', N.v.value('.' , 'varchar(100)')) + 1, LEN(N.v.value('.' , 'varchar(100)'))) FROM A.[value].nodes('/v') N ( v ) ) B;
UPDATE TMS_OrderGoods SET Goods_ActualCount = (SELECT TOP 1 t1.A_Amount FROM @tblActual AS t1 WHERE t1.A_ID = Goods_ID), Goods_Updater = @OperatorID, Goods_UpdateTime = GETDATE() WHERE Goods_OrderID = @OrderID;