【原创源码】(02):通用查询存储过程,可应用于多表关联的动态条件查询。

【原创源码】(02):通用查询存储过程,可应用于多表关联的动态条件查询。

欢迎大家发表意见(漏洞,性能等)。在博客园社区以外转载请注明作者和出处。谢谢

1,创建数据表:

None.gif if   exists  ( select   *   from  dbo.sysobjects  where  id  =   object_id (N ' [dbo].[Demo] ' and   OBJECTPROPERTY (id, N ' IsUserTable ' =   1 )
None.gif
drop   table   [ dbo ] . [ Demo ]
None.gif
GO
None.gif
None.gif
CREATE   TABLE   [ dbo ] . [ Demo ]  (
None.gif 
[ DemoId ]   [ varchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NOT   NULL  ,
None.gif 
[ DemoName ]   [ varchar ]  ( 100 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
None.gif 
[ ListPrice ]   [ decimal ] ( 18 0 NULL  ,
None.gif 
[ Quantity ]   [ int ]   NULL  ,
None.gif 
[ LastUpdatedDate ]   [ datetime ]   NULL  
None.gif
ON   [ PRIMARY ]
None.gif
GO
None.gif
None.gif
ALTER   TABLE   [ dbo ] . [ Demo ]   WITH   NOCHECK   ADD  
None.gif 
CONSTRAINT   [ PK_ApplePie ]   PRIMARY   KEY    CLUSTERED  
None.gif (
None.gif  
[ DemoId ]
None.gif )  
ON   [ PRIMARY ]  
None.gif
GO
None.gif
None.gif

2,创建存储过程:

None.gif CREATE           procedure  usp_selectDemo 
None.gif
@DemoId   varchar ( 50 =   null ,
None.gif
@DemoName   varchar ( 50 =   null ,
None.gif
@ListPrice   decimal   =   null ,
None.gif
@Quantity   int   =   null ,
None.gif
@LastUpdatedDate   datetime   =   null ,
None.gif
@LastUpdatedDateBegin   datetime   =   null ,
None.gif
@LastUpdatedDateEnd   datetime   =   null
None.gif
None.gif
as
None.gif
None.gif
-- select * from demo
None.gif--
usp_selectDemo '1'
None.gif

ExpandedBlockStart.gifContractedBlock.gif
/**/ /* Powered by taeheelive@hotmail.com 
InBlock.gifdeclare @sql varchar(500)
InBlock.gifset @sql = ' select DemoId, DemoName, ListPrice, Quantity, LastUpdatedDate from Demo where 1=1'
InBlock.gif
InBlock.gifif @DemoId is not null
InBlock.gifbegin set @sql = @sql + ' AND DemoId = '''+@DemoId+''''  end
InBlock.gif
InBlock.gifif @DemoName is not null
InBlock.gifbegin set @sql = @sql + ' AND DemoName = '''+@DemoName+'''' end
InBlock.gif
InBlock.gifif @ListPrice is not null
InBlock.gifbegin set @sql = @sql + ' AND ListPrice = '+convert(varchar(10),@ListPrice)+'' end
InBlock.gif
InBlock.gifif @Quantity is not null
InBlock.gifbegin set @sql = @sql + ' AND Quantity = '+convert(varchar(10),@Quantity)+'' end
InBlock.gif
InBlock.gifif @LastUpdatedDate is not null
InBlock.gifbegin set @sql = @sql + ' AND LastUpdatedDate = '''+convert(varchar(10),@LastUpdatedDate,120)++''' ' end
InBlock.gif
InBlock.gifif @LastUpdatedDateBegin is not null
InBlock.gifbegin set @sql = @sql + ' AND LastUpdatedDate >= '''+convert(varchar(10),@LastUpdatedDateBegin,120)++''' ' end
InBlock.gif
InBlock.gifif @LastUpdatedDateEnd is not null
InBlock.gifbegin set @sql = @sql + ' AND LastUpdatedDate < '''+convert(varchar(10),@LastUpdatedDateEnd,120)+''' ' end
InBlock.gif
InBlock.gif--print (@sql)
InBlock.gifexec (@sql)
ExpandedBlockEnd.gif
*/

None.gif
ExpandedBlockStart.gifContractedBlock.gif
/**/ /* Powered by 江千帆(cnblogs.com) */
None.gif
SELECT  DemoId, DemoName, ListPrice, Quantity, LastUpdatedDate  FROM  Demo
None.gif 
where   1 = 1  
None.gif
and  ( @DemoId   is   null   or  DemoId  =   @DemoId )
None.gif
and  ( @DemoName   is   null   or  DemoName  =   @DemoName )
None.gif
and  ( @ListPrice   is   null   or  ListPrice  =   @ListPrice )
None.gif
and  ( @Quantity   is   null   or  Quantity  =   @Quantity )
None.gif
and  ( @LastUpdatedDate   is   null   or  LastUpdatedDate  =   @LastUpdatedDate )
None.gif
and  ( @LastUpdatedDateBegin   is   null   or  LastUpdatedDate  >=   @LastUpdatedDateBegin )
None.gif
and  ( @LastUpdatedDateEnd   is   null   or  LastUpdatedDate  <   @LastUpdatedDateEnd )
None.gif
None.gif
None.gif
GO
None.gif
None.gif

3,查询方法:

查询所有记录:usp_selectDemo
查询DemoId='1'的记录:usp_selectDemo '1'
查询DemoName='maxdemo'的记录:usp_selectDemo null,'maxdemo'
等等。

4,Sorry~! 临时修改了5处Bug
change '+@ListPrice+''   to   mailto:'+@ListPrice+''
change mailto:'+@ListPrice+''   to   mailto:'+@ListPrice+''
change '''+@LastUpdatedDate+'''   to   mailto:'+@ListPrice+''
change '''+@LastUpdatedDateBegin+'''   to   mailto:'+@ListPrice+''
change '''+@LastUpdatedDateEnd+'''   to   mailto:'+@ListPrice+''
汗~~,类型转换写的好差,不知哪位高手愿意补完美。谢谢!
ps:为什么上面的字都是当成蓝色的email了,不晓得怎么去掉蓝色和底线,郁闷中。
2006-10-18

5,个人感觉是比较好的一个思路,特大胆放到首页,希望大家讨论哈,优缺点。谢谢!
灵感来自于master数据库中的存储过程“sp_tables”
2006-10-19

6,添加一段数据访问层的应用代码SQLServerDAL,PetShop4.0结构

ContractedBlock.gif ExpandedBlockStart.gif
  1ExpandedBlockStart.gifContractedBlock.gif /**//// <summary>
  2InBlock.gif        /// Query for Demo s by condition.        
  3InBlock.gif        /// </summary>
  4InBlock.gif        /// <remarks>
  5InBlock.gif        /// 查询多条记录(IList范型存储)。
  6InBlock.gif        /// </remarks>
  7InBlock.gif        /// <param name="demoModel">A Demo model.</param>
  8ExpandedBlockEnd.gif        /// <returns>Interface to model Demo collection generic by condition.</returns>

  9None.gif        public IList<DemoModel> QueryCollection(DemoModel demoModel)
 10ExpandedBlockStart.gifContractedBlock.gif        dot.gif{
 11InBlock.gif            IList<DemoModel> DemoModelCollection = new List<DemoModel>();
 12InBlock.gif
 13InBlock.gif            try
 14ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 15InBlock.gif                StringBuilder strSql = new StringBuilder();
 16InBlock.gif                strSql.Append("usp_selectDemo");
 17InBlock.gif
 18InBlock.gif                SqlParameter[] parameters = new SqlParameter[7];
 19InBlock.gif
 20InBlock.gif                parameters[0= new SqlParameter("@DemoId", SqlDbType.VarChar, 50);
 21InBlock.gif                if (demoModel.DemoId != null && demoModel.DemoId.Length > 0)
 22InBlock.gif                    parameters[0].Value = demoModel.DemoId;
 23InBlock.gif                else
 24InBlock.gif                    parameters[0].Value = null;
 25InBlock.gif
 26InBlock.gif                parameters[1= new SqlParameter("@DemoName", SqlDbType.VarChar, 50);
 27InBlock.gif                if (demoModel.DemoName != null && demoModel.DemoName.Length > 0)
 28InBlock.gif                    parameters[1].Value = demoModel.DemoName;
 29InBlock.gif                else
 30InBlock.gif                    parameters[1].Value = null;
 31InBlock.gif
 32InBlock.gif                parameters[2= new SqlParameter("@ListPrice", SqlDbType.Decimal, 8);
 33InBlock.gif                if (demoModel.ListPrice != 0)
 34InBlock.gif                    parameters[2].Value = demoModel.ListPrice;
 35InBlock.gif                else
 36InBlock.gif                    parameters[2].Value = null;
 37InBlock.gif
 38InBlock.gif                parameters[3= new SqlParameter("@Quantity", SqlDbType.Int, 4);
 39InBlock.gif                if (demoModel.Quantity != 0)
 40InBlock.gif                    parameters[3].Value = demoModel.Quantity;
 41InBlock.gif                else
 42InBlock.gif                    parameters[3].Value = null;
 43InBlock.gif
 44InBlock.gif                parameters[4= new SqlParameter("@LastUpdatedDate", SqlDbType.DateTime, 8);
 45InBlock.gif                if (demoModel.LastUpdatedDate != DateTime.Parse("1900-1-1 0:00:00"))
 46InBlock.gif                    parameters[4].Value = demoModel.LastUpdatedDate;
 47InBlock.gif                else
 48InBlock.gif                    parameters[4].Value = null;
 49InBlock.gif
 50InBlock.gif                parameters[5= new SqlParameter("@LastUpdatedDateBegin", SqlDbType.DateTime, 8);
 51ExpandedSubBlockStart.gifContractedSubBlock.gif                if (demoModel.LastUpdatedDateBegin != DateTime.Parse("1900-1-1 0:00:00"))/**//*[t]*/
 52InBlock.gif                    parameters[5].Value = demoModel.LastUpdatedDateBegin;
 53InBlock.gif                else
 54InBlock.gif                    parameters[5].Value = null;
 55InBlock.gif
 56InBlock.gif                parameters[6= new SqlParameter("@LastUpdatedDateEnd", SqlDbType.DateTime, 8);
 57ExpandedSubBlockStart.gifContractedSubBlock.gif                if (demoModel.LastUpdatedDateEnd != DateTime.Parse("1900-1-1 0:00:00"))/**//*[t]*/
 58InBlock.gif                    parameters[6].Value = demoModel.LastUpdatedDateEnd;
 59InBlock.gif                else
 60InBlock.gif                    parameters[6].Value = null;
 61InBlock.gif
 62InBlock.gif
 63InBlock.gif
 64InBlock.gif                //foreach (DataRow dr in SqlHelper.Query(strSql.ToString()).Tables[0].Rows)
 65InBlock.gif                //{
 66InBlock.gif                //    DemoModel demo = new DemoModel(dr[0].ToString(), dr[1].ToString(), Convert.ToDecimal(dr[2]), Int32.Parse(dr[3].ToString()), DateTime.Parse(dr[4].ToString()));
 67InBlock.gif                //    DemoModelCollection.Add(demo);
 68InBlock.gif                //}
 69InBlock.gif
 70InBlock.gif                //Execute a query to read the products
 71InBlock.gif                using (SqlDataReader rdr = SqlHelper.ExecuteReader(strSql.ToString(), parameters))
 72ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 73InBlock.gif                    while (rdr.Read())
 74ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
 75InBlock.gif                        DemoModel demo = new DemoModel();
 76InBlock.gif
 77InBlock.gif                        if (!rdr.IsDBNull(0))
 78InBlock.gif                            demo.DemoId = rdr.GetString(0);
 79InBlock.gif
 80InBlock.gif                        if (!rdr.IsDBNull(1))
 81InBlock.gif                            demo.DemoName = rdr.GetString(1);
 82InBlock.gif
 83InBlock.gif                        if (!rdr.IsDBNull(2))
 84InBlock.gif                            demo.ListPrice = rdr.GetDecimal(2);
 85InBlock.gif
 86InBlock.gif                        if (!rdr.IsDBNull(3))
 87InBlock.gif                            demo.Quantity = rdr.GetInt32(3);
 88InBlock.gif
 89InBlock.gif                        if (!rdr.IsDBNull(4))
 90InBlock.gif                            demo.LastUpdatedDate = rdr.GetDateTime(4);
 91InBlock.gif
 92InBlock.gif                        //DemoModel demo = new DemoModel(rdr.GetString(0), rdr.GetString(1), rdr.GetDecimal(2), rdr.GetInt32(3), rdr.GetDateTime(4));
 93InBlock.gif                        DemoModelCollection.Add(demo);
 94ExpandedSubBlockEnd.gif                    }

 95ExpandedSubBlockEnd.gif                }

 96InBlock.gif
 97InBlock.gif                return DemoModelCollection;
 98ExpandedSubBlockEnd.gif            }

 99InBlock.gif            catch (Exception ex)
100ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
101InBlock.gif                throw new Exception(ex.Message, ex);
102ExpandedSubBlockEnd.gif            }

103ExpandedBlockEnd.gif        }

2006-10-19

7,存储过程添加了/* Powered by 江千帆(cnblogs.com) */的方法(默认方法),
因为感觉比我的要优秀,感谢江千帆的意见!2006-10-19

 
注意!在博客园社区以外转载,必须注明:
作者:Clark Chan
和原文出处:http://clarkchan.cnblogs.com/
否则谢绝转载!

转载于:https://www.cnblogs.com/ClarkChan/archive/2006/10/18/532565.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值