--Create Temp Table
IF OBJECT_ID('ABC') IS NOT NULL
DROP TABLE 'ABC'
GO
CREATE TABLE [dbo].[ABC]
(
[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ABC_ID] DEFAULT (newid()),
[FullName] [nchar](10) NOT NULL,
CONSTRAINT [PK_ABC] PRIMARY KEY CLUSTERED ( [ID] ASC )ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO ABC VALUES ( NEWID(), 'New1')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New3')
INSERT INTO ABC VALUES ( NEWID(), 'New3')
-- This code will select the Duplicate row only and keep single copy from row
SELECT [ID], [FullName], [RowIndex]
FROM
(
SELECT
[ID], [FullName], RANK() OVER (PARTITION BY [FullName]
ORDER BY [ID] ASC) AS [RowIndex]
FROM [dbo].[ABC]
)[A]
WHERE [A].[RowIndex] > 1
GO
-- If replace SELECT SQL command with DELETE SQL command
DELETE FROM [dbo].[ABC] WHERE [ID] IN
(
SELECT [ID] FROM
(
SELECT
[ID], [FullName],
RANK() OVER (PARTITION BY [FullName] ORDER BY [ID] ASC) AS [RowIndex]
FROM [dbo].[ABC]
)[A] WHERE [A].[RowIndex] > 1
)
GO
IF OBJECT_ID('ABC') IS NOT NULL
DROP TABLE 'ABC'
GO
CREATE TABLE [dbo].[ABC]
(
[ID] [uniqueidentifier] NOT NULL CONSTRAINT [DF_ABC_ID] DEFAULT (newid()),
[FullName] [nchar](10) NOT NULL,
CONSTRAINT [PK_ABC] PRIMARY KEY CLUSTERED ( [ID] ASC )ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT INTO ABC VALUES ( NEWID(), 'New1')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New2')
INSERT INTO ABC VALUES ( NEWID(), 'New3')
INSERT INTO ABC VALUES ( NEWID(), 'New3')
-- This code will select the Duplicate row only and keep single copy from row
SELECT [ID], [FullName], [RowIndex]
FROM
(
SELECT
[ID], [FullName], RANK() OVER (PARTITION BY [FullName]
ORDER BY [ID] ASC) AS [RowIndex]
FROM [dbo].[ABC]
)[A]
WHERE [A].[RowIndex] > 1
GO
-- If replace SELECT SQL command with DELETE SQL command
DELETE FROM [dbo].[ABC] WHERE [ID] IN
(
SELECT [ID] FROM
(
SELECT
[ID], [FullName],
RANK() OVER (PARTITION BY [FullName] ORDER BY [ID] ASC) AS [RowIndex]
FROM [dbo].[ABC]
)[A] WHERE [A].[RowIndex] > 1
)
GO
No comments:
Post a Comment