I face a problem while writing a stored procedure. I want to write a stored procedure so that it gets 2 input parameters (Date
and TableName
) and then delete table rows which Date
column of the table is smaller than the given input date.
The table has 3 columns:
Date Name Id
Thank you
Best Answer
Create a stored procedure that builds a dynamic SQL statement based on your input parameters and then executes the command
First, let's create a test table with some data to play with.
Now, let's create the 'delete' stored procedure. My example takes in 3 parameters. DeleteDate, SchemaName and TableName.
Now, let's test the stored procedure by passing in some different DeleteDates and checking the results.
I also added some error checking logic in the stored procedure to show how you might prevent rogue deletes that are too aggressive due to the date being passed in. My example stored procedure throws an error if you try to delete any rows within the past month. (I wrote this answer on 4/9/2017 and on that date, the following throws an error.