我正在编写一个使用动态sql的存储过程。如果UserGroup为<>
'Initial',我希望能够有条件地添加第一个连接条件。以下不是实际代码,只是为了显示我的问题
SELECT A FROM MyTable
IF UserGroup <> 'Initial THEN
INNER JOIN Table1 ON MyTable.A = Table1.A
END
INNER JOIN Table1 ON MyTable.B = Table1.B
INNER JOIN Table1 ON MyTable.C = Table1.C
答案 0 :(得分:0)
这是一个如何使用外连接获得相同结果的示例:
SELECT A
FROM MyTable
LEFT JOIN Table1 T1
ON (UserGroup <> 'Initial' AND MyTable.A = T1.A)
INNER JOIN Table1 T2 ON MyTable.B = T2.B
INNER JOIN Table1 T3 ON MyTable.C = T3.C
WHERE (UserGroup <> 'Initial' AND T1.A IS NOT NULL) OR UserGroup = 'Initial'
答案 1 :(得分:0)
这样做的正确方法更像是:
select A from MyTable
inner join Table1 on
MyTable.A = case when UserGroup <> 'Initial' then Table1.A else MyTable.A end
or MyTable.B = Table1.B
or MyTable.C = Table1.C
您可以根据需要将实际or
更改为and
。
答案 2 :(得分:0)
您可以使用动态sql
declare @Query varchar(max)
set @Query = ' SELECT A
FROM myTable
'
if (UserGroup <> 'Initial')
Begin
set @Query = @Query +'INNER JOIN Table1 ON MyTable.A = Table1.A'
End
exec(@Query)