DECLARE @outerCounter INT = 1, @rowCount INT,
@query NVARCHAR(MAX), @load numeric(18,3), @batcolno NVARCHAR(MAX), @inCounter INT = 1,@innerrowsCount INT
SELECT @rowCount = COUNT(*) FROM tempA
WHILE(@outercounter <= @rowCount)
BEGIN
SELECT @innerrowsCount = COUNT(*)
FROM
tempB INNER JOIN tempA
ON tempB.batteryid = tempA.batteryid
AND
tempB.uniquerowid = @outercounter
WHILE(@inCounter <= @innnerrowCounter)
BEGIN
SELECT @laod = laod FROM tempB INNER JOIN tempA
ON tempB.batteryid = tempA.batteryid
AND
tempB.uniquerowid = @inCounter
SET @testcolno = 'batt' + REPLACE(STR(@inCounter,3),' ','0')
SET @query = ' UPDATE tempA
SET '+ @testcolno + ' = '+ @load +'
WHERE tempA.rowid = '+ @outercounter + ' '
EXEC(@query)
SET @inCounter = @inCounter + 1
END
SET @outercounter = @outercounter + 1
END
tempA と tempB の 2 つのテーブルがあります。
温度:
batteryid | batname | batt01 | batt02 | batt03 | batt04
----------+---------+---------+--------+---------+--------
01 | trixon | null | null | null | null
03 | jaguarv | null | null | null | null
tempB:
batteryid | load
-----------+---------
01 | 14.58
01 | 58.12
01 | 16.89
03 | 25.47
03 | 87.65
tempA の最終出力は次のようになります。
batteryid | batname | batt01 | batt02 | batt03 | batt04
----------|----------|----------|--------|---------|--------------
01 | trixon | 14.58 | 58.12 | 16.89 | null
03 | jaguarv | 25.47 | 87.65 | null | null
上記のコードは、while ループを使用して、batteryid を tempB テーブルのバッテリー ID と結合することにより、tempA テーブルを更新します。
ありがとう