ifexists (select*from dbo.sysobjects where id =object_id(N'[dbo].[Demo]') andOBJECTPROPERTY(id, N'IsUserTable') =1) droptable[dbo].[Demo] GO CreateTABLE[dbo].[Demo] ( [DemoId][varchar] (50) COLLATE Chinese_PRC_CI_AS NOTNULL , [DemoName][varchar] (100) COLLATE Chinese_PRC_CI_AS NULL , [ListPrice][decimal](18, 0) NULL , [Quantity][int]NULL , [LastUpdatedDate][datetime]NULL ) ON[PRIMARY] GO AlterTABLE[dbo].[Demo]WITHNOCHECKADD CONSTRAINT[PK_ApplePie]PRIMARYKEYCLUSTERED ( [DemoId] ) ON[PRIMARY] GO
2,创建存储过程:
Createprocedure usp_selectDemo @DemoIdvarchar(50) =null, @DemoNamevarchar(50) =null, @ListPricedecimal=null, @Quantityint=null, @LastUpdatedDatedatetime=null, @LastUpdatedDateBegindatetime=null, @LastUpdatedDateEnddatetime=null as —select * from demo —usp_selectDemo '1' /**//* Powered by taeheelive@hotmail.com declare @SQL varchar(500) set @SQL = ' select DemoId, DemoName, ListPrice, Quantity, LastUpdatedDate from Demo where 1=1' if @DemoId is not null begin set @SQL = @sql + ' AND DemoId = '''+@DemoId+'''' end if @DemoName is not null begin set @sql = @sql + ' AND DemoName = '''+@DemoName+'''' end if @ListPrice is not null begin set @sql = @sql + ' AND ListPrice = '+convert(varchar(10),@ListPrice)+'' end if @Quantity is not null begin set @sql = @sql + ' AND Quantity = '+convert(varchar(10),@Quantity)+'' end if @LastUpdatedDate is not null begin set @sql = @sql + ' AND LastUpdatedDate = '''+convert(varchar(10),@LastUpdatedDate,120)++''' ' end if @LastUpdatedDateBegin is not null begin set @sql = @sql + ' AND LastUpdatedDate >= '''+convert(varchar(10),@LastUpdatedDateBegin,120)++''' ' end if @LastUpdatedDateEnd is not null begin set @sql = @sql + ' AND LastUpdatedDate < '''+convert(varchar(10),@LastUpdatedDateEnd,120)+''' ' end –print (@sql) exec (@sql) */ /**//* Powered by 江千帆(cnblogs.com) */
Set @DemoName='%'+RTIM(@DemoName)+'%' Select DemoId, DemoName, ListPrice, Quantity, LastUpdatedDate FROM Demo where1=1 and (@DemoIdisnullor DemoId =@DemoId) and (@DemoNameisnullor DemoName Like@DemoName) and (@ListPriceisnullor ListPrice =@ListPrice) and (@Quantityisnullor Quantity =@Quantity) and (@LastUpdatedDateisnullor LastUpdatedDate =@LastUpdatedDate) and (@LastUpdatedDateBeginisnullor LastUpdatedDate >=@LastUpdatedDateBegin) and (@LastUpdatedDateEndisnullor LastUpdatedDate <@LastUpdatedDateEnd) GO