Table1 (ID, Col1, col2, col3, col4)
Table2 (ID, Col5, col6)
-----------------SP-------------------
set @Ids = '1,2,3,4,5,6,7,8,9' // Input paremeter (can be NULL)
Create Table #Tabel2
(
Id int
)
Insert into #table2 select * from dbo.Split(@Ids, ',')
现在#table2
有:1 2 3 4 5 6 7 8 9
方案
Select t1.Col1,t1.col2,t1.col3
FROM Table1 as t1
INNER JOIN Table2 as t2 ON t1.Col1=t2.Col2
AND (@Ids is null OR t1.ID in (Select Id from #Table2))
问题
如何用条件内连接替换IN
?
答案 0 :(得分:0)
因为您使用了从未在查询中定义的别名t
,所以我不清楚哪个表ID
应该加入。我猜了一下并使用了t1
。
Select t1.Col1,t1.col2,t1.col3
FROM Table1 as t1
INNER JOIN Table2 as t2 ON t1.Col1=t2.Col2
left outer join #Table2 ids on @Ids is null or t1.ID = ids.ID --maybe this should be t2.ID = ids.ID?
答案 1 :(得分:0)
除非我误解(毕竟是星期五下午),你想要Table1 / Table2中的所有行,尽可能匹配#Table2,但是如果#Table2为空,那么这只是一个外连接。 / p>
SELECT t.Col1,
t.col2,
t.col3
FROM Table1 AS t1
INNER JOIN Table2 AS t2
ON t1.Col1 = t2.Col2
LEFT OUTER JOIN #Table2 t3
ON t2.ID = t3.ID
答案 2 :(得分:0)
在SQL Server 2008中,您可以在join子句中使用CASE语句,例如:
SELECT *
FROM table1
INNER JOIN table2 ON CASE WHEN table1.column1 = 'this' THEN null ELSE 'that' END = table2.column1