sql t-sql else if not working properly - tsql

I have the following short version of a tsql if else if..
IF #var = 1
BEGIN
...
END
ELSE IF #var = 2
BEGIN
....
END
ELSE IF #var = 3
BEGIN
....
END
....
I get a message saying Incorrect syntax near the keyword 'BEGIN' when I use it for the #var = 2 .
not sure if I am doing something wrong

Works just fine, you can't have nothing between begin and end:
declare #var int = 2
IF #var = 1
BEGIN
select 1
END
ELSE IF #var = 2
BEGIN
select 2
END
ELSE IF #var = 3
BEGIN
select 3
END
Result:
2

Related

Incorrect syntax into IF... ELSE clause

I have a really simple query like:
BEGIN TRY
BEGIN TRAN;
DECLARE #CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password]
FROM Employee
WHERE #EmpGuid = EmpGuid)
IF (#Password = #CurrentPassword)
UPDATE [Employee]
SET [Password] = #NewPassword
WHERE #EmpGuid = EmpGuid
SELECT 1;
ELSE
SELECT 2;
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
But I really don't know why in my else clause I get
Incorrect syntax near 'ELSE'
What am I doing wrong? Regards
You you want to have more than one statement after the IF, you must use a BEGIN .... END block - like this:
BEGIN TRY
BEGIN TRAN;
DECLARE #CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password]
FROM Employee
WHERE #EmpGuid = EmpGuid)
IF (#Password = #CurrentPassword)
BEGIN --- you need a *BEGIN* here!!!
UPDATE [Employee]
SET [Password] = #NewPassword
WHERE #EmpGuid = EmpGuid
SELECT 1;
END --- and the *END* for your new *BEGIN*
ELSE
SELECT 2;
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH
Use explicitly begin . . end
BEGIN TRY
BEGIN TRAN
DECLARE #CurrentPassword VARCHAR(255) = (SELECT TOP 1 [Password]
FROM Employee
WHERE #EmpGuid = EmpGuid)
IF (#Password = #CurrentPassword)
BEGIN
UPDATE [Employee]
SET [Password] = #NewPassword
WHERE #EmpGuid = EmpGuid
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
END CATCH

Few errormessager in one raiserrror

I have following problem, I need to display few error messages from my if statements. If, for example, 2 of 3 conditions are met I need to raisevent display 2 messages.
IF #var1 > 1
BEGIN
SET #err = 'ASD'
END
IF #var1 <4
BEGIN
SET #err = 'ZXC'
END
IF #var = 3
BEGIN
SET #err = 'QWE'
END
For #var1 = 2
I need to display 2 errormessages in one raiserror. How can I do this?
Is your code inside BEGIN CACTH block?
How about raising error like this with severity less than 11 that:
IF #var1 > 1
BEGIN
SET #err = 'ASD';
RAISEERROR(#err, <your_severity>, <state>)
END
IF #var1 <4
BEGIN
SET #err = 'ZXC'
RAISEERROR(#err, <your_severity>, <state>)
END
IF #var = 3
BEGIN
SET #err = 'QWE'
RAISEERROR(#err, <your_severity>, <state>)
END
Or combining message_erorr:
IF #var1 > 1
BEGIN
SET #err += ' ASD';
END
IF #var1 <4
BEGIN
SET #err += ' ZXC'
END
IF #var = 3
BEGIN
SET #err += ' QWE'
END
RAISEERROR(#err, <your_severity>, <state>)

DECLARE statement make variables to be global? [duplicate]

I would like to declare a variable within an if/else statement in a SQL Server stored procedure. I understand that this is fairly impossible because SQL Server doesn't do memory management with respect to declaration of variables within procedures. Is there a way to have a variable scoped in an if/else statement, then redeclare a variable with the same name in another if/else statement? For example:
create procedure Foo
as
begin
if exists (x)
begin
declare #bob int
set bob = 1
end
else
begin
declare #bob int
set bob = 2
end
end
From books online:
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
However. Nothing keeps you from doing this:
create procedure Foo as begin
declare #bob int
if exists (x)
begin
set #bob = 1
end
else
begin
set #bob = 2
end
end
No, SQL is pretty funny/weird like that
Declare the variable before the if exists block of code
so
declare #bob int
set #bob = 2
if exists(x)
begin
set #bob = 1
end
Now, take a look at these examples and try to guess what happens
WHILE 1 = 2 --not true of course
BEGIN
DECLARE #VAR INT;
END
SET #VAR = 1;
SELECT #VAR;
This of course works, but it is not initialized every time
DECLARE #loop INT
SET #loop = 0
WHILE #loop <=6
BEGIN
DECLARE #VAR INT
SET #VAR = COALESCE(#VAR,0) + 1
SET #loop = #loop +1
END
SELECT #VAR
is there some reason why you can't do :
declare #bob int
if exists(x)
begin set #bob = 1 end
else
begin set #bob = 2 end
You could resort to using dynamic SQL:
if exists (x)
begin
exec sp_executesql N'
declare #bob int
set #bob = 1
';
end
else
begin
exec sp_executesql N'
declare #bob int
set #bob = 2
';
end

SQL radius search webservice IPhone SDK

I am using the following query for radius based search in meters in iPhone. I need to find users within 10 meter. But when the problem is,
lat, lon
--------
9.585879, 76.545488
9.585879, 76.545477
If I use the following function in my query as,
dbo.GetDistanceFrom2LatLong(CONVERT(FLOAT,'9.585879'), CONVERT(FLOAT,'76.545477')
Its returning the following values,
2 1106.079
1 0
actually the value 1106.079 is wrong, it should be within 10 - 15 meters (I haven't moved 1106 meters to test this ;)). I am using iPhone core location for getting GPS information and using the following SQL function. Can anybody suggest a better way to get exact distance from this function?
ALTER Function [dbo].[GetDistanceFrom2LatLong]
(
#Lat1 Float(18),
#Long1 Float(18),
#Lat2 Float(18),
#Long2 Float(18),
#ReturnType VarChar(10)
)
Returns Float(18)
AS
Begin
Declare #R Float(8);
Declare #dLat Float(18);
Declare #dLon Float(18);
Declare #a Float(18);
Declare #c Float(18);
Declare #d Float(18);
Set #R =
Case #ReturnType
When 'Miles' Then 3956.55
When 'Kilometers' Then 6367.45
When 'Feet' Then 20890584
When 'Meters' Then 6367450
Else 20890584 -- Default feet (Garmin rel elev)
End
Set #dLat = Radians(#lat2 - #lat1);
Set #dLon = Radians(#long2 - #long1);
Set #a = Sin(#dLat / 2)
* Sin(#dLat / 2)
+ Cos(Radians(#lat1))
* Cos(Radians(#lat2))
* Sin(#dLon / 2)
* Sin(#dLon / 2);
Set #c = 2 * Asin(Min(Sqrt(#a)));
Set #d = #R * #c;
Return #d;
End
I am answering my own question. When I changed my function as follows its worked. Hope this may help others.
ALTER Function [dbo].[GetDistanceFrom2LatLong]
(
#Lat1 Float(18),
#Long1 Float(18),
#Lat2 Float(18),
#Long2 Float(18),
#ReturnType VarChar(10)
)
Returns Float(18)
AS
Begin
Declare #R Float(8);
Declare #dLat Float(18);
Declare #dLon Float(18);
Declare #a Float(18);
Declare #c Float(18);
Declare #d Float(18);
Set #R =
Case #ReturnType
When 'Miles' Then 3956.55
When 'Kilometers' Then 6367.45
When 'Feet' Then 20890584
When 'Meters' Then 6367450
Else 20890584 -- Default feet (Garmin rel elev)
End
Set #dLat = Radians(#lat2 - #lat1);
Set #dLon = Radians(#long2 - #long1);
Set #a = Sin(#dLat / 2)
* Sin(#dLat / 2)
+ Cos(Radians(#lat1))
* Cos(Radians(#lat2))
* Sin(#dLon / 2)
* Sin(#dLon / 2);
--Set #c = 2 * Asin(Min(Sqrt(#a)));
Set #c = 2 * Atn2(sqrt(#a),sqrt(1-#a));
Set #d = #R * #c;
Return #d;
End

Invalid Object Error on Insert after read of same table

I am trying to insert data into a table based off what is already in the table. I read the table to get the number of records inserted for a certian month and then insert information based off if it is more or less than ten. After I read the table it throws an invalid object name when I try to do that insert. It's not an invalid object as it just read the table. If this is a permissions error how do I correct it? My code is below. Thanks,
Jason
declare #email VARCHAR(75),
#seminarNumber INT,
#isValidEmail BIT,
#monthlyTotal INT,
#statusCode INT
set #email = 'email#domain.com'
set #seminarNumber = '12345'
set #isValidEmail = dbo.RegexMatch('^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$',#email)
if #isValidEmail = 1
begin
SELECT #monthlyTotal = count(mailid)
from Email_Tracking
where emailaddress = #email
and year(datesent) = year(getdate())
and month(datesent) = month(getdate())
if #monthlyTotal > 10
begin
set #statusCode = 1
end
else
begin
set #statusCode = 2
end
end
else
begin
set #statusCode = 3
end
if #statusCode = 1
begin
insert Email_Tracking ('seminarNumber','email','reasonNotSent')
values(#seminarNumber,#email,'Maximum surveys for the month have already been sent')
end
else if #statusCode = 2
begin
insert Email_Tracking ('seminarNumber','email','datesent')
values(#seminarNumber,#email,getdate())
end
else if #statusCode = 3
begin
insertEmail_Tracking ('seminarNumber','email','reasonNotSent')
values(#seminarNumber,#email,'Email address missing or invalid')
end
print #statusCode
try removing quotes from column names. so for eg:
insert Email_Tracking (seminarNumber,email,reasonNotSent)
values(#seminarNumber,#email,'Email address missing or invalid')