I’m new to SQL and my first time to create a stored procedure.
I was supposed to insert data and get a return string. The return value should be Successfully inserted or if failed, should notify me if a username already exists.. or something like that however
I’m stuck in codes for error:
So here is my code..
Create Proc Mock_InsertUser
(
@Username varchar(20),
@Password varchar(100),
@fullName varchar(60),
@Activated bit,
@Suspended bit
)
as
Begin
DECLARE
@Error INT,
@rowcount INT,
@log varchar(1000)
IF EXISTS(SELECT username FROM Users_mock WHERE username = @Username)
BEGIN
SET @log = 'Username ' + @Username + ' already exists.'
GOTO ERROR
END
Insert into Users_mock
(username, [password], full_name, Activated, Suspended)
values
(@Username, @Password, @fullName, @Activated, @Suspended)
SELECT @Error = @@ERROR, @rowcount = @@ROWCOUNT
--if there is an error OR If row is not inserted..
IF @Error <> 0 OR @rowcount < 1
BEGIN
SET @log = 'Failed to Insert Account.'
GOTO ERROR
END
-----------------------------------------------------------
Error:
--Some code here
END
Sorry for lousy question 🙂
Why don’t you use something like this:
Points to see:
use
BEGIN TRY/END TRY - BEGIN CATCH/END CATCHlike in C# to handle exceptions – no need to constantly check for@@ERRORvalues ….basically just check for existence of the user – set the
@Logmessage accordingly. If user doesn’t exist, insert it and set@Logmessage to “success”no need for label, GOTO and other stuff like that….