SQL Server CASE statement with multiple THEN clauses - sql

I have seen several similar questions but none cover what I need. I need to put another THEN statement after the first one. My column contains int's. When it returns NULL I need it to display a blank space, but when I try the below code, I just get '0'.
CASE
WHEN Column1 IS NULL
THEN ''
ELSE Column1
END
If I try to put a sting after THEN then it tells me that it cannot convert it from int. I need to convert it to varchar and then change its output to a blank space afterwards, such as:
e.g.
CASE
WHEN Column1 IS NULL
THEN CONVERT(varchar(10), Column1)
THEN ''
ELSE Column1
END
Is there a way of doing this?
Thanks
Rob

A case expression returns a single value -- with a given type. If you want a string result, then you need to be sure that all paths in the case return strings:
CASE WHEN Column1 IS NULL
THEN ''
ELSE CAST(Column1 AS VARCHAR(255))
END
This is more simply written using COALESCE():
COALESCE(CAST(Column1 as VARCHAR(255)), '')
You cannot display an integer as a "blank" (other than using a NULL value).

Related

Best way to check input parameter isnullorwhitespace in tbv function

I have a TBV function. And that function getting couple of input parameters.
CREATE FUNCTION [dbo].[fn]
(
#id NVARCHAR(50),
...
...
)
For example i want to check that #id is not null and is not whitespace.
I was tinking to do like this
SELECT * FROM [FN_Table]() WHERE
COALESCE(#Id,'') !='' AND NULLIF(#id,'') !=null AND #Id=Id
But this is a tedious way i am sure that there would be more elegant and effective way i just newbbe in SQL and do not know best practices.
If you want id to be not null or white space, you can use ltrim():
where ltrim(#id) <> ''
This does the NULL check as well, implicitly.
I'm not sure why you have a comparison to zero. Based on your question this is not necessary. If you are passing in numbers, you should not be using a string type.
Try this, Check with ISNULL and then Get BlankSpace Character Index
SELECT
CASE WHEN ISNULL(#ID,'')='' THEN 1
WHEN CHARINDEX(' ',#ID) >0 THEN 1
ELSE 0
END

SQL: How to make a replace on the field ''

I have a very but tricky question for you guys. So, listen I have a field with spaces and numbers in one of my table columns. The key part is transform the content in a decimal field. The drawback is basically that for some rows I could get something like:
' 1584.00 '
' 156546'
'545.00 '
' '
So, to clean up my column, I have done a LTRIM and RTRIM so spaces gone. So now for a couple of records where the record were just spaces the new content is ''. Finally I need to convert this result to a decimal.
Issue: The thing is that for field that contend just the spaces the new result is '' and I'm not able to apply a REPLACE on this because it's a blank and the code below doesn't work:
SELECT REPLACE('','','0')
-- Final current verison
SELECT CAST(COALESCE(REPLACE(REPLACE([Gross_Weight],' ','0'),',',''),'0') AS DECIMAL(13,3))
How could I figure it out?
thanks so much
SELECT COALESCE(NULLIF(MyColumn, ''), 0)
This has the side-effect that you will also turn NULL values into 0, which you might not want. If that's a problem then a simple CASE statement should do the trick:
SELECT CASE WHEN MyColumn = '' THEN 0 ELSE CAST(MyColumn AS DECIMAL(10, 4)) END
Obviously you'll also have to incorporate any other manipulations that you're already doing.
No need for replace, just concatenate a zero to your column, like
SELECT RTRIM('0' + LTRIM(column))
I presume your data is in a table.
Lets call this table 'DATA' and the column 'VALUE'
Then you might use the below query
UPDATE DATA SET VALUE = 0 where VALUE = ''
To select the value do the below
select case ltrim(rtrim([Gross_Weight])) when ''
THEN 0
ELSE ltrim(rtrim([Gross_Weight])) END
Let me know if i get the requirement wrong.

Converting varchar values to decimal while handling NULLs and EMPTY strings as 0

I have a column of varchar datatype populated with a mix of values such as 1.2, 5.33 while also having NULLs and EMPTY strings.
I want to convert all the values to decimal while treating NULLs and EMPTY strings as 0.
I can change the NULLs or EMPTY strings using the CONVERT function like below. Like this I replace the NULLs and EMPTY strings with a varhcar 0.
CASE WHEN Column1 = '' OR Column1= NULL THEN '0' ELSE Column1 END AS 'NewColumn1'
However what I want to do is to be able to then convert this data (output of NewColumn1) into decimal but when I place the CASE statement into a CONVERT or a CAST function I will have errors.
I also tried the following.
CONVERT(DECIMAL(10,4), ISNULL(Column1, '0')) however it fails since here I am not handling the EMPTY strings.
Any ideas how can I solve this problem.
Simple way:
SELECT CONVERT(DECIMAL(10, 4), ISNULL(NULLIF(Column1, ''), '0'))
Your CASE statement doesn't work because you're cheking if Column1 = NULL. You sholud check if it IS NULL.
CASE WHEN Column1 = '' OR Column1 IS NULL THEN '0' ELSE Column1 END AS 'NewColumn1'
Try this,
SELECT CAST(ISNULL(NULLIF(Column1, ''),0) AS DECIMAL(12,2)) FROM table

SQL: If field is empty, return empty string, otherwise cast as number

I'm running SQL Server 2008 (otherwise I would use Try_Parse) and I need to cast a field as a number in cases where it is non-empty. If the field is empty, an empty string or NULL should be returned. I would prefer if the field was stored as a number in the database, but I have no control over that at this time.
Here is what I have tried:
SELECT CASE WHEN AccountNumber='' THEN '' ELSE CAST(AccountNumber AS bigint) END AS AccountNumber FROM Accounts
OR
SELECT CASE WHEN CAST(AccountNumber AS bigint)=0 THEN '' ELSE CAST(AccountNumber AS bigint) END AS AccountNumber FROM Accounts
But both of these bring back 0 for empty account numbers. I feel that this should be possible but I am going crazy trying to figure it out! Thanks!
You can't select both numbers and empty strings into the same column, because they are incompatible types. That's why the empty strings get converted automatically to 0. NULL should work, however.
SELECT CASE WHEN AccountNumber='' OR AccountNumber IS NULL THEN NULL
ELSE CAST(AccountNumber AS bigint) END AS AccountNumber
FROM Accounts
You can use ISNUMERIC function:
SELECT CASE WHEN ISNUMERIC(AccountNumber) = 1 THEN CAST(AccountNumber AS BIGINT) ELSE NULL END
FROM Accounts

DATALENGTH() or ISNULL() to retrieve fields that are not null and not empty

Quite simply, which of the following methods is better in a WHERE clause to retrieve records where the FIELD_NAME is NOT NULL and NOT Empty
WHERE DATALENGTH(FIELD_NAME) > 0
or
WHERE ISNULL(FIELD_NAME, '') <> ''
Update
I have been informed that the first method gives spurious results for some types of fields... Agree?
Firstly,
select *
from table
where column <> ''
will give exactly the same results as
select *
from table
where isnull(column, '') <> ''
because records where the condition is UNKNOWN rather than FALSE will still be filtered out. I would generally go with the first option.
DATALENGTH counts trailing spaces, which a comparison with '' does not. It is up to you whether you want ' ' to compare unequal to ''. If you do, you need DATALENGTH. If you don't, simply compare with ''.
Note that for TEXT/NTEXT types, comparisons are not supported, but DATALENGTH is.
ISNULL is the best approach instead of DATALENGTH.
I would use
WHERE ISNULL(FIELD_NAME, '') <> ''
One issue that might come up is that a record with a space in it would not be returned. Are you looking for records like that?
I'm not sure about unexpected results from DATALENGTH. I would use the ISNULL method so that SQL Server doesn't need to spend time calculating the length of the record being compared. I don't know the performance difference between the two, just a gut feeling.
if your "not empty" condition encompasses spaces then i would use the nullif
select case when nullif(' ', '') is null then 'y' else 'n' end
y
declare #d varchar(50)
set #d = null
select case when nullif(#d, '') is null then 'y' else 'n' end
y
I would use one of the following:
where coalesce(field_name, '') <> ''
or
where field_name <> '' or field_name is not null
or
where field_name <> ''
The first is standard SQL (coalesce() is standard, isnull() is not). The last is not the most obvious, but NULL will fail the comparison and it allows the use of indexes.
RTRIM(LTRIM(ISNULL(FIELD_NAME, ''))) <> '' will handle spaces and NULLS