将dindan表客户资料更新到client表.sql 1.1 KB

123456789101112131415161718192021222324252627282930
  1. USE [db]
  2. -- 定义变量;
  3. DECLARE @COUNT INT -- 数量;
  4. DECLARE @SIZE 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, name1, name2, phone1, phone2 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 , @Name1 = name1, @Name2 = name2, @Phone1 = phone1, @Phone2 = phone2 FROM #temp_dindan WHERE AutoId = @COUNT
  18. SELECT @SIZE = COUNT(*) FROM client WHERE id = @OrderId
  19. if @SIZE > 0
  20. UPDATE client SET name1 = @Name1, name2 = @Name2, phone1 = @Phone1, phone2 = @Phone2 WHERE id = @OrderId
  21. ELSE
  22. INSERT INTO client([id],[name1],[name2],[phone1],[phone2])VALUES(@OrderId, @Name1, @Name2, @Phone1, @Phone2)
  23. SET @COUNT = @COUNT -1
  24. SET @SIZE = 0
  25. END
  26. -- 最后,清除临时表;
  27. DROP TABLE #temp_dindan