Knowledgebase
22 Jul
In Microsofts SQL-Server soll weiterer dynamischer Code zu jeder Zeile einer Abfrage ausgeführt werden. Bei Oracle gibt es dafür FOR EACH row. MS T-SQL hat dieses Konstrukt noch nicht, hier muss man sich mit einem Workaround behelfen. Justin Carmony hat sich damit intensiv beschäftigt. In den Kommentaren sind noch verschiedene andere Möglichkeiten aufgeführt.
Es fehlt aber noch eine recht einfache über die ab Version 2005 verfügbaren Common Table Expressions:
DECLARE @cnt int DECLARE @cntMax int SELECT @cnt=1; SELECT @cntMax =Count(ID) FROM myTable WHERE x=1 DECLARE @y int WHILE @cnt <= @cntMax BEGIN --While Loop WITH AbfrageLoop AS ( SELECT row_number() OVER (ORDER BY ID) AS Row,* FROM myTable WHERE x=1 ) SELECT @y=y FROM AbfrageLoop WHERE Row=@cnt --do something based on the query DELETE FROM AnotherTable WHERE AnotherY=@y SELECT @cnt = @cnt+1 END --While Loop
siehe Justin Carmony, MS MSDN
One Response for "MS SQL T-SQL FOR EACH Row"
[...] Wenn man mit dem SQL Server 2005 eine Tabelle Reihe für Reihe durchlaufen möchte, muss man folgendes tun (Quelle: Link): [...]
Leave a reply