我在Sql Server上运行一个简单的SQL查询,但它不会停止执行。
UPDATE Table_A SET Table_A.[Miktar] = Table_B.[Miktar] FROM [Retail].[dbo].[tb_DepoSevkDetay] AS Table_A INNER JOIN ( SELECT [Miktar], [UrunID] FROM [Retail].[dbo].[tb_SatisDetay] GROUP BY [UrunID], [Miktar] ) AS Table_B ON Table_A.[UrunID] = Table_B.[UrunID]
可以有循环吗?请帮忙 这是第一张表的一小部分
Depo SatisID SatisSira UrunID Satici KdvKod KDVYuzde Miktar AZ01 20001 1 3788898 999 AZ 18.00 1 AZ01 20002 1 3788898 999 AZ 18.00 1 AZ01 20003 1 3876390 999 AZ 18.00 1 AZ01 20003 2 3793202 999 AZ 18.00 1 AZ01 20003 3 4046508 999 AZ 18.00 1 AZ01 20003 4 3843387 999 AZ 18.00 1 AZ01 20003 5 3850608 999 AZ 18.00 1第二个
BaslikID Sira UrunID Miktar Fiyat Depo 20001 1 3792703 1 1 AZ01 20002 1 4067131 1 1 AZ01 20003 1 3251881 1 1 AZ01 20003 2 3251883 1 1 AZ01 20003 3 3788887 1 1 AZ01 20003 4 3788890 1 1 AZ01 20004 1 3761260 2 1 AZ01
答案 0 :(得分:0)
更新Table_A
的值可能存在冲突:如果子查询为同一UrunID
返回多条记录,则Miktar
中的哪一条不明确}值应该用于更新Table_A
记录。
因此,请确保子查询每个UrunID
仅返回一条记录:
UPDATE
Table_A
SET
Table_A.[Miktar] = Table_B.[Miktar]
FROM
[Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
INNER JOIN (
SELECT [UrunID], Min([Miktar]) as Miktar
FROM [Retail].[dbo].[tb_SatisDetay]
GROUP BY [UrunID]
) AS Table_B
ON Table_A.[UrunID] = Table_B.[UrunID]
答案 1 :(得分:0)
在大多数情况下,使用UPDATE
的{{1}}比相关查询慢。在此,我假设JOIN
每个Miktar
UrunID
如果 UPDATE Table_A as A
SET [Miktar] =
(SELECT [Miktar] FROM [Retail].[dbo].[tb_SatisDetay] as B where B.[UrunID] = A.[UrunID])
和UrunID
答案 2 :(得分:0)
考虑到您为JOIN
条件中涉及的列准备了适当的索引。根本没有在子查询中看到group by
的需要。您可以将查询更改为如下所示。只是发布查询是不够的。考虑发布查询执行计划。
UPDATE
Table_A
SET
Table_A.[Miktar] = Table_B.[Miktar]
FROM
[Retail].[dbo].[tb_DepoSevkDetay] AS Table_A
INNER JOIN [Retail].[dbo].[tb_SatisDetay] AS Table_B
ON Table_A.[UrunID] = Table_B.[UrunID];