将dindan表客户浆糊更新到client表中.sql 1.0 KB

1234567891011121314151617181920212223242526272829
  1. USE [db]
  2. -- 定义变量;
  3. DECLARE @COUNT INT -- 数量;
  4. DECLARE @SUM INT -- 指定订单号数量;
  5. DECLARE @OrderId NVARCHAR(80) -- 订单号;
  6. DECLARE @Phone1 NVARCHAR(80) -- 电话1;
  7. DECLARE @Phone2 NVARCHAR(80) -- 电话2;
  8. DECLARE @Name1 NVARCHAR(80) -- 姓名1;
  9. DECLARE @Name2 NVARCHAR(80) -- 姓名2;
  10. -- 查询出所有订单的电话,并插入到临时表中;
  11. SELECT IDENTITY(INT,1,1) AS AutoId, id, phone1, phone2, name1, name2 INTO #temp_dindan FROM dindan
  12. -- 获取临时表最大ID;
  13. SELECT @COUNT = MAX(AutoId) FROM #temp_dindan
  14. -- 循环将dindan表里的订单电话更新到client对应的订单记录中;
  15. WHILE @COUNT > 0
  16. BEGIN
  17. SELECT @OrderId = id , @Phone1 = phone1, @Phone2 = phone2, @Name1 = name1, @Name2 = name2 FROM #temp_dindan WHERE AutoId = @COUNT
  18. SELECT @SUM = COUNT(id) FROM client WHERE id = @OrderId
  19. if @SUM = 0
  20. INSERT INTO client(id, name1, name2, phone1, phone2) VALUES(@OrderId, @Name1, @Name2, @phone1, @phone2)
  21. ELSE
  22. UPDATE client SET phone1 = @Phone1, phone2 = @Phone2 WHERE id = @OrderId
  23. SET @COUNT = @COUNT -1
  24. END
  25. -- 最后,清除临时表;
  26. DROP TABLE #temp_dindan