0

我在 Google 中找不到答案,因为我不知道关键字...所以这是我的查询

SELECT col1 
from table1
WHERE col2 in (select col2 from table2 where user_id=@ID)

我想知道是否可以放置 if 条件语句...如果 table2 为空,那么我会改为使用此条件

select col1 from table1 <no condition>

就像select col2 from table2 where user_id=@id is null它会提取所有数据一样

有人能帮我吗?

4

2 回答 2

1
SELECT table1.col1 
FROM table1 LEFT OUTER JOIN table2 ON table1.col2 = table1.col2 AND table2.user_id = @ID
于 2013-01-18T08:44:16.060 回答
0
DECLARE @sql VARCHAR(500)

SET @sql = 'SELECT col1 from table1'
IF((select col2 from table2 where user_id=@ID )IS NOT NULL) 
BEGIN
    SET @sql = @sql + ' WHERE col2 in (select col2 from table2 where user_id= ' + CAST(@ID AS VARCHAR) + ' )'
END
EXEC (@sql)

您可以根据您的要求对这种情况使用动态查询

于 2013-01-18T08:55:10.553 回答