Passing table name in sql stored procedure

前端 未结 3 1135
不思量自难忘°
不思量自难忘° 2021-01-03 01:22

Is it possible to pass the table name as input parameter to the stored procedure?

For example:

create procedure test
@tablename char(10)
as
begin
sel         


        
3条回答
  •  情深已故
    2021-01-03 02:08

    The safest way to do this is via a view.

    Create a view which unions all the tables you may wish to access (and which must all have the same column structure), and prefix the rows with the table name.

    CREATE VIEW MultiTable
    AS
        SELECT 'table1' AS TableName, * FROM table1
        UNION ALL
        SELECT 'table2' AS TableName, * FROM table2
        UNION ALL
        SELECT 'table3' AS TableName, * FROM table3
    

    Your stored procedure can now filter on the table name:

    CREATE PROCEDURE test
        @TableName varchar(100)
    AS
        SELECT * FROM MultiTable WHERE TableName = @TableName
    

    This is safer than using dynamic SQL creation and execution.

提交回复
热议问题