I want to write one common stored procedure to insert data in any table of my database

前端 未结 4 1172
不思量自难忘°
不思量自难忘° 2021-01-23 04:44

I have 6 table with different fields. I want to access table name dynamically. is there any idea to do it? My code is below this is simple procedure which I want to make dynamic

4条回答
  •  悲哀的现实
    2021-01-23 05:13

    Don't go there.
    It's a bad idea since you will end up with a long, inefficient stored procedure that will be vulnerable to SQL injection attacks and have performance issues.
    Writing an insert stored procedure for each table is the way to go.

    You wrote you have six different tables with different columns, so writing a stored procedure to handle inserts for all of them will require you to send all the parameters for all columns as well as a parameter for the table name, and a nested if...else with 6 possible paths, one for each table.
    This will end up as a long, messy, poorly written code at best, bad in each parameter: security, performance, code readability and maintainability.

    The only way that makes some sense to achieve such a goal is to write individual insert stored procedures for each table, and then write a stored procedure that will take all of the possible parameters and the table name and inside of it decide what insert stored procedure to execute based on the value of the table name parameter. However, you will be better off leaving conditions like these to the SQL client (your c# code in this case) then to SQL Server.

提交回复
热议问题