ISNULL behaviour in sql server - sql-server

As per my understanding IsNull Function checks the first value if its null or blank then it returns the next value.
SELECT ISNULL(1,getdate())
but the above statement is giving error. Can any one help to highlight the reason?

Implicit conversion from data type datetime to int is not allowed, make the first value a char
SELECT ISNULL('1',getdate())
BTW, just be aware that ISNULL is not ANSI is proprietery and only accepts 2 parameters, COALESCE accepts a lot more
DECLARE #1 INT,#2 int, #3 INT, #4 int
SELECT #4 = 6
SELECT COALESCE(#1,#2,#3,#4)
This statement below is incorrect
IsNull Function checks the first value if its null or blank then it returns the next value.
it doesn't care for blanks
run this
SELECT ISNULL('','A') -- Blank is returned not A
SELECT ISNULL(NULL,'A') -- A is returned because the first value is NULL
another difference between ISNULL and COALESCE is that ISNULL will return the same length as the first parameter
run this
DECLARE #c CHAR(3)
SELECT ISNULL(#c,'not available') -- not
SELECT COALESCE(#c,'not available') --not available

I guess you are trying to replace an Integer with a Date. Try this SELECT ISNULL(1,2) maybe instead.

You can get it to autocast doing this but I really would not recommend it. It's super unclear to someone else looking at this what it is trying to do:
SELECT case when not 1 is null then 1 else getdate() end

Related

SQL Select column tinyint

I have a table with a column:
txntype (tinyint, not null)
I'm doing a select where value of txntype is equal to 9:
where CAST(txntype as varchar(3)) = '9'
but is throwing an error:
Insufficient result space to convert uniqueidentifier value to char.
I also tried:
where ISNUMERIC(txntype) = 9
but no records are selected when query is executed. Any ideas?
Can you add the create statement of that table and the entire select statement, because it seems that either the column has been declared as a uniqueidentifier column or your select is doing something with the value of another column than the one you are using in your where clause.
Also, the ISNUMERIC() function returns a bit (0 or 1) indicating if a value can actually be converted to a numeric datatype. Comparing it with the value 9 will always yield "false" for that piece of the where clause.
If the column is actually a numeric type, you don't have to cast the value in the where clause either way.
where [txntype] = 9
That is enough if the column is really a tinyint. And that's also the reason you need to be looking at other parts of the query in order to find the cause of the error.
You don't need to use cast or isnumeric
Just simply txntype = 9

select from SQL table with concatenation of two string columns

Issue
I want to write a query that will select all from a table where my string value is equal to two columns concatenated together.
This is plain English version:
#MYSTRING varchar(50)
SELECT ALL FROM [FFLOCNP] WHERE COLUMN1 + COLUMN2 = #MYSTRING
I have tried to use the COALESCE but i have never used this before and it is returning me an error:
#CODE varchar(50)
SELECT * FROM [dbo].[FFLOCNP] WHERE COALESCE([LOCTRY], '') || COALESCE([LOCLCN], '') = #CODE
you have to use ISNULL for this.
Use below query may be it helps you.
SELECT * FROM [FFLOCNP] WHERE ISNULL(COLUMN1,'') + ISNULL(COLUMN2,'') = #MYSTRING
Be careful, when using ISNULL instead of COALESCE. ISNULL limits the returned value to the datatype of the first input parameter. In the given example column V1 will be implicitly defined with nvarchar(1), because the longest text in column V1 consists of only one character. ISNULL(V1, [param2]) will therefor return always a one character long string, regardless of the length of the second parameter. In your case ISNULL would work, if you wanted to replace a NULL with an empty string. If you wanted to replace a NULL with a longer string then you MUST use COALESCE instead of ISNULL. COALESCE returns the full string in parameter 2 regardless of the datatype of parameter 1. Apart from this COALESCE is standard SQL whereas ISNULL is a flavor of SQL-Server. Standard SQL should be preferred to T-SQL flavor to get more portable code.
WITH CTE_SRC AS
(
SELECT
[V1]
,[V2]
FROM
(VALUES
(N'A', N'BB')
,(NULL, N'BB')
,(N'A', NULL)
) T([V1],[V2])
)
SELECT
ISNULL([V1], '1234') AS [ISNULL]
,COALESCE([V1], '123') AS [COALESCE]
FROM
CTE_SRC
Result
ISNULL COALESCE
------ --------
A A
1 123
A A

SQL Server Conversion error: Conversion failed when converting the nvarchar value 'XXX' to data type int

Running some pretty simple SQL here:
select *
from table
where columnA <> convert(int,columnB)
and isnumeric(columnB) = 1
Still getting this error every time:
Conversion failed when converting the nvarchar value 'XXX' to data type int.
If you're using SQL Server 2012 or more recent you could use TRY_PARSE which will return NULL when the parse fails.
SELECT TRY_PARSE('one' as int) -- NULL
, TRY_PARSE('1' as int) -- 1
, TRY_PARSE('0.1' as int) -- NULL
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Isnumeric has a lot of odd behavior. For example, it also considers currency signs such as $ or £, and even a hyphen (-) to be numeric.
I think you'd be better of using NOT columnB like '%[^0-9]%' to ONLY take numbers into account.
Check the comments at the bottom of the msdn page for isnumeric(), which you can find here: https://msdn.microsoft.com/en-us/library/ms186272.aspx
This may sound weird, but it breaks when do not put the ISNUMERIC check first. Try this out:
WITH [Table]
AS
(
SELECT columnA,columnB
FROM
(
VALUES (1,'2'),
(2,'XXX')
) A(columnA,columnB)
)
select *
from [Table]
where ISNUMERIC(columnB) = 1 --this works
AND columnA <> convert(int,columnB)
--where columnA <> convert(int,columnB) --this doesn't work
-- and isnumeric(columnB) = 1
I suggest you to reverse your checking like this:
SELECT *
FROM table
WHERE CONVERT(NVARCHAR, columnA) <> columnB
I got this using a combination of the answers and comments here. I used a CASE statement in my WHERE clause and also had to use LIKE instead of ISNUMERIC to account for illegal characters. I also had to use BIGINT because a few select samples were overflowing the INT column. Thanks for all of the suggestions everybody!
select * from patient
where PatientExternalID <>
(case when mrn not like '%[^0-9]%'
then convert(bigint, mrn)
else 0
end)

SQL Server - Cast invalid value to int

Is there any way to deal with SQL casts if the input data is corrupt?
Let's say I have a column of datatype NVarchar(10) and want to cast this column to int.
Let's also say that some of the nvarchar values are corrupt, so they can't be converted to int.
Is there any way to silently ignore these, default them to 0 or some such?
DECLARE #t TABLE (Numbers VARCHAR(20))
INSERT INTO #t
VALUES
('30a'),('30'),('100'),
('100a'),('200'),('200a')
SELECT CASE
WHEN ISNUMERIC(Numbers) = 1
THEN CAST(Numbers AS INT) ELSE NULL END AS Number
FROM #t
ISNUMERIC Function returns 1 when it is an integer value you can use this function.
Result
Number
NULL
30
100
NULL
200
NULL
it will cast the integer values to INT and ignore the values that cannot be cast to Int
Try this with PatIndex() function:
select id, val
from t
where patindex('%[^0-9]%',val) = 0
Note: above query is filtering out corrupted values, if you need to bring them in with 0 values, please use a case expression as below.
select id, case when patindex('%[^0-9]%',val) = 0
then convert(int, val)
else 0 end val
from t
Fiddle demo for both queries
I'll be the unpopular one and advise REGEX because ISNUMERIC, while sometimes useful, doesn't catch everything. This answer on SO excellently covers some REGEX concepts, for instance:
One numeric digit
Probably the easiest one of the bunch:
WHERE Column LIKE '[0-9]'
For more details, here's a useful REGEX workbench by Phil Factor and Robyn Pae.

Handling NULLs in SQL query

What is the right practice of checking NULLs in SQL Case ?
1) Using ISNULL()
WHEN (ISNULL(TABLE.COLUMN,0) > 0) THEN ....
2) Using IS NULL
WHEN TABLE.COLUMN IS NOT NULL THEN ....
If you are checking any condition then always use 'is null' and if replacing any value with a different one, then use isnull(a,b).
Check the following -
http://msdn.microsoft.com/en-us/library/ms184325.aspx
Read the last line specially!!!
Second one is right if you want to check for null value in SQL case..
Both are correct if the values in the column are either greater than 0 or null.
You can refer to this post if you want to know about the weird behavior of nulls in SQL Server.
This is also another approach to check for NON NULL values.
Checking for length of the column if it is greater than 1 or equal 1 then its a NON NULL
value.
declare #emp table
(
fname varchar(50)
);
INSERT into #emp VALUES('vishwanath');
INSERT into #emp VALUES('chetan');
INSERT into #emp VALUES(NULL);
INSERT into #emp VALUES(NULL);
SELECT * FROM #emp
where len(fname)>=1 and fname<>'';
Gives..
fname
--------------------------------------------------
vishwanath
chetan
when you are checking whether a column is null or not it is better to use
col IS NULL
when you use ISNULL(TABLE.COLUMN,0) > 0) function , null values have to be converted to zero fist then should take all values greater than zero
this function is useful in another occasion. lets say if I want to return all the null values as well as the negative values.
so the query would be
select * from table where col is null or col<0
this can be re-written as
select * from table isnull(col,-1)<0
Both are correct in there cause, however ISNULL can be helpfull when you want to use a constant value instead of NULL in that column while calculating SUM, average, etc.
For example you can check :http://www.w3schools.com/sql/sql_isnull.asp
Due to this feature I personally use ISNULL/COALESCE for calculation purposes.

Resources