T-SQL关于内部联接表变量的问题

时间:2010-08-25 08:22:24

标签: tsql

在我的存储过程中,我有一个包含行ID的表变量。这两种情况 - 表变量是空的而不是。

declare @IDTable as table
(
  number NUMERIC(18,0)
)

在主查询中,我加入了该表:

inner join @IDTable tab on (tab.number = csr.id)

BUT:

因为我们知道内部联接如何工作,我需要我的查询返回一些行:

  

当@IDTable为空时

OR

  

返回 ONLY 存在的行   @IDTable

我也尝试使用LEFT加入,但它不起作用。任何想法如何解决?

2 个答案:

答案 0 :(得分:5)

如果`@IDTable'为空,那么你返回哪些行?你是否只是忽略了加入桌面?

我不确定自己能做什么,但这可能会更容易。

if (Select Count(*) From @IDTable) == 0
    begin
    -- do a SELECT that doesn't join on to the @IDTable

     end
else
    begin
    -- do a SELECT that joins on to @IDTable
    end

答案 1 :(得分:2)

这不是最佳的,但它有效:

declare @z table
  (
    id int
  )
  --insert @z values(2)

  select * from  somTable n 
    left join @z z on (z.id = n.id)
  where NOT exists(select 1 from @z) or (z.id is not null)
相关问题