DELETE (Transact-SQL)DELETE (Transact-SQL)
Si applica a:Applies to: SQL ServerSQL Server (tutte le versioni supportate)
SQL ServerSQL Server (all supported versions)
database SQL di AzureAzure SQL Database
database SQL di AzureAzure SQL Database
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
SQL ServerSQL Server (tutte le versioni supportate)
SQL ServerSQL Server (all supported versions)
database SQL di AzureAzure SQL Database
database SQL di AzureAzure SQL Database
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Istanza gestita di SQL di AzureAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
Rimuove una o più righe da una tabella o vista in SQL ServerSQL Server.Removes one or more rows from a table or view in SQL ServerSQL Server.
Convenzioni della sintassi Transact-SQL
Transact-SQL Syntax Conventions
SintassiSyntax
-- Syntax for SQL Server and Azure SQL Database
[ WITH <common_table_expression> [ ,...n ] ]
DELETE
[ TOP ( expression ) [ PERCENT ] ]
[ FROM ]
{ { table_alias
| <object>
| rowset_function_limited
[ WITH ( table_hint_limited [ ...n ] ) ] }
| @table_variable
}
[ <OUTPUT Clause> ]
[ FROM table_source [ ,...n ] ]
[ WHERE { <search_condition>
| { [ CURRENT OF
{ { [ GLOBAL ] cursor_name }
| cursor_variable_name
}
]
}
}
]
[ OPTION ( <Query Hint> [ ,...n ] ) ]
[; ]
<object> ::=
{
[ server_name.database_name.schema_name.
| database_name. [ schema_name ] .
| schema_name.
]
table_or_view_name
}
-- Syntax for Azure Synapse Analytics
[ WITH <common_table_expression> [ ,...n ] ]
DELETE [database_name . [ schema ] . | schema. ] table_name
FROM [database_name . [ schema ] . | schema. ] table_name
JOIN {<join_table_source>}[ ,...n ]
ON <join_condition>
[ WHERE <search_condition> ]
[ OPTION ( <query_options> [ ,...n ] ) ]
[; ]
<join_table_source> ::=
{
[ database_name . [ schema_name ] . | schema_name . ] table_or_view_name [ AS ] table_or_view_alias
[ <tablesample_clause>]
| derived_table [ AS ] table_alias [ ( column_alias [ ,...n ] ) ]
}
-- Syntax for Parallel Data Warehouse
DELETE
[ FROM [database_name . [ schema ] . | schema. ] table_name ]
[ WHERE <search_condition> ]
[ OPTION ( <query_options> [ ,...n ] ) ]
[; ]
Nota
Per visualizzare la sintassi Transact-SQL per SQL Server 2014 e versioni precedenti, vedere Documentazione delle versioni precedenti.To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
ArgomentiArguments
WITH <common_table_expression>WITH <common_table_expression>
Specifica il set di risultati denominato temporaneo, anche noto come espressione di tabella comune, definito nell'ambito dell'istruzione DELETE.Specifies the temporary named result set, also known as common table expression, defined within the scope of the DELETE statement. Il set di risultati deriva da un'istruzione SELECT.The result set is derived from a SELECT statement.
Le espressioni di tabella comuni possono inoltre essere utilizzate con istruzioni SELECT, INSERT, UPDATE e CREATE VIEW.Common table expressions can also be used with the SELECT, INSERT, UPDATE, and CREATE VIEW statements. Per altre informazioni, vedere WITH common_table_expression (Transact-SQL).For more information, see WITH common_table_expression (Transact-SQL).
TOP ( expression ) [ PERCENT ]TOP (expression) [ PERCENT ]
Viene specificato il numero o la percentuale di righe casuali che verranno eliminate.Specifies the number or percent of random rows that will be deleted. Il valore di expression può essere specificato come numero o come percentuale di righe.expression can be either a number or a percent of the rows. Le righe a cui viene fatto riferimento nell'espressione TOP utilizzata con INSERT, UPDATE o DELETE non sono disposte in alcun ordine.The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order. Per altre informazioni, vedere TOP (Transact-SQL).For more information, see TOP (Transact-SQL).
FROMFROM
Parola chiave facoltativa che è possibile specificare tra la parola chiave DELETE e l'oggetto di destinazione table_or_view_name o rowset_function_limited.An optional keyword that can be used between the DELETE keyword and the target table_or_view_name, or rowset_function_limited.
table_aliastable_alias
Alias specificato nella clausola FROM table_source che rappresenta la tabella o la vista da cui devono essere eliminate le righe.The alias specified in the FROM table_source clause representing the table or view from which the rows are to be deleted.
server_nameserver_name
Si applica a: SQL Server 2008SQL Server 2008 e versioni successive.Applies to: SQL Server 2008SQL Server 2008 and later.
Nome del server, che usa come nome un nome di server collegato o la funzione OPENDATASOURCE, in cui è contenuta la tabella o la vista.The name of the server (using a linked server name or the OPENDATASOURCE function as the server name) on which the table or view is located. Se server_name è specificato, è obbligatorio specificare database_name e schema_name.If server_name is specified, database_name and schema_name are required.
database_namedatabase_name
Nome del database.The name of the database.
schema_nameschema_name
Nome dello schema a cui appartiene la tabella o la vista.The name of the schema to which the table or view belongs.
table_or_view_nametable_or_view_name
Nome della tabella o della vista da cui si desidera rimuovere le righe.The name of the table or view from which the rows are to be removed.
È inoltre possibile utilizzare una variabile di tabella, nel relativo ambito, come origine della tabella in un'istruzione DELETE.A table variable, within its scope, also can be used as a table source in a DELETE statement.
È necessario che la vista a cui viene fatto riferimento in table_or_view_name sia aggiornabile e includa un riferimento esatto a una tabella di base nella clausola FROM della definizione della vista.The view referenced by table_or_view_name must be updatable and reference exactly one base table in the FROM clause of the view definition. Per altre informazioni sulle viste aggiornabili, vedere CREATE VIEW (Transact-SQL).For more information about updatable views, see CREATE VIEW (Transact-SQL).
rowset_function_limitedrowset_function_limited
Si applica a: SQL Server 2008SQL Server 2008 e versioni successive.Applies to: SQL Server 2008SQL Server 2008 and later.
Funzione OPENQUERY o OPENROWSET, in base alle funzionalità del provider.Either the OPENQUERY or OPENROWSET function, subject to provider capabilities.
WITH ( <table_hint_limited> [... n] )WITH ( <table_hint_limited> [... n] )
Specifica uno o più hint di tabella consentiti per una tabella di destinazione.Specifies one or more table hints that are allowed for a target table. La parola chiave WITH e le parentesi sono obbligatorie.The WITH keyword and the parentheses are required. Le opzioni NOLOCK e READUNCOMMITTED non sono consentite.NOLOCK and READUNCOMMITTED are not allowed. Per altre informazioni sugli hint di tabella, vedere Hint di tabella (Transact-SQL).For more information about table hints, see Table Hints (Transact-SQL).
<OUTPUT_Clause>
Restituisce le righe eliminate o le espressioni basate su tali righe nell'ambito di un'operazione DELETE.Returns deleted rows, or expressions based on them, as part of the DELETE operation. La clausola OUTPUT non è supportata nelle istruzioni DML eseguite su viste o tabelle remote.The OUTPUT clause is not supported in any DML statements targeting views or remote tables. Per altre informazioni sugli argomenti e il comportamento di questa clausola, vedere Clausola OUTPUT (Transact-SQL).For more information about the arguments and behavior of this clause, see OUTPUT Clause (Transact-SQL).
FROM table_sourceFROM table_source
Specifica una clausola FROM aggiuntiva.Specifies an additional FROM clause. Questa estensione di Transact-SQLTransact-SQL dell'istruzione DELETE consente di specificare dati di <table_source> e di eliminare le righe corrispondenti dalla tabella specificata nella prima clausola FROM.This Transact-SQLTransact-SQL extension to DELETE allows specifying data from <table_source> and deleting the corresponding rows from the table in the first FROM clause.
È possibile utilizzare questa estensione, specificando un join, al posto di una sottoquery nella clausola WHERE per identificare le righe che si desidera rimuovere.This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed.
Per altre informazioni, vedere FROM (Transact-SQL).For more information, see FROM (Transact-SQL).
WHEREWHERE
Specifica le condizioni utilizzate per limitare il numero di righe da eliminare.Specifies the conditions used to limit the number of rows that are deleted. Se la clausola WHERE viene omessa, l'istruzione DELETE elimina tutte le righe della tabella.If a WHERE clause is not supplied, DELETE removes all the rows from the table.
Le operazioni di eliminazione possono essere di due diversi tipi in base al contenuto della clausola WHERE:There are two forms of delete operations based on what is specified in the WHERE clause:
Le eliminazioni con ricerca specificano una condizione di ricerca che qualifica le righe da eliminare.Searched deletes specify a search condition to qualify the rows to delete. Ad esempio, WHERE column_name = value.For example, WHERE column_name = value.
Le eliminazioni posizionate utilizzano la clausola CURRENT OF per specificare un cursore.Positioned deletes use the CURRENT OF clause to specify a cursor. L'operazione di eliminazione viene eseguita nella posizione corrente del cursore.The delete operation occurs at the current position of the cursor. Questo tipo di eliminazione risulta più accurato rispetto a un'istruzione DELETE con ricerca che usa una clausola WHERE search_condition per qualificare le righe da eliminare.This can be more accurate than a searched DELETE statement that uses a WHERE search_condition clause to qualify the rows to be deleted. Un'istruzione DELETE con ricerca elimina più righe se la condizione di ricerca non identifica una singola riga in modo univoco.A searched DELETE statement deletes multiple rows if the search condition does not uniquely identify a single row.
<search_condition>
Specifica le condizioni di restrizione per le righe da eliminare.Specifies the restricting conditions for the rows to be deleted. Non sono previsti limiti per il numero di predicati che è possibile includere in una condizione di ricerca.There is no limit to the number of predicates that can be included in a search condition. Per altre informazioni, vedere Condizione di ricerca(Transact-SQL).For more information, see Search Condition (Transact-SQL).
CURRENT OFCURRENT OF
Specifica che l'istruzione DELETE viene eseguita nella posizione corrente del cursore specificato.Specifies that the DELETE is performed at the current position of the specified cursor.
GLOBALGLOBAL
Specifica che cursor_name fa riferimento a un cursore globale.Specifies that cursor_name refers to a global cursor.
cursor_namecursor_name
Nome del cursore aperto da cui viene eseguita l'operazione di recupero.Is the name of the open cursor from which the fetch is made. Se sono presenti un cursore globale e un cursore locale denominati cursor_name ed è stato specificato l'argomento GLOBAL, l'argomento fa riferimento al cursore globale. Se non è stato specificato l'argomento GLOBAL, fa riferimento al cursore locale.If both a global and a local cursor with the name cursor_name exist, this argument refers to the global cursor if GLOBAL is specified; otherwise, it refers to the local cursor. Il cursore deve consentire operazioni di aggiornamento.The cursor must allow updates.
cursor_variable_namecursor_variable_name
Nome di una variabile di cursore.The name of a cursor variable. La variabile di cursore deve fare riferimento a un cursore che consente operazioni di aggiornamento.The cursor variable must reference a cursor that allows updates.
OPTION ( <query_hint> [ , ... n] )OPTION ( <query_hint> [ ,... n] )
Parole chiave che indicano quali hint di ottimizzazione vengono utilizzati per personalizzare la modalità di elaborazione dell'istruzione nel Motore di databaseDatabase Engine.Keywords that indicate which optimizer hints are used to customize the way the Motore di databaseDatabase Engine processes the statement. Per altre informazioni, vedere Hint per la query (Transact-SQL).For more information, see Query Hints (Transact-SQL).
Procedure consigliateBest Practices
Per eliminare tutte le righe in una tabella, utilizzare TRUNCATE TABLE.To delete all the rows in a table, use TRUNCATE TABLE. L'esecuzione di TRUNCATE TABLE è più rapida rispetto a quella di DELETE e comporta un minor utilizzo di risorse del log delle transazioni e di sistema.TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources. TRUNCATE TABLE presenta alcune restrizioni, ad esempio, la tabella non può partecipare alla replica.TRUNCATE TABLE has restrictions, for example, the table cannot participate in replication. Per altre informazioni, vedere TRUNCATE TABLE (Transact-SQL)For more information, see TRUNCATE TABLE (Transact-SQL)
Usare la funzione @@ROWCOUNT per restituire il numero di righe eliminate nell'applicazione client.Use the @@ROWCOUNT function to return the number of deleted rows to the client application. Per altre informazioni, vedere @@ROWCOUNT (Transact-SQL).For more information, see @@ROWCOUNT (Transact-SQL).
Gestione degli erroriError Handling
È possibile implementare la gestione degli errori per l'istruzione DELETE specificando l'istruzione in un costrutto TRY...CATCH.You can implement error handling for the DELETE statement by specifying the statement in a TRY...CATCH construct.
L'istruzione DELETE può avere esito negativo se viola un trigger o tenta di rimuovere una riga a cui fanno riferimento i dati di un'altra tabella contenente un vincolo FOREIGN KEY.The DELETE statement may fail if it violates a trigger or tries to remove a row referenced by data in another table with a FOREIGN KEY constraint. Se l'istruzione DELETE tenta di rimuovere più righe e l'eliminazione di una qualsiasi di queste righe viola un trigger o un vincolo, l'istruzione viene annullata, viene restituito un errore e non viene rimossa alcuna riga.If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.
Quando un'istruzione DELETE rileva un errore aritmetico, ovvero un errore di overflow, una divisione per zero o un errore di dominio, durante la valutazione di un'espressione, Motore di databaseDatabase Engine gestisce l'errore come se l'opzione SET ARITHABORT fosse impostata su ON.When a DELETE statement encounters an arithmetic error (overflow, divide by zero, or a domain error) occurring during expression evaluation, the Motore di databaseDatabase Engine handles these errors as if SET ARITHABORT is set ON. La parte rimanente del batch viene annullata e viene restituito un messaggio di errore.The rest of the batch is canceled, and an error message is returned.
InteroperabilitàInteroperability
È possibile utilizzare l'istruzione DELETE nel corpo di una funzione definita dall'utente se l'oggetto modificato è una variabile di tabella.DELETE can be used in the body of a user-defined function if the object modified is a table variable.
Quando si elimina una riga che contiene una colonna FILESTREAM, vengono eliminati anche i file del file system sottostanti.When you delete a row that contains a FILESTREAM column, you also delete its underlying file system files. I file sottostanti vengono rimossi dal Garbage Collector di FILESTREAM.The underlying files are removed by the FILESTREAM garbage collector. Per altre informazioni, vedere Accedere a dati FILESTREAM con Transact-SQL.For more information, see Access FILESTREAM Data with Transact-SQL.
Non è possibile specificare la clausola FROM in un'istruzione DELETE contenente un riferimento diretto o indiretto a una vista per cui è stato definito un trigger INSTEAD OF.The FROM clause cannot be specified in a DELETE statement that references, either directly or indirectly, a view with an INSTEAD OF trigger defined on it. Per altre informazioni sui trigger INSTEAD OF, vedere CREATE TRIGGER (Transact-SQL).For more information about INSTEAD OF triggers, see CREATE TRIGGER (Transact-SQL).
Limitazioni e restrizioniLimitations and Restrictions
Se TOP viene utilizzato con DELETE, le righe a cui viene fatto riferimento non vengono disposte in alcun ordine e la clausola ORDER BY non può essere specificata in modo diretto in questa istruzione.When TOP is used with DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in this statement. Se si desidera utilizzare TOP per eliminare le righe in un ordine cronologico significativo, è necessario utilizzare TOP insieme a una clausola ORDER BY in un'istruzione sub-SELECT.If you need to use TOP to delete rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause in a subselect statement. Vedere la sezione Esempi più avanti in questo argomento.See the Examples section that follows in this topic.
Non è possibile utilizzare TOP in un'istruzione DELETE in viste partizionate.TOP cannot be used in a DELETE statement against partitioned views.
Comportamento di bloccoLocking Behavior
Per impostazione predefinita, un'istruzione DELETE acquisisce sempre un blocco preventivo esclusivo (IX) sull'oggetto tabella che modifica e mantiene tale blocco fino al completamento della transazione.By default, a DELETE statement always acquires an intent exclusive (IX) lock on the table object it modifies, and holds that lock until the transaction completes. Con un blocco preventivo esclusivo (IX) nessun'altra transazione può modificare dati. Le operazioni di lettura possono essere eseguite solo usando l'hint NOLOCK o il livello di isolamento Read Uncommitted.With an intent exclusive (IX) lock, no other transactions can modify data; read operations can take place only with the use of the NOLOCK hint or read uncommitted isolation level. È possibile specificare hint di tabella per eseguire l'override di questo comportamento predefinito per la durata dell'istruzione DELETE specificando un altro metodo di blocco. Gli hint dovrebbero comunque essere utilizzati solo se strettamente necessario ed esclusivamente da sviluppatori e amministratori di database esperti.You can specify table hints to override this default behavior for the duration of the DELETE statement by specifying another locking method, however, we recommend that hints be used only as a last resort by experienced developers and database administrators. Per altre informazioni, vedere Hint di tabella (Transact-SQL).For more information, see Table Hints (Transact-SQL).
Quando si eliminano righe da un heap, il Motore di databaseDatabase Engine può utilizzare il blocco di riga o di pagina per l'operazione.When rows are deleted from a heap the Motore di databaseDatabase Engine may use row or page locking for the operation. Le pagine svuotate dall'operazione di eliminazione rimangono pertanto allocate all'heap.As a result, the pages made empty by the delete operation remain allocated to the heap. Se le pagine vuote non vengono deallocate, non è possibile riutilizzare lo spazio associato per altri oggetti nel database.When empty pages are not deallocated, the associated space cannot be reused by other objects in the database.
Per eliminare le righe di un heap e deallocare le pagine, utilizzare uno dei metodi seguenti.To delete rows in a heap and deallocate pages, use one of the following methods.
Specificare l'hint TABLOCK nell'istruzione DELETE.Specify the TABLOCK hint in the DELETE statement. Se si utilizza l'hint TABLOCK, nell'operazione di eliminazione viene accettato un blocco esclusivo nella tabella anziché un blocco di riga o di pagina.Using the TABLOCK hint causes the delete operation to take an exclusive lock on the table instead of a row or page lock. In questo modo sarà possibile deallocare le pagine.This allows the pages to be deallocated. Per altre informazioni sugli hint TABLOCK, vedere Hint di tabella (Transact-SQL).For more information about the TABLOCK hint, see Table Hints (Transact-SQL).
Usare
TRUNCATE TABLE
se è necessario eliminare tutte le righe della tabella.UseTRUNCATE TABLE
if all rows are to be deleted from the table.Creare un indice cluster sull'heap prima di eliminare le righe.Create a clustered index on the heap before deleting the rows. È possibile eliminare l'indice cluster dopo l'eliminazione delle righe.You can drop the clustered index after the rows are deleted. Questo metodo richiede più tempo rispetto ai precedenti e utilizza una maggiore quantità di risorse temporanee.This method is more time consuming than the previous methods and uses more temporary resources.
Nota
Le pagine vuote possono essere rimosse da un heap in qualsiasi momento con l'istruzione ALTER TABLE <table_name> REBUILD
.Empty pages can be removed from a heap at any time by using the ALTER TABLE <table_name> REBUILD
statement.
Comportamento di registrazioneLogging Behavior
L'istruzione DELETE viene sempre registrata completamente.The DELETE statement is always fully logged.
SicurezzaSecurity
AutorizzazioniPermissions
Le autorizzazioni DELETE
sono necessarie nella tabella di destinazione.DELETE
permissions are required on the target table. Se l'istruzione contiene una clausola WHERE, sono inoltre richieste le autorizzazioni SELECT
.SELECT
permissions are also required if the statement contains a WHERE clause.
Le autorizzazioni DELETE vengono concesse per impostazione predefinita ai membri del ruolo predefinito del server sysadmin
, ai membri dei ruoli predefiniti del database db_owner
e db_datawriter
e al proprietario della tabella.DELETE permissions default to members of the sysadmin
fixed server role, the db_owner
and db_datawriter
fixed database roles, and the table owner. I membri dei ruoli sysadmin
, db_owner
e db_securityadmin
e il proprietario della tabella possono trasferire le autorizzazioni ad altri utenti.Members of the sysadmin
, db_owner
, and the db_securityadmin
roles, and the table owner can transfer permissions to other users.
EsempiExamples
CategoryCategory | Elementi di sintassi inclusiFeatured syntax elements |
---|---|
Sintassi di baseBasic syntax | DELETEDELETE |
Limitazione delle righe eliminateLimiting the rows deleted | WHERE • FROM • cursore •WHERE • FROM • cursor • |
Eliminazione di righe da una tabella remotaDeleting rows from a remote table | Server collegato • funzione per set di righe OPENQUERY • funzione per set di righe OPENDATASOURCELinked server • OPENQUERY rowset function • OPENDATASOURCE rowset function |
Acquisizione dei risultati dell'istruzione DELETECapturing the results of the DELETE statement | Clausola OUTPUTOUTPUT clause |
Sintassi di baseBasic Syntax
Negli esempi contenuti in questa sezione vengono illustrate le funzionalità di base dell'istruzione DELETE tramite la sintassi minima richiesta.Examples in this section demonstrate the basic functionality of the DELETE statement using the minimum required syntax.
R.A. Utilizzo di DELETE senza una clausola WHEREUsing DELETE with no WHERE clause
Nell'esempio seguente vengono eliminate tutte le righe dalla tabella SalesPersonQuotaHistory
nel database AdventureWorks2012AdventureWorks2012 perché una clausola WHERE non è utilizzata per limitare il numero di righe eliminate.The following example deletes all rows from the SalesPersonQuotaHistory
table in the AdventureWorks2012AdventureWorks2012 database because a WHERE clause is not used to limit the number of rows deleted.
DELETE FROM Sales.SalesPersonQuotaHistory;
GO
Limitazione delle righe eliminateLimiting the Rows Deleted
Negli esempi riportati in questa sezione viene illustrato come limitare il numero di righe che verranno eliminate.Examples in this section demonstrate how to limit the number of rows that will be deleted.
B.B. Utilizzo della clausola WHERE per eliminare un set di righeUsing the WHERE clause to delete a set of rows
Nell'esempio seguente vengono eliminate tutte le righe della tabella ProductCostHistory
del database AdventureWorks2012AdventureWorks2012 in cui il valore della colonna StandardCost
è maggiore di 1000.00
.The following example deletes all rows from the ProductCostHistory
table in the AdventureWorks2012AdventureWorks2012 database in which the value in the StandardCost
column is more than 1000.00
.
DELETE FROM Production.ProductCostHistory
WHERE StandardCost > 1000.00;
GO
Nell'esempio seguente viene illustrata una clausola WHERE più complessa.The following example shows a more complex WHERE clause. La clausola WHERE definisce due condizioni che devono essere soddisfatte per determinare le righe da eliminare.The WHERE clause defines two conditions that must be met to determine the rows to delete. Il valore nella colonna StandardCost
deve essere compreso tra 12.00
e 14.00
, mentre quello nella colonna SellEndDate
deve essere Null.The value in the StandardCost
column must be between 12.00
and 14.00
and the value in the column SellEndDate
must be null. Nell'esempio viene inoltre stampato il valore dalla funzione @@ROWCOUNT per restituire il numero di righe eliminate.The example also prints the value from the @@ROWCOUNT function to return the number of deleted rows.
DELETE Production.ProductCostHistory
WHERE StandardCost BETWEEN 12.00 AND 14.00
AND EndDate IS NULL;
PRINT 'Number of rows deleted is ' + CAST(@@ROWCOUNT as char(3));
C.C. Utilizzo di un cursore per determinare la riga da eliminareUsing a cursor to determine the row to delete
Nell'esempio seguente viene eliminata una riga dalla tabella EmployeePayHistory
nel database AdventureWorks2012AdventureWorks2012 usando un cursore denominato complex_cursor
.The following example deletes a single row from the EmployeePayHistory
table in the AdventureWorks2012AdventureWorks2012 database using a cursor named complex_cursor
. L'operazione di eliminazione interessa unicamente la riga attualmente recuperata dal cursore.The delete operation affects only the single row currently fetched from the cursor.
DECLARE complex_cursor CURSOR FOR
SELECT a.BusinessEntityID
FROM HumanResources.EmployeePayHistory AS a
WHERE RateChangeDate <>
(SELECT MAX(RateChangeDate)
FROM HumanResources.EmployeePayHistory AS b
WHERE a.BusinessEntityID = b.BusinessEntityID) ;
OPEN complex_cursor;
FETCH FROM complex_cursor;
DELETE FROM HumanResources.EmployeePayHistory
WHERE CURRENT OF complex_cursor;
CLOSE complex_cursor;
DEALLOCATE complex_cursor;
GO
D.D. Utilizzo di join e sottoquery per i dati di una tabella per eliminare righe di un'altra tabellaUsing joins and subqueries to data in one table to delete rows in another table
Negli esempi seguenti vengono illustrati due modi per eliminare righe di una tabella in base ai dati di un'altra tabella.The following examples show two ways to delete rows in one table based on data in another table. In entrambi gli esempi le righe della tabella SalesPersonQuotaHistory
del database AdventureWorks2012AdventureWorks2012 vengono eliminate in base alle vendite da inizio anno archiviate nella tabella SalesPerson
.In both examples, rows from the SalesPersonQuotaHistory
table in the AdventureWorks2012AdventureWorks2012 database are deleted based on the year-to-date sales stored in the SalesPerson
table. La prima istruzione DELETE
illustra la soluzione di sottoquery compatibile con ISO, mentre la seconda istruzione DELETE
illustra l'estensione FROM Transact-SQLTransact-SQL per creare un join tra le due tabelle.The first DELETE
statement shows the ISO-compatible subquery solution, and the second DELETE
statement shows the Transact-SQLTransact-SQL FROM extension to join the two tables.
-- SQL-2003 Standard subquery
DELETE FROM Sales.SalesPersonQuotaHistory
WHERE BusinessEntityID IN
(SELECT BusinessEntityID
FROM Sales.SalesPerson
WHERE SalesYTD > 2500000.00);
GO
-- Transact-SQL extension
DELETE FROM Sales.SalesPersonQuotaHistory
FROM Sales.SalesPersonQuotaHistory AS spqh
INNER JOIN Sales.SalesPerson AS sp
ON spqh.BusinessEntityID = sp.BusinessEntityID
WHERE sp.SalesYTD > 2500000.00;
GO
-- No need to mention target table more than once.
DELETE spqh
FROM
Sales.SalesPersonQuotaHistory AS spqh
INNER JOIN Sales.SalesPerson AS sp
ON spqh.BusinessEntityID = sp.BusinessEntityID
WHERE sp.SalesYTD > 2500000.00;
E.E. Utilizzo di TOP per limitare il numero di righe eliminateUsing TOP to limit the number of rows deleted
Quando si usa una clausola TOP (n) con l'istruzione DELETE, l'operazione di eliminazione viene eseguita su una selezione casuale di un numero di righe n.When a TOP (n) clause is used with DELETE, the delete operation is performed on a random selection of n number of rows. Nell'esempio seguente vengono eliminate 20
righe casuali della tabella PurchaseOrderDetail
del database AdventureWorks2012AdventureWorks2012 che contengono date di scadenza precedenti alla data 1 luglio 2006.The following example deletes 20
random rows from the PurchaseOrderDetail
table in the AdventureWorks2012AdventureWorks2012 database that have due dates that are earlier than July 1, 2006.
DELETE TOP (20)
FROM Purchasing.PurchaseOrderDetail
WHERE DueDate < '20020701';
GO
Se è necessario utilizzare TOP per eliminare le righe in un ordine cronologico significativo, è necessario utilizzare TOP insieme a ORDER BY in un'istruzione subselect.If you have to use TOP to delete rows in a meaningful chronological order, you must use TOP together with ORDER BY in a subselect statement. Tramite la query seguente vengono eliminate le 10 righe della tabella PurchaseOrderDetail
contenenti le date di scadenza più imminenti.The following query deletes the 10 rows of the PurchaseOrderDetail
table that have the earliest due dates. Per assicurarsi che vengano eliminate solo 10 righe, la colonna specificata nell'istruzione di selezione secondaria (PurchaseOrderID
) è la chiave primaria della tabella.To ensure that only 10 rows are deleted, the column specified in the subselect statement (PurchaseOrderID
) is the primary key of the table. L'utilizzo di una colonna non chiave nell'istruzione sub-SELECT può avere come conseguenza l'eliminazione di più di 10 righe se la colonna specificata contiene valori duplicati.Using a nonkey column in the subselect statement may result in the deletion of more than 10 rows if the specified column contains duplicate values.
DELETE FROM Purchasing.PurchaseOrderDetail
WHERE PurchaseOrderDetailID IN
(SELECT TOP 10 PurchaseOrderDetailID
FROM Purchasing.PurchaseOrderDetail
ORDER BY DueDate ASC);
GO
Eliminazione di righe da una tabella remotaDeleting Rows From a Remote Table
Negli esempi riportati in questa sezione viene illustrato come eliminare righe da una tabella remota tramite un server collegato o una funzione per i set di righe per fare riferimento alla tabella remota.Examples in this section demonstrate how to delete rows from a remote table by using a linked server or a rowset function to reference the remote table. Esiste una tabella remota in un server diverso o un'istanza di SQL Server.A remote table exists on a different server or instance of SQL Server.
Si applica a: SQL Server 2008SQL Server 2008 e versioni successive.Applies to: SQL Server 2008SQL Server 2008 and later.
F.F. Eliminazione di dati da una tabella remota tramite un server collegatoDeleting data from a remote table by using a linked server
Nell'esempio seguente vengono eliminate righe da una tabella remota.The following example deletes rows from a remote table. L'esempio inizia con la creazione di un collegamento all'origine dati remota tramite sp_addlinkedserver.The example begins by creating a link to the remote data source by using sp_addlinkedserver. Il nome del server collegato, MyLinkServer
, viene specificato come parte del nome di oggetto in quattro parti nel formato server.catalogo.schema.oggetto.The linked server name, MyLinkServer
, is then specified as part of the four-part object name in the form server.catalog.schema.object.
USE master;
GO
-- Create a link to the remote data source.
-- Specify a valid server name for @datasrc as 'server_name' or 'server_name\instance_name'.
EXEC sp_addlinkedserver @server = N'MyLinkServer',
@srvproduct = N' ',
@provider = N'SQLNCLI',
@datasrc = N'server_name',
@catalog = N'AdventureWorks2012';
GO
-- Specify the remote data source using a four-part name
-- in the form linked_server.catalog.schema.object.
DELETE MyLinkServer.AdventureWorks2012.HumanResources.Department
WHERE DepartmentID > 16;
GO
G.G. Eliminazione di dati da una tabella remota tramite una funzione OPENQUERYDeleting data from a remote table by using the OPENQUERY function
Nell'esempio seguente vengono eliminate righe da una tabella remota specificando la funzione per i set di righe OPENQUERY.The following example deletes rows from a remote table by specifying the OPENQUERY rowset function. Viene utilizzato il nome del server collegato creato nell'esempio precedente.The linked server name created in the previous example is used in this example.
DELETE OPENQUERY (MyLinkServer, 'SELECT Name, GroupName
FROM AdventureWorks2012.HumanResources.Department
WHERE DepartmentID = 18');
GO
H.H. Eliminazione di dati da una tabella remota tramite una funzione OPENDATASOURCEDeleting data from a remote table by using the OPENDATASOURCE function
Nell'esempio seguente vengono eliminate righe da una tabella remota specificando la funzione per i set di righe OPENDATASOURCE.The following example deletes rows from a remote table by specifying the OPENDATASOURCE rowset function. Specificare un nome server valido per l'origine dati usando il formato nome_server oppure nome_server\nome_istanza.Specify a valid server name for the data source by using the format server_name or server_name\instance_name.
DELETE FROM OPENDATASOURCE('SQLNCLI',
'Data Source= <server_name>; Integrated Security=SSPI')
.AdventureWorks2012.HumanResources.Department
WHERE DepartmentID = 17;
Acquisizione dei risultati dell'istruzione DELETECapturing the results of the DELETE statement
I.I. Utilizzo di DELETE con la clausola OUTPUTUsing DELETE with the OUTPUT clause
Nell'esempio seguente viene illustrato come salvare i risultati di un'istruzione DELETE
in una variabile di tabella nel database AdventureWorks2012AdventureWorks2012.The following example shows how to save the results of a DELETE
statement to a table variable in the AdventureWorks2012AdventureWorks2012 database.
DELETE Sales.ShoppingCartItem
OUTPUT DELETED.*
WHERE ShoppingCartID = 20621;
--Verify the rows in the table matching the WHERE clause have been deleted.
SELECT COUNT(*) AS [Rows in Table]
FROM Sales.ShoppingCartItem
WHERE ShoppingCartID = 20621;
GO
J.J. Uso di OUTPUT con <from_table_name> in un'istruzione DELETEUsing OUTPUT with <from_table_name> in a DELETE statement
Nell'esempio seguente vengono eliminate alcune righe della tabella ProductProductPhoto
del database AdventureWorks2012AdventureWorks2012 in base ai criteri di ricerca definiti nella clausola FROM
dell'istruzione DELETE
.The following example deletes rows in the ProductProductPhoto
table in the AdventureWorks2012AdventureWorks2012 database based on search criteria defined in the FROM
clause of the DELETE
statement. La clausola OUTPUT
restituisce le colonne della tabella che si desidera eliminare, DELETED.ProductID
, DELETED.ProductPhotoID
e alcune colonne della tabella Product
.The OUTPUT
clause returns columns from the table being deleted, DELETED.ProductID
, DELETED.ProductPhotoID
, and columns from the Product
table. Queste informazioni vengono utilizzate nella clausola FROM
per specificare le righe da eliminare.This is used in the FROM
clause to specify the rows to delete.
DECLARE @MyTableVar table (
ProductID int NOT NULL,
ProductName nvarchar(50)NOT NULL,
ProductModelID int NOT NULL,
PhotoID int NOT NULL);
DELETE Production.ProductProductPhoto
OUTPUT DELETED.ProductID,
p.Name,
p.ProductModelID,
DELETED.ProductPhotoID
INTO @MyTableVar
FROM Production.ProductProductPhoto AS ph
JOIN Production.Product as p
ON ph.ProductID = p.ProductID
WHERE p.ProductModelID BETWEEN 120 and 130;
--Display the results of the table variable.
SELECT ProductID, ProductName, ProductModelID, PhotoID
FROM @MyTableVar
ORDER BY ProductModelID;
GO
Esempi: Azure Synapse AnalyticsAzure Synapse Analytics e Parallel Data WarehouseParallel Data WarehouseExamples: Azure Synapse AnalyticsAzure Synapse Analytics and Parallel Data WarehouseParallel Data Warehouse
K.K. Eliminare tutte le righe di una tabellaDelete all rows from a table
Nell'esempio seguente vengono eliminate tutte le righe dalla tabella Table1
perché non viene utilizzata una clausola WHERE per limitare il numero di righe eliminate.The following example deletes all rows from the Table1
table because a WHERE clause is not used to limit the number of rows deleted.
DELETE FROM Table1;
L.L. Eliminare un set di righe di una tabellaDELETE a set of rows from a table
Nell'esempio seguente vengono eliminate dalla tabella Table1
tutte le righe in cui il valore della colonna StandardCost
è maggiore di 1000,00.The following example deletes all rows from the Table1
table that have a value greater than 1000.00 in the StandardCost
column.
DELETE FROM Table1
WHERE StandardCost > 1000.00;
M.M. Uso di LABEL con un'istruzione DELETEUsing LABEL with a DELETE statement
Nell'esempio seguente viene usata un'etichetta con l'istruzione DELETE.The following example uses a label with the DELETE statement.
DELETE FROM Table1
OPTION ( LABEL = N'label1' );
N.N. Uso di un'etichetta e di un hint per la query con l'istruzione DELETEUsing a label and a query hint with the DELETE statement
Questa query illustra la sintassi di base per l'uso di un hint di join per la query con l'istruzione DELETE.This query shows the basic syntax for using a query join hint with the DELETE statement. Per altre informazioni sugli hint di join e su come usare la clausola OPTION, vedere Clausola OPTION (Transact-SQL).For more information on join hints and how to use the OPTION clause, see OPTION Clause (Transact-SQL).
-- Uses AdventureWorks
DELETE FROM dbo.FactInternetSales
WHERE ProductKey IN (
SELECT T1.ProductKey FROM dbo.DimProduct T1
JOIN dbo.DimProductSubcategory T2
ON T1.ProductSubcategoryKey = T2.ProductSubcategoryKey
WHERE T2.EnglishProductSubcategoryName = 'Road Bikes' )
OPTION ( LABEL = N'CustomJoin', HASH JOIN ) ;
O.O. Eliminare usando una clausola WHEREDelete using a WHERE clause
Questa query mostra come eliminare usando la clausola WHERE e non una clausola FROM.This query shows how to delete using a WHERE clause and not using a FROM clause.
DELETE tableA WHERE EXISTS (
SELECT TOP 1 1 FROM tableB tb WHERE tb.col1 = tableA.col1
)
P.P. Eliminare in base al risultato del join con un'altra tabellaDelete based on the result of joining with another table
Questo esempio illustra come eseguire un'eliminazione da una tabella in base al risultato del join con un'altra tabella.This example shows how to delete from a table based on the result from joining wiht another table.
CREATE TABLE dbo.Table1
(ColA int NOT NULL, ColB decimal(10,3) NOT NULL);
GO
CREATE TABLE dbo.Table2
(ColA int PRIMARY KEY NOT NULL, ColB decimal(10,3) NOT NULL);
GO
INSERT INTO dbo.Table1 VALUES(1, 10.0), (1, 20.0);
INSERT INTO dbo.Table2 VALUES(1, 0.0);
GO
DELETE dbo.Table2
FROM dbo.Table2
INNER JOIN dbo.Table1
ON (dbo.Table2.ColA = dbo.Table1.ColA)
WHERE dboTable2.ColA = 1;
Vedere ancheSee Also
CREATE TRIGGER (Transact-SQL) CREATE TRIGGER (Transact-SQL)
INSERT (Transact-SQL) INSERT (Transact-SQL)
SELECT (Transact-SQL) SELECT (Transact-SQL)
TRUNCATE TABLE (Transact-SQL) TRUNCATE TABLE (Transact-SQL)
UPDATE (Transact-SQL) UPDATE (Transact-SQL)
WITH common_table_expression (Transact-SQL) WITH common_table_expression (Transact-SQL)
@@ROWCOUNT (Transact-SQL)@@ROWCOUNT (Transact-SQL)