【发布时间】:2016-04-05 21:32:52
【问题描述】:
我试图让这个存储过程只在函数等于特定 ID 号时返回特定行。例如,if @RentalOnly = 'Y' 则只返回 productID 在 '3367' 或 '3367G' 和 if @RentalOnly = 'N' 中的行,然后返回所有其他不包含此 productID 的行。
这是我目前所拥有的。
alter Procedure [dbo].GetAllProductIDs
@StartDate datetime,
@EndDate datetime,
@RentalOnly char(1)
AS
begin
SET NOCOUNT ON;
CREATE TABLE #GetAllProductIDs
(
[Status] nvarchar(30),
[To Set Date] datetime,
[Order ID] int,
[Product ID] nvarchar(10),
[PPArea] char(2),
[OrderLineNo] nvarchar(10),
[OrigSalesman] nvarchar(30),
[Enterby] int,
[Rental Month] int,
[Quantity] int,
[Quoted$] money,
[EXT$] money,
[Mo Base Rental] money,
[Ext. Base Rental] money,
[Quoted Mo Rent] money,
[3367 Total$ vs. Base Total$] money,
[3367 % Total vs. Base Total] float
)
insert #GetAllProductIDs
exec TempPower_AZ.dbo.GetAllProductIDs @StartDate, @EndDate
insert #GetAllProductIDs
exec TempPower_LV.dbo.GetAllProductIDs @StartDate, @EndDate
insert #GetAllProductIDs
exec TempPower_OC.dbo.GetAllProductIDs @StartDate, @EndDate
insert #GetAllProductIDs
exec TempPower_SD.dbo.GetAllProductIDs @StartDate, @EndDate
insert #GetAllProductIDs
exec TempPower_RS.dbo.GetAllProductIDs @StartDate, @EndDate
if (@RentalOnly = 'Y')
begin
Select *
from #GetAllProductIDs
where [Product ID] in ('3367', '3367G')
return
end
if (@RentalOnly = 'N')
begin
Select *
from #GetAllProductIDs
where [Product ID] not in ('3367', '3367G')
return
end
end
【问题讨论】:
-
那么,忘记 IF/ELSE 并使用类似这样的
WHERE子句怎么样?WHERE (@RentalOnly = 'Y' AND productID IN ('3367', '3367G')) OR (@RentalOnly = 'N' AND productID NOT IN ('36367, '3367G')) -
有什么问题?
-
当@RentalOnly 是 'Y' 或 'N' 以外的值时应该返回什么?您是在问问题还是只是提供状态报告?
-
如果 RentalOnly = 'Y' 则仅返回 productID 在 '3367' 或 '3367G' 中的行,如果 RentalOnly = 'N' 则返回所有其他行中没有此 productID @spencer7593
-
如果 @RentalOnly 包含字符
'W'怎么办?还是'5'?您想问的问题是什么?您是否在询问有关 SQL Server 的IF ELSE语法的问题?当@RentalOnly 不包含 'Y' 或 'N' 时,您是否问过如何返回空结果?完全不清楚你在问什么。
标签: sql sql-server sql-server-2008 stored-procedures