Passing table name in sql stored procedure

前端 未结 3 1043
不思量自难忘°
不思量自难忘° 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:04

    You would need to use dynamic SQL, but you need to be aware of potential sql injection risks you open yourself up to as if @tablename contained something dodgy, you could end up in a world of pain.

    e.g.

    -- basic check to see if a table with this name exists
    IF NOT EXISTS(SELECT * FROM sys.tables WHERE name = @tablename)
        RETURN
    
    DECLARE @sql NVARCHAR(100)
    SET @sql = 'SELECT * FROM ' + QUOTENAME(@tablename)
    EXECUTE(@sql)
    

    You need to be very careful with this approach, make sure you don't open up a can of security worms.

    My other concern is that you may be trying to make generic data access sprocs which is usually a bad idea. Obviously I don't know your use case.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-03 02:09
    DECLARE @Name VARCHAR(50)
    SET @Name='Company'
    
    EXEC('SELECT * from ' + @Name )
    

    use this way to get record from database.

    0 讨论(0)
提交回复
热议问题