Stored procedure, pass table name as a parameter

后端 未结 5 1763
小鲜肉
小鲜肉 2020-12-12 02:15

I have about half a dozen generic, but fairly complex stored procedures and functions that I would like to use in a more generic fashion.

Ideally I\'d like to be abl

相关标签:
5条回答
  • 2020-12-12 02:34

    You'd have to use dynamic sql. But don't do that! You're better off using an ORM.

    0 讨论(0)
  • 2020-12-12 02:36

    You can use dynamic Sql, but check that the object exists first unless you can 100% trust the source of that parameter. It's likely that there will be a performance hit as SQL server won't be able to re-use the same execution plan for different parameters.

    IF OBJECT_ID(@tablename, N'U') IS NOT NULL
    BEGIN 
        --dynamic sql
    END
    
    0 讨论(0)
  • 2020-12-12 02:44
    EXEC(N'SELECT * from ' + @MyTable + N' WHERE ...     ')
    
    0 讨论(0)
  • 2020-12-12 02:48

    Dynamic SQL is the only way to do this, but I'd reconsider the architecture of your application if it requires this. SQL isn't very good at "generalized" code. It works best when it's designed and coded to do individual tasks.

    Selecting from TableA is not the same as selecting from TableB, even if the select statements look the same. There may be different indexes, different table sizes, data distribution, etc.

    You could generate your individual stored procedures, which is a common approach. Have a code generator that creates the various select stored procedures for the tables that you need. Each table would have its own SP(s), which you could then link into your application.

    I've written these kinds of generators in T-SQL, but you could easily do it with most programming languages. It's pretty basic stuff.

    Just to add one more thing since Scott E brought up ORMs... you should also be able to use these stored procedures with most sophisticated ORMs.

    0 讨论(0)
  • 2020-12-12 02:50
    ALTER procedure [dbo].[test](@table_name varchar(max))
     AS
     BEGIN
      declare @tablename varchar(max)=@table_name;
      declare @statement varchar(max);
      set @statement = 'Select * from ' + @tablename;
      execute (@statement);
     END
    
    0 讨论(0)
提交回复
热议问题