I have a sql server stored procedure that I use to backup data from our database before doing an upgrade, and I’d really like it to be able to run the stored procedure on multiple databases by passing in the database name as a parameter. Is there an easy way to do this? The best I can figure is to dynamically build the sql in the stored procedure, but that feels like its the wrong way to do it.
Share
There isn’t any other way to do this. Dynamic SQL is the only way; if you’ve got strict controls over DB names and who’s running it, then you’re okay just truncating everything together, but if there’s any doubt use QUOTENAME to escape the parameter safely:
Obviously, if there’s anything more being passed through then you’ll want to double-check any other input, and potentially use parameterised dynamic SQL, for example:
This then makes sure that parameters for the dynamic SQL are passed through safely and the chances for injection attacks are reduced. It also improves the chances that the execution plan associated with the query will get reused.