我有一个以下形式的简单数据库:
Users{
UserID (PK)
Username
Email
FirstName
SecondName
}
Groups{
GroupID (PK)
GroupName
}
Membership{
UserID (FK)
GroupID (FK)
}
成员资格是其他两个表的“中间人”。当用户注册时,他们的用户名将插入到“用户和组”表中(自己创建一个组)。 UserID和GroupID应引用Users
和Groups
中的相应列。
当用户注册时,这是使用三个INSERT INTO语句执行此操作的最佳方法,如下所示:
if (db.Execute("INSERT INTO Users(Username, Email, FirstName, SecondName) VALUES(@0,@1,@2,@3)", username, email, firstName, secondName) < 1
|| db.Execute("INSERT INTO Groups(GroupName) VALUES(@0)", username) < 1
|| db.Execute("INSERT INTO Membership(UserID, GroupID) VALUES(@0, @1)",?????????????) < 1)
{
<p class="error">Wasn't able to insert User record</p>//insert failed
}else {
Response.Redirect("Success.cshtml"); //success
}
我应该在第三个INSERT INTO语句中添加什么内容才能正确插入userID和相应的groupID?
答案 0 :(得分:2)
这是数据库逻辑......把它放在数据库中。
CREATE PROCEDURE dbo.AddUserAndGroup
@username NVARCHAR(255),
@email VARCHAR(320),
@firstname NVARCHAR(32),
@secondName NVARCHAR(32)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @UserID INT, @GroupID INT;
INSERT dbo.Users(Username, Email, FirstName, SecondName)
SELECT @username, @email, @firstname, @secondname;
SELECT @UserID = SCOPE_IDENTITY();
-- could probably simply rest with OUTPUT, just keeping it simple/consistent
INSERT dbo.Groups(GroupName) SELECT @username;
SELECT @GroupID = SCOPE_IDENTITY();
INSERT dbo.Membership(UserID, GroupID) SELECT @UserID, @GroupID;
END
GO
现在你应该可以说出这样的话(请原谅我,如果我没有正确的客户端语法,但我正试图接近):
if (db.Execute("EXEC dbo.AddUserAndGroup @0,@1,@2,@3;",
username, email, firstName, secondName) < 1
{
<p class="error">Wasn't able to insert User record</p>//insert failed
}
else
{
Response.Redirect("Success.cshtml"); //success
}