0

I have two tables called ALUMNO and ALUMNO_GENERAL.

I would like to create a stored procedure which automatically chooses which table will update by looking at the variable @campo declared as a parameter to the stored procedure.

When I execute the procedure below, it says 1 row affected, but does not update the value of the table.

exec updateAl 'CALLE','0015','ROJO' 

Stored procedure:

create procedure updateAl @campo varchar(30), @matr varchar(10), @newVal varchar(15) as begin if @campo IN ('AP_PATERNO' , 'AP_MATERNO', 'NOMBRE', 'GRUPO', 'TURNO' , 'SEMESTRE' , 'STATUS' , 'NUMEMPLEADO') begin select @campo declare @sql varchar (1000) select @sql= 'update alumno set '+ @campo+'='+@newVal +' where MATRICULA='+@matr exec(@sql) end else update ALUMNO_GENERAL set @campo =@newVal where MATRICULA=@matr end 
5
  • 2
    You second statement in the else isn't going to work as-is. So if your @campo is causing it go to the else then you'll have to fix that up to be dynamic as well. Commented Nov 16, 2017 at 21:07
  • 1
    I hope you are not going to use this in a web application; Little Bobby Tables is close... Commented Nov 16, 2017 at 21:19
  • Tip: The best practice when assembling object names into dynamic SQL statements is to use QuoteName() to avoid problems with odd names, e.g. New Table with a space. Commented Nov 16, 2017 at 21:19
  • My guess would be that you have a UI that auto-saves each field after you leave it (inline editing kind-of-thing), and you don't want to write a separate SQL statement for each field to do the updating. There are definitely alternatives and frameworks that would help you with this. You are setting yourself up for a maintenance nightmare with procedures like this. Commented Nov 16, 2017 at 21:21
  • this is a practice in my school, and I just thought about that to save code.. Commented Nov 16, 2017 at 21:42

1 Answer 1

1

Your dynamic sql is not correct, try this:

select @sql= 'update alumno set '+ @campo+'='''+@newVal +''' where MATRICULA='''+@matr + ''' exec(@sql) end 
Sign up to request clarification or add additional context in comments.

2 Comments

Probably need extra quotes around @matr as well, since it's also a varchar.
it doesn't works :/ also shows the message "1 row(s) affected" but doesn't update the value on the table.. Any idea?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.