3

我想通过将表名作为参数传递来对多个表执行下面的存储过程。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
 GO
 -- =============================================
CREATE PROCEDURE GETARTICLESPAGEWISE
  @PageIndex INT = 1
  ,@PageSize INT = 10
  ,@ArticleCategory varchar(100) = 'null'
  ,@RecordCount INT OUTPUT

 AS
 BEGIN
  SET NOCOUNT ON;
  SELECT ROW_NUMBER() OVER
  (
        ORDER BY [ArticleID] ASC
  )AS RowNumber
  ,[ArticleID]
  ,[ArticleName]
  ,[ArticleCategory]
 INTO #ResultSet
  FROM [ASPDOTNETARTICLES]
  WHERE ArticleCategory = @ArticleCategory
  SELECT @RecordCount = COUNT(*)
  FROM #ResultSet

  SELECT * FROM #ResultSet
  WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) +                @PageSize) - 1

  DROP TABLE #ResultSet
 END
GO


--EXEC dbo.GETARTICLESPAGEWISE @PageIndex =1, @PageSize  = 2,          @ArticleCategory='Gridview',@RecordCount=0

我试过但发生错误,尝试存储过程

    SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
ALTER PROCEDURE GETARTICLESPAGEWISEGENERIC
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@ArticleCategory varchar(100) = 'null'
      ,@RecordCount INT OUTPUT
      ,@TableName varchar(100) = 'NULL'
AS
BEGIN
DECLARE @columnList varchar(200)
SET @columnList='  SELECT ROW_NUMBER() OVER
      (
            ORDER BY [ArticleID] ASC
      )AS RowNumber
      ,[ArticleID]
      ,[ArticleName]
      ,[ArticleCategory]'

      SET NOCOUNT ON;
DECLARE @sqlCommand varchar(300)

set @sqlCommand ='
    SELECT '+ @columnList +'
     INTO #ResultSet
      FROM '+ @TableName +'
      WHERE ArticleCategory ='+ @ArticleCategory+'
      //i got the error in this statement
        SELECT @RecordCount = COUNT(*)
      FROM #ResultSet

      SELECT * FROM #ResultSet
      // i got the error in this statement 
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1

      DROP TABLE #ResultSet'
END
GO

你能解决这个问题吗?

4

2 回答 2

2

试试这个——

CREATE PROCEDURE GETARTICLESPAGEWISE 

       @PageIndex INT = 1
     , @PageSize INT = 10
     , @ArticleCategory VARCHAR(100) = 'null'
     , @TableName VARCHAR(100) = 'dbo.ASPDOTNETARTICLES'
     , @RecordCount INT OUTPUT

AS BEGIN

     SET NOCOUNT ON;

     IF OBJECT_ID (N'tempdb.dbo.##ResultSet') IS NOT NULL
        DROP TABLE ##ResultSet

     DECLARE @SQL NVARCHAR(MAX) = '
     SELECT
           RowNumber = ROW_NUMBER() OVER (ORDER BY ArticleID) 
         , ArticleID
         , ArticleName
         , ArticleCategory
     INTO ##ResultSet
     FROM ' + @TableName + '
     WHERE ArticleCategory = ''' + @ArticleCategory + ''''

     EXEC sys.sp_executesql @SQL

     SELECT @RecordCount = COUNT(*)
     FROM ##ResultSet

     SELECT *
     FROM ##ResultSet
     WHERE RowNumber BETWEEN (@PageIndex - 1) * @PageSize + 1 AND (((@PageIndex - 1) * @PageSize + 1) + @PageSize) - 1

END
于 2013-07-10T10:12:19.703 回答
0

创建一个表,该表将保存所有要处理的表名,并在存储过程中循环遍历该表。

于 2013-07-10T09:53:18.383 回答