sql Join条件中的动态列

时间:2012-12-24 03:56:08

标签: sql sql-server-2008 tsql dynamic-sql

Customer

customer_id |   customer_name | customer_city | customer_number
---------------------------------------------------------------
   1        |   john          | sanjose       | 978234
   2        |   chris         | newyork       | 293
   3        |   mary          | madrid        | 342943
   4        |   tom           | bangkok       | 8627093
---------------------------------------------------------------

Data

data_id |   data_name  |    data_city   |   data_number |   data_cust_id |  customer_id
--------------------------------------------------------------------------------------------
   1    |   abc        |    xyz         |   990         |   1        |  NULL
   2    |   john       |    sanjose     |   978234      |   1        |  NULL
   3    |   mary       |    madrid      |   8627093     |   3        |  NULL
   4    |   tom        |    LA          |   7729        |   4        |  NULL


ActionType

action_id | action_description
-----------------------------------
1         | customer_name
2         | customer_number
3         | customer_city


DataToAction

id |    data_id | action_id
--------------------------
1  |    1       | 1
2  |    1       | 2
4  |    2       | 1
5  |    2       | 2
6  |    2       | 3
7  |    3       | 1
8  |    3       | 2
9  |    4       | 1

有4个表 -

  1. 客户 - 拥有客户数据
  2. 数据 - 从外部来源(拥有客户数据和其他数据)提取的原始数据
  3. ActionType - 具有将在连接条件中使用的列名
  4. DataToAction - 对于Data表中的每个原始数据行,在此处指定要在连接中使用的列。
  5. 目标 - 在“数据”表格中填充customer_id。 我需要这样的东西

    UPDATE D
    SET D.customer_id = C.customer_id
    FROM Data D
    INNER JOIN Customer C on D.data_cust_id = C.customer_id
    WHERE *("GET THE COLUMNS TO BE MATCHED FROM DATATOACTION TABLE AND USE HERE")*
    

    例如,对于Data id 1,我将根据customer_name&更新customer_id。 customer_number,对于数据id 2,我将基于customer_name,customer_number& amp; udpate customer_id。 customer_city等。

    如何在其中要在不同表中指定要匹配的列的每一行的where子句中应用动态列条件。

1 个答案:

答案 0 :(得分:0)

那么问题还不清楚。你能详细说明最终的结果集吗? 行动目的类型表??

UPDATE D
SET D.customer_id = C.customer_id
FROM Data D
INNER JOIN Customer C on D.data_cust_id = C.customer_id INNER JOIN DataToAction DA ON DA.data_id = D.data_id