CREATE PROCEDURE [dbo].[SP_User]
@UserId varchar(50)
,@Username varchar(50)
,@Email varchar(50)
,@Password varchar(50)
,@OperationType int
AS
BEGIN TRAN
IF(@OperationType = 1) --Insert
BEGIN
IF EXISTS(SELECT * FROM [User] WHERE Username=@Username)
BEGIN
ROLLBACK
RAISERROR (N'This username already exist !!!',16,1);
RETURN
END
IF EXISTS(SELECT * FROM [User] WHERE Email=@Email)
BEGIN
ROLLBACK
RAISERROR (N'This email already exist !!!',16,1);
RETURN
END
SET @UserId = (SELECT MAX(UserId) FROM [USER]) + 1
INSERT INTO [USER] (UserId, Username, Email, [Password])
VALUES(@UserId, @Username, @Email, @Password)
SELECT * FROM [USER] WHERE UserId=@UserId
END
ELSE IF(@OperationType = 2) --Update
BEGIN
IF (@UserId = 0)
BEGIN
ROLLBACK
RAISERROR (N'Invalid User !!!',16,1);
RETURN
END
IF EXISTS(SELECT * FROM [User] WHERE Email=@Email AND UserId!=@UserId)
BEGIN
ROLLBACK
RAISERROR (N'This email already exist !!!',16,1);
RETURN
END
UPDATE [USER] SET Username=@Username
,Email=@Email
WHERE UserId=@UserId
SELECT * FROM [USER] WHERE UserId=@UserId
END
ELSE IF(@OperationType = 3) --Delete
BEGIN
IF (@UserId = 0)
BEGIN
ROLLBACK
RAISERROR (N'Invalid User !!!',16,1);
RETURN
END
DELETE FROM [USER] WHERE UserId=@UserId
END
COMMIT TRAN
0 Comments