【问题标题】:SQL Server 2008 - excluding rowsSQL Server 2008 - 不包括行
【发布时间】:2009-09-20 10:53:39
【问题描述】:

我有以下问题

声明@ProductIdsToExclude nvarchar(max)

SET @ProductIdsToExclude = '49506541-4CE2-40AC-812A-7AB262E6F0B0,49506541-4ce2-40ac-812a-7ab262e6f0b0'

然后我使用this 函数将@ProductIdsToExclude 解析为临时表:

创建表

#TempProductIdsToExclude (ProductId 唯一标识符)

插入

#TempProductIdsToExclude (ProductId)

选择

t.txt_value

来自

dbo.fn_ParseText2Table(@ProductIdsToExclude,',') as t

然后我使用这个查询来提取所有产品

从产品中选择 *

我的问题是 - 如何让查询 排除 Products 表中的 ProductId 包含在 中的所有结果>#TempProductIdsToExclude

谢谢!

【问题讨论】:

    标签: sql sql-server-2008


    【解决方案1】:

    使用where not exists:

    select *
      from Products prod with (nolock)
     where not exists (select 1
                         from #TempProductIdsToExclude temp
                        where temp.ProductId = prod.ProductId)
    

    【讨论】:

    • 出于好奇,为什么要使用“with (nolock)”?
    • 默认情况下,整个Products 表将在select 运行时被锁定,即没有其他查询可以访问它。 with (nolock) 禁用此锁定以允许并发访问 - 缺点是如果在 select 运行时更改表数据,结果可能与您的预期不同。
    【解决方案2】:

    你可以使用:

    select * from products where productId not in (select productId from ) #TempProductIdsToExclude)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      相关资源
      最近更新 更多