Passing table name in sql stored procedure

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

提交回复
热议问题