如何获取除主键之外的相同值的记录

时间:2011-03-24 19:52:42

标签: sql-server sql-server-2005 sql-server-2008 sql

假设数据库中的记录如下:

Id         FirstName       LastName        OrderPrice
1          Tom             Hanks           123
2          Tom             Hanks           173
3          Tom             Hanks           123
4          Tom             Bob             123
5          Robert          Hanks           123

Given Input : Id = 1
Expected OUtput : Id = 3

我知道我可以写下面的内容

Declare @Id as INT = 1
Declare @FirstName as varchar(100)
Declare @LastName as varchar(100)
Declare @OrderPrice as INT

Select @FirstName = FirstName, @LastName  = LastName , @OrderPrice = OrderPrice  From Customers Where Id= @ID

Select ID From Customers Where FirstName = @FirstName and LastName = @LastName and OrderPrice = @OrderPrice

但是,我不想写一些像我应该在where where条件中提到所有列名称的东西。因为实际上我正在处理的记录中包含了近100列。所以,我被要求不要使用这样的查询。

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

您可以使用动态SQL创建查询以搜索重复记录。基本上,此查询构建一个类似a.col1 = b.col1 and a.col2 = b.col2 and ...的字符串,并将其用作自联接中的on子句:

declare @columns varchar(max)

select  @columns = 
            case when @columns is null then 'a.' else @columns + ' and a.' end +
            quotename(name) + ' = b.' + quotename(name)
from    sys.columns
where   object_id = object_id('YourTable')
        and name <> 'ID'

declare @query varchar(max)
set @query = 'select b.ID from YourTable a ' +
    'join YourTable b on a.ID <> b.ID and ' + @columns + ' where a.ID = 1'
exec (@query)

这将搜索重复ID = 1的行,ID除外。

答案 1 :(得分:0)

Declare @Id as INT = 1

WITH
    dupes AS
    (
        SELECT
C1.Id,
            C1.FirstName,
            C1.LastName,
            C1.OrderPrice
        FROM
            Customers C1
        LEFT OUTER JOIN Customers C2
        ON
            C1.FirstName = C2.FirstName
        AND C1.LastName = C2.LastName
        AND C1.OrderPrice = C2.OrderPrice
        WHERE
            C1.Id <> C2.Id
    )
SELECT
    dupes.Id
FROM
    Customer
INNER JOIN dupes
ON
    Customer.FirstName = dupes.FirstName
AND Customer.LastName = dupes.LastName
AND Customer.OrderPrice = dupes.OrderPrice
WHERE
   Customer.Id = @Id
AND dupes.Id <> @Id