@PageSize int =10, --如果值为负数,则返回所有数据
@TableName nvarchar(200), --表名
@PrimaryKey nvarchar(20), --查询条件字段
@Fields nvarchar(200)='*', --查询字段
@Condition nvarchar(500),
@RecordCount int output - -记录的查询条数
ASDECLARE @tmpSql nvarchar(1024),@tmpSqlCount nvarchar(1024)--定义变量
--挨个给变量赋值
SET @tmpSqlCount='SELECT @RecordCount=count(*) FROM {TableName} WHERE (1=1) {condition}' --{condition}只是当占位符使用
SET @tmpSqlCount=Replace(@tmpSqlCount,'{condition}',@Condition);
EXEC sp_executesql @tmpSqlCount,N'@RecordCount int output', @RecordCount outputSET @tmpSql='SELECT {PageSize} {Fields} FROM {TableName}
WHERE {PrimaryKey} >(
SELECT CASE WHEN max({PrimaryKey}) IS NULL THEN 0 ELSE max({PrimaryKey}) end FROM (
SELECT {CutPage} {PrimaryKey} FROM {TableName} WHERE (1=1) {condition} ORDER BY {PrimaryKey})AS T
)
{condition}ORDER BY {PrimaryKey}'
--挨个给变量赋值
SET @tmpSql=Replace(@tmpSql,'{Fields}',@Fields);
SET @tmpSql=Replace(@tmpSql,'{TableName}',@TableName);SET @tmpSql=Replace(@tmpSql,'{PrimaryKey}',@PrimaryKey);
SET @tmpSql=Replace(@tmpSql,'{condition}',@Condition);IF(@PageSize>0)--要分页
BEGIN SET @tmpSql=Replace(@tmpSql,'{PageSize}',' TOP '+cast(@PageSize AS nvarchar(2)));
END
ELSE--不分页 返回所有数据
BEGIN
SET @tmpSql=Replace(@tmpSql,'{PageSize}',' ');
END
EXEC(@tmpSql)--PRINT(@tmpSql)
go