检查存储过程中的参数是否为空或空

问题描述:

我知道如何检查一个参数是否为空,但我不知道如何检查它是否空......我有这些参数,我想检查以前参数是空的或空的,然后像下面那样设置它们:检查存储过程中的参数是否为空或空

ALTER PROCEDURE [dbo].[GetSummary] 
    @PreviousStartDate NVARCHAR(50) , 
    @PreviousEndDate NVARCHAR(50) , 
    @CurrentStartDate NVARCHAR(50) , 
    @CurrentEndDate NVARCHAR(50) 
AS 
    BEGIN 
    IF(@PreviousStartDate IS NULL OR EMPTY) 
     SET @PreviousStartdate = '01/01/2010' for example.. 

我希望得到帮助。

我有时用NULLIF是这样的...

IF NULLIF(@PreviousStartDate, '') IS NULL 

有可能是没有理由它比好@Oded和@bluefeet建议的方式,只是文体偏好。

@ danihp的方法真的是很酷,但我厌倦了旧的大脑不会去的时候我想凝聚为空或空:-)

+2

嗨,雷克斯,因为我已经阅读你的答案,我转移到你的符号。 – danihp 2012-04-24 13:31:39

这里是一般模式:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '') 

''是SQL Server一个空字符串。

+0

我认为它应该是:'IF(@PreviousStartDate为空或@PreviousStartDate = '')' – 2012-12-19 23:03:59

你可以使用:

IF(@PreviousStartDate IS NULL OR @PreviousStartDate = '') 
+1

相同的代码Oded和相同的拼写错误? – 2012-12-19 23:06:03

+1

@pavel感谢您指出missin @标志,但您可以从时间戳中看到它们同时发布。 – Taryn 2012-12-19 23:38:27

我用coalesce

IF (COALESCE(@PreviousStartDate, '') = '') ... 

我建议检查无效日期太:

set @PreviousStartDate=case ISDATE(@PreviousStartDate) 
    when 1 then @PreviousStartDate 
     else '1/1/2010' 
    end 

如何结合​​3210和nullif

SET @PreviousStartDate = coalesce(nullif(@PreviousStartDate, ''), '01/01/2010') 

另一种选择:

IF ISNULL(@PreviousStartDate, '') = '' ... 

看到基于这种表达的功能在http://weblogs.sqlteam.com/mladenp/archive/2007/06/13/60231.aspx

你可以试试这个: -

IF NULLIF(ISNULL(@PreviousStartDate,''),'') IS NULL 
SET @PreviousStartdate = '01/01/2010' 

如果你想要一个“空,空白或空格“检查,您可以用避免不必要的字符串操作0和RTRIM这个样子。

IF COALESCE(PATINDEX('%[^ ]%', @parameter), 0) > 0 
    RAISERROR ... 

如果你想使用一个参数是可选的,所以使用它。

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL 
    AS 
    SELECT * 
    FROM AdventureWorks.Person.Address 
    WHERE City = ISNULL(@City,City) 
    AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%' 
    GO 

要检查是否变量为空或空使用本:

IF LEN(ISNULL(@var, '')) = 0