Notitie
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen u aan te melden of de directory te wijzigen.
Voor toegang tot deze pagina is autorisatie vereist. U kunt proberen de mappen te wijzigen.
Included in this article are tips for dedicated SQL pool solution development using T-SQL loops and replacing cursors.
Purpose of WHILE loops
Dedicated SQL pools in Azure Synapse support the WHILE loop for repeatedly executing statement blocks. Deze WHILE-lus wordt voortgezet zolang de opgegeven voorwaarden waar zijn of totdat de code de lus specifiek beëindigt met behulp van het trefwoord BREAK.
Loops are useful for replacing cursors defined in SQL code. Fortunately, almost all cursors that are written in SQL code are of the fast forward, read-only variety. WHILE-lussen zijn dus een goed alternatief voor het vervangen van cursors.
Replacing cursors in dedicated SQL pool
However, before diving in head first you should ask yourself the following question: "Could this cursor be rewritten to use set-based operations?"
In many cases, the answer is yes and is frequently the best approach. A set-based operation often performs faster than an iterative, row by row approach.
Fast forward read-only cursors can be easily replaced with a looping construct. The following example is a simple one. In dit codevoorbeeld worden de statistieken voor elke tabel in de database bijgewerkt. Door de tabellen in de lus te herhalen, wordt elke opdracht op volgorde uitgevoerd.
Maak eerst een tijdelijke tabel met een uniek rijnummer dat wordt gebruikt om de afzonderlijke instructies te identificeren:
CREATE TABLE #tbl
WITH
( DISTRIBUTION = ROUND_ROBIN
)
AS
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Sequence
, [name]
, 'UPDATE STATISTICS '+QUOTENAME([name]) AS sql_code
FROM sys.tables
;
Second, initialize the variables required to perform the loop:
DECLARE @nbr_statements INT = (SELECT COUNT(*) FROM #tbl)
, @i INT = 1
;
Now loop over statements executing them one at a time:
WHILE @i <= @nbr_statements
BEGIN
DECLARE @sql_code NVARCHAR(4000) = (SELECT sql_code FROM #tbl WHERE Sequence = @i);
EXEC sp_executesql @sql_code;
SET @i +=1;
END
Verwijder ten slotte de tijdelijke tabel die u in de eerste stap hebt gemaakt
DROP TABLE #tbl;
Volgende stappen
Zie ontwikkelingsoverzicht voor meer ontwikkelingstips.