存储过程为不同的表执行相同的操作

时间:2016-01-27 11:26:53

标签: sql-server

                       Month        Registered Users        Daily - Total Accounted Time (Hrs)


                         Oct             73                      5.90
                         Nov             70                      6.40    
                         Dec             81                      5.80
  

我有3张相同格式的表,我要执行相同的操作   所有这3个表的操作。有没有办法呢?   在存储过程中使用单个查询执行它们吗?

1 个答案:

答案 0 :(得分:0)

试试这样,你应该使用动态SQL。

CREATE PROCEDURE dbo.Proc1 @tablename VARCHAR(256),@groupbycolumn VARCHAR(256)='',@filter VARCHAR(256)=''
AS
  BEGIN
      SET NOCOUNT ON;

      DECLARE @cmd NVARCHAR(max)=''

      SET @cmd='select * from ' + @tablename +''
      --using where
      --SET @cmd='select * from ' + @tablename +' where id='+@filter
      --using group by columns
      --SET @cmd='select '+@groupbycolumn+',max(column) from ' + @tablename + ' '+@groupbycolumn 

      EXEC Sp_executesql
        @cmd
  END 

exec dbo.Proc1 @tablename='table1'--returns results of table1
exec dbo.Proc1 @tablename='table2'--returns results of table2
exec dbo.Proc1 @tablename='table3'--returns results of table3
相关问题