HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlModerate

Truncate with where clause

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
withtruncatewhereclause

Problem

Can I use truncate command with a where clause? I need to remove specific rows from several tables.

How can I delete specific data from the entire database?

SELECT DimEmployee.[FirstName], DimEmployee.[LastName], [SalesOrderNumber], [ShipDateKey]
    FROM DimEmployee
    JOIN [FactResellerSales] 
        ON DimEmployee.[EmployeeKey] = [FactResellerSales].[ProductKey] 
    WHERE DimEmployee.[FirstName] like 'kevin%' <--have to truncate this specific name from entire DB


Is there any other method to remove a specific data from entire DB?

In my database there are 172 tables. I wanted to delete a specific name and its corresponding columns from the entire database. The name is spread across entire database, hence I want to remove it in a single shot instead of going to each table and deleting it individually.

Solution

No, Truncate can't be used with a WHERE clause. Truncate simply deallocates all the pages belonging to a table (or a partition) and its indexes.

From BOL:

-- Syntax for SQL Server and Azure SQL Database  

TRUNCATE TABLE   
    [ { database_name .[ schema_name ] . | schema_name . } ]  
    table_name  
    [ WITH ( PARTITIONS ( {  |  }   
    [ , ...n ] ) ) ]  
[ ; ]


If you're looking for a more efficient way to delete data, I'd start here.

Code Snippets

-- Syntax for SQL Server and Azure SQL Database  

TRUNCATE TABLE   
    [ { database_name .[ schema_name ] . | schema_name . } ]  
    table_name  
    [ WITH ( PARTITIONS ( { <partition_number_expression> | <range> }   
    [ , ...n ] ) ) ]  
[ ; ]

Context

StackExchange Database Administrators Q#170849, answer score: 12

Revisions (0)

No revisions yet.