I have two tables (Table 1 and Table 2) which are listed below. I wanted to update a column in Table 2 while getting the data from Table 1.
Table 1
+-----------+---------------+---------------------+
+ form_id + request_id + BatchNo +
+-----------+---------------+---------------------+
+ 5649464 + 562 + Batch5649464_1 +
+-----------+---------------+---------------------+
+ 5649464 + 563 + Batch5649464_11 +
+-----------+---------------+---------------------+
Table 2
+------------+---------------+-----------+
+ NumberId + ServiceName + RefId +
+------------+---------------+-----------+
+ 5649464 + XYZ + 0 +
+------------+---------------+-----------+
+ 5649464 + XYZ + 0 +
+------------+---------------+-----------+
In Table 1 there are two rows as per list above. By Default my RefId is 0. I have to update that column with the data from Table 1 (request_id). As you can see request_id have two different data. Both data (562 and 563) should get updated as per my Expected Output. But right now I am getting result as per my Initial Output. Can anyone help to get as per my Expected Output?
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;
Initial Output
+------------+---------------+-----------+
+ NumberId + ServiceName + RefId +
+------------+---------------+-----------+
+ 5649464 + XYZ + 562 +
+------------+---------------+-----------+
+ 5649464 + XYZ + 562 +
+------------+---------------+-----------+
Expected Output
+------------+---------------+-----------+
+ NumberId + ServiceName + RefId +
+------------+---------------+-----------+
+ 5649464 + XYZ + 562 +
+------------+---------------+-----------+
+ 5649464 + XYZ + 563 +
+------------+---------------+-----------+
You can use ROW_NUMBER() to join tables and update 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
If you then select from Table2
you will get:
NumberId ServiceName RefId
5649464 XYZ 562
5649464 XYZ 563
Table2没有主键,因此您不能使用一个值更新第一行,而使用不同值更新第二行,除非您将主键添加到table2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.