Sql Server 存储过程可选参数

有如下存储过程


ALTER PROC [dbo].[P_ChannelType] (@CollectBeginDate DATETIME, @CollectEndDate DATETIME, @Type nvarchar(50) ) AS DECLARE @BeginQueryDate DATETIME DECLARE @EndQueryDate DATETIME SET @BeginQueryDate = Dateadd(day, Datediff(day, '20010101', @CollectBeginDate), '20010101') --获得0SET @EndQueryDate = CONVERT(DATETIME, CONVERT(VARCHAR, @CollectEndDate, 112) , 112) + 1 - 1.0 / 3600 / 24 --获得23:59:59 SELECT a.externalProduct , c.GameChannelName , b.ChannelAccount, a.externalProduct, '增加' Property, SUM(a.num * a.faceValue * ISNULL(b.Discount,1)) AS [Money] FROM externalsystempurchaseorder a JOIN dbo.ChannelAccount b ON a.systemAccount = b.ChannelAccount JOIN dbo.GameChannel c ON a.systemId = c.GameChannelID WHERE purchaseTime >= @CollectBeginDate AND purchaseTime <= @CollectEndDate and (@Type is NULL or a.externalProduct = @Type) GROUP BY a.externalProduct , a.num , a.faceValue , a.disCount , c.GameChannelName , b.ChannelAccount, a.externalProduct

但@Type是一个可选参数,不作为查询条件的时候就给Null
上面关键的一句是

and (@Type is NULL or a.externalProduct = @Type)

就是说当@Type有值的时候,将它作为一个查询条件,没有值的时候就忽略

你可能感兴趣的:(Sql Server 存储过程可选参数)