我遇到了T-SQL问题。我是T-SQL的初学者。
我有一个朋友条目数据库。一列包含MemberA_ID,它是一对朋友中朋友的成员ID之一的整数ID。另一列包含MemberB_ID,它是一对朋友中另一位朋友的成员ID的整数ID。
因此,如果Mary的ID为1且John的ID为2,并且他们是朋友,那么Friends表中的一行将包含1和2(以及其他数据)。
我正在尝试编写一个T-SQL存储过程,该过程接收成员ID作为输入,并为该成员的所有朋友检索其memberID和用户名(用户名存储在名为MemberProfiles的另一个表中)。 / p>
我正在尝试此代码,但它未被接受。
ALTER PROCEDURE dbo.GetFriends (@ownMemberID [int])
AS
DECLARE @localFriendID_A AS INTEGER
DECLARE @localFriendID_B AS INTEGER
IF EXISTS
(
SELECT @localFriendID_B = MemberB_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberA_ID = @ownMemberID)
)
BEGIN
SELECT MemberID, VisibleUsername
FROM MemberProfiles
WHERE (MemberID = @localFriendID_B)
END
ELSE IF EXISTS
(
SELECT @localFriendID_A = MemberA_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberB_ID = @ownMemberID)
)
BEGIN
SELECT MemberID, VisibleUsername
FROM MemberProfiles
WHERE (MemberID = @localFriendID_A)
END
RETURN
答案 0 :(得分:1)
上面代码的唯一问题是,你在检查是否存在行时尝试初始化...
你必须编写如下的TSQL
ALTER PROCEDURE dbo.GetFriends (@ownMemberID [int])
AS
DECLARE @localFriendID_A AS INTEGER
DECLARE @localFriendID_B AS INTEGER
SET @localFriendID_A = 0
SET @localFriendID_B = 0
SELECT @localFriendID_B = MemberB_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberA_ID = @ownMemberID)
SELECT @localFriendID_A = MemberA_ID
FROM Friends
WHERE (StartDate IS NOT NULL) AND (EndDate IS NULL)
AND (RequestRejectDate IS NULL) AND (MemberB_ID = @ownMemberID)
IF ( @localFriendID_B <> 0 )
BEGIN
SELECT MemberID, VisibleUsername
FROM MemberProfiles
WHERE (MemberID = @localFriendID_B)
END
ELSE IF (@localFriendID_A <> 0 )
BEGIN
SELECT MemberID, VisibleUsername
FROM MemberProfiles
WHERE (MemberID = @localFriendID_A)
END
RETURN