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
我有 2 张表 tempA 和 tempB。
温度A:
batteryid | batname | batt01 | batt02 | batt03 | batt04
----------+---------+---------+--------+---------+--------
01 | trixon | null | null | null | null
03 | jaguarv | null | null | null | null
温度B:
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 循环通过将电池 ID 与 tempB 表连接来更新 tempA 表。
谢谢