Discussion Locked

IF Clause in SQL Stored Procedure

0 helpful
6 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

I am converting an Access97 SQL statement with several nested IIF clauses to MS SQL-7.0
I tried to do it with IF/ELSE as follows:

IF (TableA.Field1 = 21 or TableA.Field1 = 22)
SET @Amount = @Amount + TableA.Field2
ELSE
IF (TableA.Field1 = 24)
SET @Reserve = @Reserve + TableA.Field2
------
Eventually I want to UPDATE the table with the two declared @ Variables.
The Syntax checks OK in Query Analyzer, but tells me there is no TableA when I run it.
What am I doing wrong? An INSERT part into TableA in the same procedure, located before this, works OK.

6 replies

by shanghai sam

The reason you get an error is that SQL Server does not understand TableA the way you have it defined, if you want to execute your code you need to create a cursor and loop through the cursor to obtain the values of the fields. Instead try the following code, it should work fine from a stored procedure, where you pass in the values of @Amount and @Reserve.

SET @strSQL=UPDATE TableA SET CASE
Field1 WHEN 21 OR 22 THEN
TableA.SomeField = @Amount + TableA.Field2
ELSE
WHEN 24 THEN
TableA.SomeField = @Reserve + TableA.Field2
END

EXEC @strSQL

Good Luck

Neal Martinelli

by frankus

Maybe I wasn't very clear. The answer applies when I the SQL string in ACCESS97. I am writing the stored procedure in SQL - Server. The @Amount etc variables are not passed parameters but variables declared in the Stored Procedure.

by roc180

The reason you get an error is that SQL Server does not understand TableA the way you have it defined, if you want to execute your code you need to create a cursor and loop through the cursor to obtain the values of the fields. Instead try the following code, it should work fine from a stored procedure, where you pass in the values of @Amount and @Reserve.

SET @strSQL=UPDATE TableA SET CASE
Field1 WHEN 21 OR 22 THEN
TableA.SomeField = @Amount + TableA.Field2
ELSE
WHEN 24 THEN
TableA.SomeField = @Reserve + TableA.Field2
END

EXEC @strSQL

Good Luck

Neal Martinelli

by frankus

Maybe I wasn't very clear. The answer applies when I the SQL string in ACCESS97. I am writing the stored procedure in SQL - Server. The @Amount etc variables are not passed parameters but variables declared in the Stored Procedure.

This discussion is closed to new replies.