我想在用户表中插入一个新用户(电子邮件地址)。如果成功(无重复),则将新用户的基本配置插入其他表,然后将一些数据返回给客户端。如果未成功,则在c#项目的数据集中收到相关的通知。
这是示例代码,因此您可以轻松对其进行注释
ALTER PROCEDURE [dbo].[CreateUser]
@Email nvarchar(256),
@Password nvarchar(256)
AS
BEGIN
declare @UserID uniqueidentifier;
declare @ConfigID uniqueidentifier;
declare @TopMostNode uniqueidentifier;
BEGIN TRANSACTION;
select @UserID = NEWID();
select @ConfigID = newid();
insert into Users (UserID,Email,Password,CurrentConfig)
values(@UserID, @Email, @Password, @ConfigID);
INSERT INTO Configs (ConfigID, OwnerID, DisplayName, LastPrintID)
VALUES (@ConfigID,@UserID, 'Default Config', 1);
COMMIT TRANSACTION
END
答案 0 :(得分:1)
在一种可能性中,您将返回一个记录集,其中包含所需的数据和一个标志,用于指示用户是否已经存在。
alter procedure [dbo].[CreateUser]
(
@Email nvarchar(256)
, @Password nvarchar(256)
)
as
begin
declare @UserID uniqueidentifier, @ConfigID uniqueidentifier, @TopMostNode uniqueidentifier, @UserExists bit = 0;
select @UserID = UserID, @UserExists = 1 from Users where Email = @Email;
if @UserExists = 0 begin
begin transaction;
set @UserID = newid();
set @ConfigID = newid();
insert into Users (UserID, Email, [Password], CurrentConfig)
values (@UserID, @Email, @Password, @ConfigID);
insert into Configs (ConfigID, OwnerID, DisplayName, LastPrintID)
values (@ConfigID, @UserID, 'Default Config', 1);
commit transaction
end
-- Return whether the user already exists or not and the user id
select @UserExists, @UserId
return 0;
end
将数据返回到应用程序的另一种方法是使用output
参数,例如
alter procedure [dbo].[CreateUser]
(
@Email nvarchar(256)
, @Password nvarchar(256)
, @UserId uniqueidentifier out
, @UserExists bit out
)
as
begin
declare @ConfigID uniqueidentifier, @TopMostNode uniqueidentifier;
set @UserExists = 0;
select @UserID = UserID, @UserExists = 1 from Users where Email = @Email;
if @UserExists = 0 begin
begin transaction;
set @UserID = newid();
set @ConfigID = newid();
insert into Users (UserID, Email, [Password], CurrentConfig)
values (@UserID, @Email, @Password, @ConfigID);
insert into Configs (ConfigID, OwnerID, DisplayName, LastPrintID)
values (@ConfigID, @UserID, 'Default Config', 1);
commit transaction
end
return 0;
end
答案 1 :(得分:1)
该代码几乎完整。只需添加一个SELECT即可返回新键。如果发生错误,您将获得一个例外。 EG:
ALTER PROCEDURE [dbo].[CreateUser]
@Email nvarchar(256),
@Password nvarchar(256)
AS
BEGIN
declare @UserID uniqueidentifier;
declare @ConfigID uniqueidentifier;
declare @TopMostNode uniqueidentifier;
BEGIN TRANSACTION;
select @UserID = NEWID();
select @ConfigID = newid();
insert into Users (UserID,Email,Password,CurrentConfig)
values(@UserID, @Email, @Password, @ConfigID);
INSERT INTO Configs (ConfigID, OwnerID, DisplayName, LastPrintID)
VALUES (@ConfigID,@UserID, 'Default Config', 1);
COMMIT TRANSACTION
select @UserID UserID, @ConfigID ConfigID;
END