比较SQL Server 2012中同一表中的行。
给定一个表(参见下面的脚本),比较同一个表中的行(单个列)的最佳方法是什么?
实施例
我们正在从客户端导入数据,这可以多次完成,我们应该能够检测列值的差异。
因此,每次我们获取数据并导入数据时,我们都会增加“DataCut”列,然后我应该能够比较数据库之间的差异。
如果您在datacutId 3中的示例数据中注意到Name-Postcode-Homephone已更改。
我如何报告这些差异?任何片段sql或思路?
非常感谢
用于创建测试环境的SQL脚本
IF EXISTS (SELECT * FROM sys.databases WHERE name='TestDatabase')
BEGIN
ALTER DATABASE TestDatabase
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
DROP DATABASE TestDatabase
END
CREATE DATABASE TestDatabase collate Latin1_General_CI_AS
GO
ALTER DATABASE TestDatabase SET RECOVERY SIMPLE
BEGIN TRANSACTION
USE TestDatabase
IF OBJECT_ID(N'[dbo].[Customer]', 'U') IS NOT NULL
DROP TABLE [dbo].[Customer];
GO
CREATE TABLE [dbo].[Customer](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[DataCutId] [int] NOT NULL,
[CustomerId] [int] NOT NULL,
[Name] [varchar](50) NULL,
[Surname] [varchar](50) NULL,
[City] [varchar](255) NULL,
[PostCode] [varchar](10) NULL,
[HomePhone] [varchar](50) NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[Customer] ON;
INSERT INTO [dbo].[Customer]([Id], [DataCutId],CustomerId, [Name], [Surname], [City], [PostCode], [HomePhone])
SELECT 1, 1,20, N'Jo', N'Bloggs', N'London', N'aaa 342', N'0207 3456785' UNION ALL
SELECT 2, 2, 20,N'Jo', N'Bloggs', N'London', N'aaa 342', N'0207 3456785' UNION ALL
SELECT 3, 3, 20,N'Mark', N'Bloggs', N'Londong', N'bbb d4543', N'0208 3456785'
SET IDENTITY_INSERT [dbo].[Customer] OFF;
COMMIT
答案 0 :(得分:0)
这会让您开始解决问题吗?
我相信可能有更简单的方法吗?
Map
编辑我已在下面的单个查询中将所有内容整合在一起
select a.*, b.DataCutId as UpdDataCutID, b.Name as UpdName, b.Surname as UpdSurname, b.City as UpdCity, b.PostCode as UpdPostCode, b.HomePhone as UpdHomePhone
from Customer a inner join Customer b on a.CustomerId = b.CustomerId
and a.Id < b.ID and a.Name <> b.Name
union
select a.*, b.DataCutId, b.Name, b.Surname, b.City, b.PostCode, b.HomePhone
from Customer a inner join Customer b on a.CustomerId = b.CustomerId
and a.Id < b.ID and a.Surname <> b.Surname
union
select a.*, b.DataCutId, b.Name, b.Surname, b.City, b.PostCode, b.HomePhone
from Customer a inner join Customer b on a.CustomerId = b.CustomerId
and a.Id < b.ID and a.City <> b.City
union
select a.*, b.DataCutId, b.Name, b.Surname, b.City, b.PostCode, b.HomePhone
from Customer a inner join Customer b on a.CustomerId = b.CustomerId
and a.Id < b.ID and a.PostCode <> b.PostCode
union
select a.*, b.DataCutId, b.Name, b.Surname, b.City, b.PostCode, b.HomePhone
from Customer a inner join Customer b on a.CustomerId = b.CustomerId
and a.Id < b.ID and a.HomePhone <> b.HomePhone