i'm trying to execute the following SQL 2008 code it says there is a problem near "=" and "else"... i cant understand what is wrong with the code
ALTER PROCEDURE dbo.LoginEmp @username NVARCHAR(10),
@password NVARCHAR(10),
@confirm INT output,
@emp_name NVARCHAR(50) output,
@emp_id BIGINT output
AS
IF EXISTS (SELECT @emp_id = emp_id,
@emp_name = emp_name_ara
FROM Employee
WHERE ( emp_username LIKE @username
AND emp_password LIKE @password ))
BEGIN
SET @confirm=1
INSERT INTO EmployeeLog
(log_emp_id,
log_act_id,
log_date,
log_data)
VALUES (@emp_id,
1,
GETDATE(),
-1)
END
ELSE
BEGIN
SET @confirm=0
END
RETURN
We can use SQL IF statement without ELSE as well. In the following, the expression evaluates to TRUE; therefore, it prints the message. If the expression evaluates to FALSE, it does not return any output. We should use ELSE statement so that if an evaluation is not TRUE, we can set default output.
If you have used a CTE in your query, this can sometimes be tricky as they cannot be used in a conditional like IF EXISTS (queryWithCTE).
Using @@ERROR to conditionally exit a procedure. The following example uses IF...ELSE statements to test @@ERROR after an DELETE statement in a stored procedure. The value of the @@ERROR variable determines the return code sent to the calling program, indicating success or failure of the procedure.
Syntax. IF (a <= 20) THEN c:= c+1; END IF; If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing end if) will be executed.
Instead of trying to assign to the output parameters inside the EXISTS
do the assignment then check @@rowcount
to see if any matching row(s) were found.
ALTER PROCEDURE dbo.LoginEmp @username NVARCHAR(10),
@password NVARCHAR(10),
@confirm INT output,
@emp_name NVARCHAR(50) output,
@emp_id BIGINT output
AS
SELECT @emp_id = emp_id,
@emp_name = emp_name_ara
FROM Employee
WHERE ( emp_username = @username
AND emp_password = @password )
IF @@ROWCOUNT = 1
BEGIN
SET @confirm=1
INSERT INTO EmployeeLog
(log_emp_id,
log_act_id,
log_date,
log_data)
VALUES (@emp_id,
1,
GETDATE(),
-1)
END
ELSE
BEGIN
SET @confirm=0
END
Exists operator checks if any row present in resultset returned by query. In your example it's just assigning values to variable. For more reference please check this link : Assigning a variable inside an IF EXISTS clause
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With