我试图在nchar(1)
类型列中使用like运算符,下面是我的存储过程:
Create procedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType like '%'+@DiscountType+'%'
set nocount off
end
我在表 tblCoupons 中有2条记录,但我调用proc CouponSearch ''
它会返回0条记录。 TIA。
我也试过以下但不能正常工作。
Select Couponcode from tblCoupons where DiscountType like N'%'+@DiscountType+'%'
答案 0 :(得分:1)
您正在寻找处理IIF
以及''
NULL
条件
select * from tblCoupons
where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)
因此,您的程序变为:
Createprocedure [dbo].[CouponSearch]
(
@DiscountType nchar(1)
)as
begin
set nocount on
Select Couponcode from tblCoupons where DiscountType = IIF(@DiscountType = '' OR @DiscountType IS NULL,DiscountType,@DiscountType)
set nocount off
end
答案 1 :(得分:1)
或者这个,用于检查空值和空字符串。
示例来源
CREATE TABLE TBLCOUPONS
(
Couponid INT ,
Couponcode VARCHAR(10) ,
DiscountType NCHAR(1) ,
Discount INT
)
INSERT TBLCOUPONS
( Couponid, Couponcode, DiscountType, Discount )
VALUES ( 1, 'JT5326', '$', 5 ),
( 2, 'CY1990', '%', 9 )
GO
PROCEDURE
CREATE PROCEDURE [dbo].[CouponSearch] ( @DiscountType NCHAR(1) )
AS
BEGIN
IF ( @DiscountType = '' )
BEGIN
SET @DiscountType = NULL
END
SELECT Couponcode
FROM tblCoupons
WHERE DiscountType = ISNULL(@DiscountType, DiscountType)
END
GO
EXECUTION
EXEC [CouponSearch] '%'
GO
EXEC [CouponSearch] '$'
GO
EXEC [CouponSearch] ''
GO
EXEC [CouponSearch] NULL
GO
结果
------------------EXEC [CouponSearch] '%'
Couponcode
----------
CY1990
(1 row(s) affected)
------------------EXEC [CouponSearch] '$'
Couponcode
----------
JT5326
(1 row(s) affected)
-------------------EXEC [CouponSearch] ''
Couponcode
----------
JT5326
CY1990
(2 row(s) affected)
-------------------EXEC [CouponSearch] NULL
Couponcode
----------
JT5326
CY1990
(2 row(s) affected)
答案 2 :(得分:1)
IIF()函数,如果您使用的是SQL Server 2012:
Select Couponcode from tblCoupons where DiscountType = IIF(ISNULL(@DiscountType,'') = '', DiscountType, @DiscountType)
您可以使用较低版本的
CASE
语句
Select Couponcode from tblCoupons where DiscountType = CASE WHEN ISNULL(@DiscountType,'') = '' THEN DiscountType ELSE @DiscountType END
答案 3 :(得分:1)
你也可以试试这个:
DECLARE @DiscountType nchar(1)
SELECT COUPONCODE
FROM TBLCOUPONS
WHERE CASE WHEN COALESCE(@DISCOUNTTYPE,'')='' THEN 1 ELSE 0 END=1 OR DISCOUNTTYPE = @DISCOUNTTYPE