简体   繁体   中英

SQL Server 2008 R2: stored procedure with one or more table names a parameter

I have this stored procedure to archive data which is older than a given number of days for a given table:

CREATE PROCEDURE [dbo].[sp_util_archive_test] 
    @days int, @table_name nvarchar(64)
AS
BEGIN TRY
BEGIN TRANSACTION
    DECLARE @archive_table varchar(128),
            @src_table varchar(128);
    SET @src_table = @table_name;
    SET @archive_table = @table_name + '_archive';

    DECLARE @dropSQL nvarchar(max) = 'DROP TABLE ' + @archive_table;

    IF OBJECT_ID(@archive_table, 'U') IS NOT NULL
      EXEC (@dropSQL);

    DECLARE @sqlCommand nvarchar(1000)
    DECLARE @date varchar(75)
    SET @sqlCommand = 'Select * into [' + @archive_table + ']  from  [' + @src_table + '] WHERE date <= dateadd(d, -' + CAST(@days AS varchar(16)) + ', getdate())'
    EXECUTE sp_executesql @sqlCommand

  COMMIT
END TRY
BEGIN CATCH
  ROLLBACK
  DECLARE @Msg nvarchar(max)
  SELECT
    @Msg = ERROR_MESSAGE();
  RAISERROR ('Error Occured: %s', 20, 101, @Msg) WITH LOG;
END CATCH

Right now I have scheduled multiple SQL jobs to archive data for multiple tables, is there way to eliminate multiple SQL jobs by making the stored procedure to accept 1 or more table names and then to archive the data for all the table at once?

Ignoring the risk of injection; You could pass through delimited strings into a parameter, and then loop through the results executing your existing stored procedure for each itteration.

eg @param = 'table1|Table2|Table3|Table4'

Split on "|" Loop through all results and execute your SP for each itteration.

Split example: How to split string and insert values into table in SQL Server

Why complicate it? Either use multiple job steps or put multiple lines inside a single step:

EXEC [dbo].[sp_util_archive_test] 50, 'table1';
EXEC [dbo].[sp_util_archive_test] 70, 'table2';
EXEC [dbo].[sp_util_archive_test] 80, 'table3';
EXEC [dbo].[sp_util_archive_test] 10, 'table4';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM