2012-03-24 14 views
29

Sé cómo comprobar si un parámetro es nulo pero no estoy seguro de cómo comprobar si está vacío ... Tengo estos parámetros y deseo verificar el anterior los parámetros están vacíos o nulos y luego los establece como debajo deComprueba si un parámetro es nulo o está vacío en un procedimiento almacenado

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.. 

Agradecería la ayuda.

Respuesta

58

veces uso NULLIF así ...

IF NULLIF(@PreviousStartDate, '') IS NULL 

Probablemente no hay razón por la que es mejor que la sugerido por @Oded y @bluefeet, solo preferencia estilística.

@ método de danihp es realmente bueno, pero mi viejo y cansado cerebro no iría a fundirse cuando estoy pensando es nulo o vacío :-)

+2

Hola Rex, ya que he leído tu respuesta, pasé a tu notación. – danihp

24

Aquí es el patrón general:

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

'' es una cadena vacía en SQL Server.

+0

creo que debe ser: 'SI (@PreviousStartDate es nulo o @PreviousStartDate = '')' –

2

puede utilizar:

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

El mismo código que Oded y el mismo error de palabra? –

+1

@pavel, gracias por señalar el signo "missin", pero se puede ver desde el momento en que se publicaron al mismo tiempo. – Taryn

10

utilizo coalesce:

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

recomiendo la comprobación de las fechas no válidas también:

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

¿Qué hay de combinar coalesce y nullif?

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

Puede probar esto: -

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

si quieres un "nulo, "verificación de espacio vacío o blanco", puede evitar la manipulación innecesaria de cadenas con LTRIM y RTRIM de esta manera.

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

Si desea utilizar un parámetro es opcional, utilícelo.

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 
1

Para comprobar si la variable es nula o uso de este vacío:

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