SQL 分割字符串和通用分页查询存储过程

来源:互联网 发布:java管理系统界面 编辑:程序博客网 时间:2024/06/06 05:35



USE [sg]  --使用某个数据库

GO
/****** Object:  StoredProcedure [dbo].[findTableIndex]    Script Date: 2017/4/1 17:02:58 ******/
SET ANSI_NULLS ON
GO
--------------------------------分割字符串,生产表----------------------------------------------
go
 create FUNCTION F_split(@c     VARCHAR(2000),    --分割字符串,生产表
                         @split VARCHAR(2))
 returns @t TABLE(
   Field VARCHAR(20))
 AS
   BEGIN
       WHILE( Charindex(@split, @c) <> 0 )  -- 字符@c在@split中的位置
         BEGIN
             INSERT @t
                    (Field)
             VALUES (Substring(@c, 1, Charindex(@split, @c) - 1)) --截取字符串,前面部分
 
             SET @c = Stuff(@c, 1, Charindex(@split, @c), '') --截取字符串,后面部分
         END
 
       INSERT @t
              (Field)
       VALUES (@c)
 
       RETURN
   END
go


----------------------------------------------------------通用分页查询--------------------------------------------
go
SET QUOTED_IDENTIFIER ON
GO
 ALTER proc [dbo].[findTableIndex](    --通用分页查询
    @Table nvarchar(100),    --查询表名
    @Fields nvarchar(200),    --查询表名
    @Where nvarchar(3000),    --查询条件
    @PageIndex int,        --当前页数  
    @PageSize int        --页大小
)
    as  
    set nocount ON  --不返回影响行数,提高效率
    set ansi_warnings ON  --当设置为 ON 时,如果聚合函数(如 SUM、AVG、MAX、MIN、STDEV、STDEVP、VAR、VARP 或 COUNT)中出现空值,将生成警告信息。当设置为 OFF 时,不发出警告。
begin
if (object_id(@Table,N'U') is null)  --查找表是否存在,防止恶性字符
begin
return '表不存在'
return
end
begin  --统计@Fields中的字段不在是表中的数量,防止恶性字符
declare @Field nvarchar(20)
set @Field = @Fields
declare @FieldDifferentCount in --统计@Fields中的字段不在是表中的数量
Select @FieldDifferentCount = COUNT(*)  From dbo.F_split(@Field,',') t1  where  Field not in (select name from syscolumns where id=object_id(@Table) )   -- 查找@Fields中的字段通过分割后生产的字段不在当前表中的数量
if @FieldDifferentCount > 1
begin
return  '存在当前表中不存在的返回字段'
end
end
begin
if(@PageIndex < 0)
    set @PageIndex = 0;
end
begin
    if(@PageSize < 0)
    set    @PageSize = 0
end
declare @sql varchar(5000)
declare @new_key varchar(5000)
set @new_key = REPLACE(REPLACE(' '+@Where,' )',''),' --','') --替换敏感字符,只要替换这几个,防止恶性字符
set @sql = 'select top '+CONVERT(varchar,@PageSize)+' '+@Fields+' from (
select top '+CONVERT(varchar,@PageSize*@PageIndex)+' ROW_NUMBER() over (order by id desc) row,* from '+@Table+Replace(@new_key,'#','''')+' ) a order by id asc'  --由于在key中直接使用 like '%key%'发生异常,就使用 like #key#,到了这里在替换为 : '
exec(@sql)

end


-----------------------------------------执行存储过程-----------------------------------------

go
exec findTableIndex 'UserInformation0','*','',1,10

0 0
原创粉丝点击