How to check if field is NULL and blank? - sql

I'm trying to remove the possibility of blank spaces by a value not existing in the database when creating the view for my lookup. The issue I'm having is that my CASE statement isn't working quite right when I'm trying to check for a NULL or blank value. It seems to work for those that are null but the blank doesn't seem to have as much luck. In this case I am trying to check for null or blank of importantField
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
CASE WHEN (importantField is null OR importantField = '')
THEN '' ELSE ' ' + importantField END,
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup

Is this what you are after
CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,
CASE WHEN (ISNULL(importantField,'') = '')
THEN '' ELSE ' ' + importantField END,
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup

If you only want to check for null and not for empty strings then you can also use ifnull as you tried. But that is not suitable for empty strings too.
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename

Try to change:
importantField is null
with
IsNull(importantField)

CREATE VIEW Lookup4 AS
SELECT TOP 140000 CONCAT(no,ifnull(importantField,'')<>'',
fieldname + ' ', anotherField2) AS UNRELATEDFIELD, Code,
CASE NAME
WHEN '101,,,,,' THEN 'value1e'
WHEN '14,,,,,' THEN 'value3'
WHEN '16,,,,,' THEN 'value4'
END AS NAME
FROM dbo.Lookup

Minor changes according to your result
Method 1:
Select *
From dbo.Lookup
Where IsNull(importantField, '') = ''
Method 2:
Select *
From dbo.Lookup
Where (importantField is NULL or importantField = '')

Related

How to get records where at least one of the fields has a number in SQL Server 2014?

I have a table that has 3 phone number fields (among other fields).
DayTimePhone
EveningPhone
MobilePhone
I need to pull up records where there is a number in at least one of them.
SELECT Field1
,Field2
,Field3
,DayTimePhone
,EveningPhone
,MobilePhone
FROM Contact
WHERE DayTimePhone IS NOT NULL
AND EveningPhone IS NOT NULL
AND MobilePhone IS NOT NULL
But in some results I get rows where all three fields are blank. They don't have a NULL, just blank. So my code works to an extent.
I tried:
SELECT Field1, Field2, Field3
,CASE isnull (DayTimePhone, '-') WHEN '' THEN '-' WHEN ' ' THEN'-'
END DayTimePhone
,CASE isnull (EveningPhone, '-') WHEN '' THEN '-' WHEN ' ' THEN'-'
END EveningPhone
,CASE isnull (MobilePhone, '-') WHEN '' THEN '-' WHEN ' ' THEN'-'
END MobilePhone
INTO #TempTable
--------------------------------
SELECT * FROM #TempTable
WHERE DayTimePhone IS NOT NULL
AND EveningPhone IS NOT NULL
AND MobilePhone IS NOT NULL
AND DayTimePhone != '-'
AND EveningPhone != '-'
AND MobilePhone != '-'
But this code only gives me results WHERE there is a NULL or - in the fields.
How do I get results where there is at least 1 number in any of the three fields?
Edit
Please see my comment to #LONG answer. That solution worked but now the results are also showing rows where the DayTimePhone reads 0. Please read my comment below.
Another option is to simply check the length of the string representing the number. If it is null or too short then simply exclude it from the result.
SELECT * FROM #TempTable
WHERE (
(ISNULL(LEN(RTRIM([DayTimePhone])), 0) > 8)
OR
(ISNULL(LEN(RTRIM([EveningPhone])), 0) > 8)
OR
(ISNULL(LEN(RTRIM([MobilePhone])), 0) > 8)
)
Try:
SELECT * FROM #TempTable
WHERE (DayTimePhone IS NOT NULL AND REPLACE(DayTimePhone,' ','') != '')
OR (EveningPhone IS NOT NULL AND REPLACE(EveningPhone ,' ','') != '')
OR (MobilePhone IS NOT NULL AND REPLACE(MobilePhone ,' ','') != '')
Having blank is not always a good table design, try to update them with NULL
UPDATE:
From you comments, could you please indicate which type 0 phone that is?
If you still see '0' in the result, that means that is definitely not a single 0.
You can just go with WHERE DayTimePhone != '0-0-0' or DayTimePhone != '0-0', but this is not a skeleton key. If you are checking with U.S phone numbers, you can go with Validate U.S. Phone number and using LIKE, '[0-9]', expression pattern like this to check. I will try to give you a general way to check a validate U.S phone query.
A pretty simple way is:
SELECT tt.*
FROM #TempTable tt
WHERE tt.DayTimePhone <> '-' OR
tt.EveningPhone <> '-' OR
tt.MobilePhone <> '-';
NULL values will not return true for the <> comparison.
You should first clean you table from nulls and blank values.
That was actually done already. What you need now is to use the OR command instead of AND and check it for the value you replaced ('-'):
SELECT * FROM #TempTable
WHERE (DayTimePhone IS NOT NULL != '-')
OR (EveningPhone IS NOT NULL != '-')
OR (MobilePhone IS NOT NULL != '-')
I hope it helps...

Fill Variable with Case Statement Results

I have a questionnaire that my users have filled out (several thousand a day)
The result is each questionnaire record contains 70 something fields (that correspond to each question)
I've been asked to identify all the affirmatives for each of the 70 questions and concatentate them into one field (a summary of all the issues identified for that record).
In other languages (VBA in particular) I would accomlish this by initializing a variable to '', looping through my recordset and setting the variable to what it was previously + the field name of the issue. I'm not sure how to accomplish this in sql.
I've tried...
DECLARE #strFYI AS NVARCHAR
SET #strFYI = ''
SELECT
a.record_num
,CASE
WHEN a.Date_Missing = 'Yes' THEN #strFYI = #strFYI + 'Date_Missing, '
WHEN a.Unclear_Images = 'Yes' THEN #strFYI = #strFYI + 'Unclear_Images, '
WHEN a.Damage = 'Yes' THEN #strFYI = #strFYI + 'Damage, '
ELSE #strFYI
END AS FYI_Reasons
FROM
questionaretable a
But obviously that doesn't work. I'll also need to trim the last comma and space off the list once it's generated, but that shouldn't be a problem... I'm just not sure how to iterate through my records and build this concatenation in tsql :) I'm not even sure (because the syntax is wrong) if the variable would be reset to '' before each record was evaluated!
Can anyone help me out here?
This will be very ugly for 70 columns.
SELECT record_num, LEFT(strFYI, LEN(strFYI) - 2)
FROM (
SELECT
a.record_num,
(CASE WHEN a.Date_Missing = 'Yes' THEN 'Date_Missing, ' ELSE '' END) +
(CASE WHEN a.Unclear_Images = 'Yes' THEN 'Unclear_Images, ' ELSE '' END) +
(CASE WHEN a.Damage = 'Yes' THEN 'Damage, ' ELSE '' END) as strFYI
FROM
questionaretable a
) T
Maybe is cleaner using IIF
IIF ( boolean_expression, true_value, false_value )
SELECT record_num, LEFT(strFYI, LEN(strFYI) - 2)
FROM (
SELECT
a.record_num,
IIF(a.Date_Missing = 'Yes', 'Date_Missing, ' , '' ) +
IIF(a.Unclear_Images = 'Yes', 'Unclear_Images, ', '') +
IIF(a.Damage = 'Yes', 'Damage, ', '') as strFYI
FROM
questionaretable a
) T
As CElliot mention not IIF in 2008 so another solution may be
isnull((select 'Date_Missing, ' where a.Date_Missing = 'Yes'),'')

TSQL Replace with Length Constraint

So FIELD2 can return 2 groups of fields concatenated as a single result depending on the value of Mycondition.
My problem is only when Mycondition = 1
If MyCondition = 1 then I need to concatenate INT_FIELD_ONE + 'A' + INT_FIELD_TWO.
The concatenation is not the problem.
The problem is if INT_FIELD_ONE (is null) + 'A' + INT_FIELD_TWO (is null), then I have to return nothing.
My Replace command would work if both fields ONE and TWO are null. But if only 1 is NULL and the other is not the "A" gets deleted any way. The A needs to remain if 1 field is not null.
For Example:
NULL + 'A' + NULL = Nothing
NULL + 'A' + xxxx = Axxxx
xxxx + 'A' + NULL = xxxxA
Therefore I need to make a TSQL replace with a length constraint of result > 1
Any Ideas?
SELECT XXX,
CASE --Case Statement to Return Field2
WHEN MyCondition = 1 THEN
--Constraint on the Replace Starts Here
REPLACE(
Isnull(CAST(INT_FIELD_ONE AS VARCHAR), '') + 'A' +
Isnull(CAST(INT_FIELD_TWO AS
VARCHAR), '')
,'A','')
ELSE
REPLACE(
Coalesce(REPLACE(INT_FIELD_THREE, '', '-'), Isnull(INT_FIELD_THREE, '-'), INT_FIELD_THREE) +
' / ' + Coalesce(REPLACE(INT_FIELD_FOUR, '', '-'),
Isnull(INT_FIELD_FOUR, '-'), INT_FIELD_FOUR) + ' ', '- / - ',
'')
END
AS FIELD2
FROM TABLEX
how about this?
CASE WHEN MyCondition = 1 AND (INT_FIELD_ONE IS NOT NULL OR INT_FIELD_TWO IS NOT NULL) THEN concat..
WHEN MyCondition = 1 THEN NULL -- at that point we know that both are null
ELSE ... END
Notice that now you don't need the REPLACE function when you are doing the concat because you know for sure that one of your fields is not null
…
WHEN MyCondition = 1 THEN
ISNULL(
NULLIF(
ISNULL(CAST(int1 AS VARCHAR), '') + 'A' + ISNULL(CAST(int2 AS VARCHAR), ''),
'A'
),
''
)
…
When both int1 and int2 are NULL, the result of the concatenation will be A. NULLIF() will return NULL if the expression returns A, otherwise it will return the result of the expression. The outer ISNULL() will transform NULL into the empty string or return whatever non-NULL value its first argument has got.

concatenate two database columns into one resultset column

I use the following SQL to concatenate several database columns from one table into one column in the result set:
SELECT (field1 + '' + field2 + '' + field3) FROM table1
When one of the fields is null I got null result for the whole concatenation expression. How can I overcome this?
The database is MS SQL Server 2008. By the way, is this the best way to concatenate database columns? Is there any standard SQL doing this?
The SQL standard way of doing this would be:
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1
Example:
INSERT INTO table1 VALUES ('hello', null, 'world');
SELECT COALESCE(field1, '') || COALESCE(field2, '') || COALESCE(field3, '') FROM table1;
helloworld
If you were using SQL 2012 or above you could use the CONCAT function:
SELECT CONCAT(field1, field2, field3) FROM table1
NULL fields won't break your concatenation.
#bummi - Thanks for the comment - edited my answer to correspond to it.
Normal behaviour with NULL is that any operation including a NULL yields a NULL...
- 9 * NULL = NULL
- NULL + '' = NULL
- etc
To overcome this use ISNULL or COALESCE to replace any instances of NULL with something else..
SELECT (ISNULL(field1,'') + '' + ISNULL(field2,'') + '' + ISNULL(field3,'')) FROM table1
If you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:
SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1
http://www.codeproject.com/KB/database/DataCrunching.aspx
Use ISNULL to overcome it.
Example:
SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1
This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.
If both Column are numeric Then Use This code
Just Cast Column As Varchar(Size)
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
Just Cast Column As Varchar(Size)
If both Column are numeric then use code below.
Example:
Select (Cast(Col1 as Varchar(20)) + '-' + Cast(Col2 as Varchar(20))) As Col3 from Table
What will be the size of col3 it will be 40 or something else

If statement within switch

I know I'm just thinking of the logic all wrong here but how do I achieve the following:
update #table
set column1 = case
when column1 <> ''
then rtrim(column1) + ', ' + rtrim(column2)--if statement here
else rtrim(column2)
end
from #othertable
I basically want to check if rtrim(column 2) = 'value' then replace it with something else. I understand this is within a switch statement, so how would this be acheived?
update #table
set column1 = case
when column1 <> ''
then rtrim(column1) + ', ' +
case
when column2 = 'value'
then rtrim(column2)
else ...
end
else rtrim(column2)
end
from #othertable
Use a REPLACE within your CASE statement
eg: REPLACE(rtrim(column2),'value','newValue');
Refer MSDN for more details on REPLACE
may be you don't need any switch and if clause:
update #table set column1 = rtrim(isnull(nullif(column1,'') + ', ', '')) + rtrim(column2)