[英]Updating data via stored procedure
I have two tables (Table 1 and Table 2) which are listed below. 我有两个表(表1和表2),如下所示。 I wanted to update a column in Table 2 while getting the data from Table 1.
我想在获取表1中的数据时更新表2中的列。
Table 1 表格1
+-----------+---------------+---------------------+
+ form_id + request_id + BatchNo +
+-----------+---------------+---------------------+
+ 5649464 + 562 + Batch5649464_1 +
+-----------+---------------+---------------------+
+ 5649464 + 563 + Batch5649464_11 +
+-----------+---------------+---------------------+
Table 2 表2
+------------+---------------+-----------+
+ NumberId + ServiceName + RefId +
+------------+---------------+-----------+
+ 5649464 + XYZ + 0 +
+------------+---------------+-----------+
+ 5649464 + XYZ + 0 +
+------------+---------------+-----------+
In Table 1 there are two rows as per list above. 在表1中,按照上面的列表有两行。 By Default my RefId is 0. I have to update that column with the data from Table 1 (request_id).
默认情况下,我的RefId为0.我必须使用表1中的数据(request_id)更新该列。 As you can see request_id have two different data.
如您所见,request_id有两个不同的数据。 Both data (562 and 563) should get updated as per my Expected Output.
数据(562和563)应根据我的预期输出进行更新。 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
您可以使用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
If you then select from Table2
you will get: 如果您从
Table2
选择,您将获得:
NumberId ServiceName RefId
5649464 XYZ 562
5649464 XYZ 563
Table2没有主键,因此您不能使用一个值更新第一行,而使用不同值更新第二行,除非您将主键添加到table2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.