0

I have 2 tables. TableA has columns OldLogin and NewLogin. TableB has ID, IsManager, and CanChange.

I'm writing a stored procedure with an input parameter login. It needs ultimately return all columns in TableB where login = ID but it first needs to check TableA to see if it needs to use NewLogin.

So, can someone help me write a query that says "show me all columns in TableB where ID = (login OR NewLogin)"?

Thanks!

EDIT: Added code:

DECLARE @login varchar(30) = 'test'

SELECT ISNULL(NewLogin, @login) AS NewLogin, TableB .IsManager, TableB.CanChange
FROM TableA
LEFT JOIN TableB ON TableB.ID = ISNULL(NewLogin, @login)
WHERE OldLogin = @login

THe above code works only if @login exists in TableA. I get no results if it doesn't exist in that table.

4

3 回答 3

0

如果 a 为空,则使用 IFNULL(a,b) 返回 b。

编辑:我假设 mysql,不确定它是否适用于其他语言。您也可以使用 COALESCE,它接受任意数量的参数并返回第一个非空参数。

DECLARE @login varchar(30) = 'test'

SELECT IFNULL(TableA.NewLogin, @login) AS NewLogin, TableB.IsManager, TableB.CanChange
FROM TableA
LEFT JOIN TableB ON 
  TableB.ID = IFNULL(TableA.NewLogin, @login)
WHERE OldLogin = @login
于 2012-11-08T20:31:20.443 回答
0
DECLARE @login varchar(30) = 'test'
SELECT DISTINCT TableB.*
FROM TableA
  INNER JOIN TableB ON TableB.ID = NewLogin OR TableB.ID = @login
于 2012-11-09T10:33:47.513 回答
0

if I'm understanding that correctly...

SELECT TableB.*
FROM TableB
LEFT JOIN TableA ON TableB.id IN (TableA.OldLogin, TableB.NewLogin)

?

于 2012-11-08T20:16:20.103 回答