I would like to know how to use NULL and an empty string at the same time in a WHERE
clause in SQL Server. I need to find records that have either null values o
SELECT * FROM DBO.AGENDA
WHERE
--IF @DT_START IS NULL OR EMPTY
( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) -- GET ALL DATE
OR --ELSE
( DT_START >= @DT_START ) --FILTER
-- MORE FILTER
SELECT * FROM DBO.AGENDA
WHERE
( ( ISNULL( @DT_START,'' ) = '' AND DT_START IS NOT NULL ) OR ( DT_START >= @DT_START ) )
AND
DT_END < GETDATE()
This is ugly MSSQL:
CASE WHEN LTRIM(RTRIM(ISNULL([Address1], ''))) <> '' THEN [Address2] ELSE '' END
by this function:
ALTER FUNCTION [dbo].[isnull](@input nvarchar(50),@ret int = 0)
RETURNS int
AS
BEGIN
return (case when @input='' then @ret when @input is null then @ret else @input end)
END
and use this:
dbo.isnull(value,0)
You could use isnull function to get both null
and empty values of a text field:
SELECT * FROM myTable
WHERE isnull(my_nullable_text_field,'') = ''
Select *
From Table
Where (col is null or col = '')
Or
Select *
From Table
Where IsNull(col, '') = ''
--setup
IF OBJECT_ID('tempdb..#T') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T(ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY, NAME VARCHAR(10))
INSERT INTO #T (Name) VALUES('JOHN'),(''),(NULL);
SELECT * FROM #T
1 JOHN
2 -- is empty string
3 NULL
You can examine ''
as NULL
by converting it to NULL
using NULLIF
--here you set '' to null
UPDATE #T SET NAME = NULLIF(NAME,'')
SELECT * FROM #T
1 JOHN
2 NULL
3 NULL
or you can examine NULL
as ''
using SELECT ISNULL(NULL,'')
-- here you set NULL to ''
UPDATE #T SET NAME = ISNULL(NULL,'') WHERE NAME IS NULL
SELECT * FROM #T
1 JOHN
2 -- is empty string
3 -- is empty string
--clean up
DROP TABLE #T