通过存储过程更新数据

时间:2016-10-19 13:44:21

标签: sql sql-server stored-procedures

我有两张表(表1和表2),如下所示。我想在获取表1中的数据时更新表2中的列。

表1

+-----------+---------------+---------------------+
+  form_id  +   request_id  +         BatchNo     +
+-----------+---------------+---------------------+
+  5649464  +      562      +     Batch5649464_1  +
+-----------+---------------+---------------------+
+  5649464  +      563      +     Batch5649464_11 +
+-----------+---------------+---------------------+

表2

+------------+---------------+-----------+
+  NumberId  +   ServiceName +    RefId  +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     0     +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     0     +
+------------+---------------+-----------+

在表1中,按照上面的列表有两行。默认情况下,我的RefId为0.我必须使用表1中的数据(request_id)更新该列。如您所见,request_id有两个不同的数据。数据(562和563)应根据我的预期输出进行更新。但是现在我按照初始输出得到了结果。 根据我的预期输出,任何人都可以帮忙吗?

DECLARE @Tempnumbers TABLE
            (
              form_id INT ,
              request_id INT
            );

         ;
        WITH    Result
                  AS ( SELECT   form_id ,
                                CONVERT(BIGINT, ( CONVERT(VARCHAR, request_id) )) AS request_id
                       FROM     [Table1] 
                     )
            INSERT  INTO @Tempnumbers
                    SELECT  form_id, request_id
                    FROM    Result;

        UPDATE  DT
        SET    RefID = request_id
       FROM    Table2 DT 
       INNER JOIN @Tempnumbers TN ON TN.NumberId = DT.form_id;

初始输出

+------------+---------------+-----------+
+  NumberId  +   ServiceName +    RefId  +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     562   +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     562   +
+------------+---------------+-----------+

预期产出

+------------+---------------+-----------+
+  NumberId  +   ServiceName +    RefId  +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     562   +
+------------+---------------+-----------+
+  5649464   +      XYZ      +     563   +
+------------+---------------+-----------+

2 个答案:

答案 0 :(得分:2)

您可以使用ROW_NUMBER()连接表并更新RefId

;WITH cte1 AS (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY form_id ORDER BY request_id) as rn
    FROM Table1 t1
), cte2 AS (
    SELECT  *,
            ROW_NUMBER() OVER (PARTITION BY NumberId ORDER BY RefId) as rn
    FROM Table2 t2
)

UPDATE c2
SET RefId = c1.request_id
FROM cte1 c1
INNER JOIN cte2 c2
    ON c1.form_id = c2.NumberId AND c1.rn = c2.rn

如果您从Table2中选择,您将获得:

NumberId    ServiceName RefId
5649464     XYZ         562
5649464     XYZ         563

答案 1 :(得分:-1)

Table2没有主键,因此您无法使用一个值更新第一行,使用不同值更新第二行,除非您向table2添加主键