我希望通过将表名作为参数传递来对多个表执行以下存储过程。
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
你可以解决这个问题吗?
答案 0 :(得分: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
答案 1 :(得分:0)
创建一个表,该表将包含要处理的所有表名,并在您的sproc中遍历此表。