我有一些記錄,我正在從一個表格移動到另一個表格,並進行一些操作。SQL更新每個不同的一半
我已經把它們放在臨時表中,這樣我就可以進行操作了。具體而言,我需要換一個不同的值的一半到的東西列,那麼另一半變成別的東西:
在我的臨時表,我有
Animals | SeveralOtherColumns
dog
cat
fish
dog
dog
dog
fish
cat
cat
cat
,我需要有
Animals | SeveralOtherColumns
dog_A
cat_A
fish_A
dog_A
dog_B
dog_B
fish_B
cat_A
cat_B
cat_B
我不知道Animals
中有什麼不同的值,或者每個不同的值會有多少。
所以我最初的想法是:
SET @count = (SELECT COUNT(DISTINCT(Animals)) FROM #temptable)
--this throws an error, doesn't like the assignment
SET @animals = (SELECT DISTINCT(Animals) FROM #temptable)
WHILE (@count > 0)
BEGIN
-- about here is where I'm lost
-- update the first half of the distinct value
UPDATE #temptable SET #temptable.Animals = #temptable.Animals + '_A'
WHERE Animals = @animals[@count] --Pretty sure this won't work but gets the point across
FROM (SELECT TOP 50 PERCENT FROM #temptable)
-- update the remaining set of that distinct value
UPDATE #temptable SET #temptable.Animals = #temptable.Animals + '_B'
WHERE Animals = @animals[@count]
FROM #temptable
SET @count = @count - 1
END
後綴的邏輯是什麼?不明白 – Lamak
你需要任何sql server的兼容性,還是最新版本是你的目標? – infiniteRefactor
@Lamak每個不同值的前半部分都被附加了_A,其餘部分被附加了_B。用人類語言來解釋這種奇怪的... –