Pages

Search This Blog

Showing posts with label delete. Show all posts
Showing posts with label delete. Show all posts

Saturday, August 25, 2012

[T-SQL] DELETE, TRUNCATE and RESEED Identity

Create a temp table with Identity column beginning with value 11. The seed value is 11.
USE [TempDB]
GO
-- Create TableCREATE TABLE [dbo].[TestTable]([ID] [int] IDENTITY(11,1) NOT NULL,[var] [nchar](10) NULL
)
ON [PRIMARY]
GO
-- Build sample dataINSERT INTO [TestTable]VALUES ('val')GO

When seed value is 11 the next value which is inserted has the identity column value as 11.
– Select Data
SELECT *FROM [TestTable]
GO


Effect of DELETE statement

-- Delete DataDELETE FROM [TestTable]
GO

When the DELETE statement is executed without WHERE clause it will delete all the rows. However, when a new record is inserted the identity value is increased from 11 to 12. It does not reset but keep on increasing.
-- Build sample dataINSERT INTO [TestTable]VALUES ('val')GO-- Select DataSELECT *FROM [TestTable]

Effect of TRUNCATE statement

-- Truncate tableTRUNCATE TABLE [TestTable]
GO

When the TRUNCATE statement is executed it will remove all the rows. However, when a new record is inserted the identity value is increased from 11 (which is original value). TRUNCATE resets the identity value to the original seed value of the table.
-- Build sample dataINSERT INTO [TestTable]VALUES ('val')GO-- Select DataSELECT *FROM [TestTable]
GO

Effect of RESEED statement

If you notice I am using the reseed value as 1. The original seed value when I created table is 11. However, I am reseeding it with value 1.
-- ReseedDBCC CHECKIDENT ('TestTable', RESEED, 1)GO
When we insert the one more value and check the value it will generate the new value as 2. This new value logic is Reseed Value + Interval Value – in this case it will be 1+1 = 2.
-- Build sample dataINSERT INTO [TestTable]VALUES ('val')GO-- Select DataSELECT *FROM [TestTable]
GO

Here is the clean up act.
-- Clean upDROP TABLE [TestTable]
GO

Tuesday, January 4, 2011

[T-SQL] Delete vs Truncate

Here is good comparision between delete and truncate

DELETE:

  • DELETE supports a WHERE clause
  • DELETE removes rows from a table, row-by-row
  • Because DELETE moves row-by-row, it acquires a row-level lock
  • Depending upon the recovery model of the database, DELETE is a fully-logged operation.
  • Because DELETE moves row-by-row, it can fire off triggers

TRUNCATE:

  • TRUNCATE does not support a WHERE clause
  • TRUNCATE works by directly removing the individual data pages of a table
  • TRUNCATE directly occupies a table-level lock.
  • (Because a lock is acquired, and because TRUNCATE can also participate in a transaction, it has to be a logged operation)
  • TRUNCATE is, therefore, a minimally-logged operation; again, this depends upon the recovery model of the database
  • Triggers are not fired when TRUNCATE is used (because individual row deletions are not logged)

Monday, November 8, 2010

[T-SQL] Delete duplicate without ID

Here is a query by which you can delete duplicate rows without using identity column

/* Delete Duplicate records */
WITH CTE (COl1,Col2, DuplicateCount)
AS
(
SELECT COl1,Col2,
ROW_NUMBER() OVER(PARTITION BY COl1,Col2 ORDER BY Col1) AS DuplicateCount
FROM DuplicateRcordTable
)
DELETE
FROM CTE
WHERE DuplicateCount > 1
GO

Wednesday, October 13, 2010

[T-SQL] How to remove duplicate data

One of the very common question that is asked many times , tell the way how can we delete the duplicate data or an easiest way or fastest way.

This method has one limitation that the table should have a primary key.

DELETE
FROM TableName
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM TableName
GROUP BY Col1, Col2, Col3)

*TableName should be replaced with Table Name
*Col1 , Col2 and Col3 must be replaced with the criteria on which records will qualify as duplicate. It can be increase and decrease.

Thursday, September 23, 2010

[T-SQL] Generate Delete script for all tables

You can use this script for generate delete script or even trncate

select 'delete from ' + o.name + ';'
from sysobjects o
where o.type = 'U';

Wednesday, September 22, 2010

[T-SQL] Delete all data in database (when you have FKs)

SET NOCOUNT ON
GO

SELECT 'USE [' + db_name() +']';

SELECT 'ALTER TABLE ' +
'[' + s.name + '].[' + t.name + ']' +
' DROP CONSTRAINT [' + f.name +']'
FROM sys.foreign_keys f
INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0;


SELECT 'TRUNCATE TABLE ' + '[' + s.name + '].[' + t.name + ']'
FROM sys.TABLES t
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0;


SELECT 'ALTER TABLE ' +
'[' + s.name + '].[' + t.name + ']' +
' ADD CONSTRAINT [' + f.name + ']' +
' FOREIGN KEY (' +
Stuff( (SELECT ', ['+col_name(fk.parent_object_id, fk.parent_column_id) +']'
FROM sys.foreign_key_columns fk
WHERE constraint_object_id = f.object_id
ORDER BY constraint_column_id
FOR XML Path('')
), 1,2,'') + ')' +
' REFERENCES [' +
object_schema_name(f.referenced_object_id)+'].['+object_name(f.referenced_object_id) + '] (' +
Stuff((SELECT ', ['+col_name(fc.referenced_object_id, fc.referenced_column_id)+']'
FROM sys.foreign_key_columns fc
WHERE constraint_object_id = f.object_id
ORDER BY constraint_column_id
FOR XML Path('')),
1,2,'') +
')' +
' ON DELETE ' + REPLACE(f.delete_referential_action_desc, '_', ' ') +
' ON UPDATE ' + REPLACE(f.update_referential_action_desc , '_', ' ') collate database_default
FROM sys.foreign_keys f
INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
WHERE t.is_ms_shipped=0;

Monday, September 20, 2010

[T-SQL] Find Auto Created Stats and Delete query for them

Query for getting them:

SELECT name, OBJECT_NAME(OBJECT_ID)
FROM sys.stats
WHERE auto_created = 1;

Delete query for one of the table stats:

DROP STATISTICS TableName.StatisticsName

Thursday, August 5, 2010

[T-SQL] Merge Operator

Let us run the same example which I have used earlier; I am listing the same here again for convenience.

--Let’s create Student Details and StudentTotalMarks and inserted some records.
USE tempdb
GO
CREATE TABLE StudentDetails
(
StudentID INTEGER PRIMARY KEY,
StudentName VARCHAR(15)
)
GO
INSERT INTO StudentDetails
VALUES(1,'SMITH')
INSERT INTO StudentDetails
VALUES(2,'ALLEN')
INSERT INTO StudentDetails
VALUES(3,'JONES')
INSERT INTO StudentDetails
VALUES(4,'MARTIN')
INSERT INTO StudentDetails
VALUES(5,'JAMES')
GO
CREATE TABLE StudentTotalMarks
(
StudentID INTEGER REFERENCES StudentDetails,
StudentMarks INTEGER
)
GO
INSERT INTO StudentTotalMarks
VALUES(1,230)
INSERT INTO StudentTotalMarks
VALUES(2,255)
INSERT INTO StudentTotalMarks
VALUES(3,200)
GO
-- Select from Table
SELECT *
FROM StudentDetails
GO
SELECT *
FROM StudentTotalMarks
GO
-- Merge Statement
MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);
GO
-- Select from Table
SELECT *
FROM StudentDetails
GO
SELECT *
FROM StudentTotalMarks
GO
-- Clean up
DROP TABLE StudentDetails
GO
DROP TABLE StudentTotalMarks
GO

Monday, July 19, 2010

[T-Sql] Deleting Duplicate Records

Deleting Duplciate Records on any specific crieteria


DECLARE @DATE AS VARCHAR(19)
SET @DATE=(SELECT CONVERT(VARCHAR(19),ISNULL(MAX(TIMEMODIFIED),'01/01/2000'),121) FROM ACDW.DBO.QB_SALESREP)

INSERT INTO QB_SALESREP SELECT * FROM QB_SALESREP_TEMP WHERE TIMEMODIFIED>@DATE

DELETE ACDW.DBO.QB_SALESREP
FROM ACDW.DBO.QB_SALESREP TSR INNER JOIN
(
SELECT LISTID,MIN(TIMEMODIFIED) TIMEMODIFIED
FROM ACDW.DBO.QB_SALESREP
GROUP BY LISTID
HAVING COUNT(*)>1
) DD ON TSR.LISTID=DD.LISTID AND TSR.TIMEMODIFIED=DD.TIMEMODIFIED