Displaying NULL values as 'unknown' in SQL Server - sql-server

I have a table that has two columns; one for Name (datatype nvarchar), the other for ID (datatype int and allows null).
I am trying to display all data from the table including those with null values but I want the query result to display the null value as 'unknown'.
I ran the following query:
Select Name, ID
Case
When ID is null then 'unknown'
When id is not null then (ID)
End
From table
The problem is I am getting this message:
Conversion failed when converting the varchar value 'unknown' to data type int

I guess you could cast your integers to a varchar
You can also use COALESCE instead of case when dealing with nulls.
Select Name, COALESCE(CAST(ID AS VARCHAR(10)),'unknown') AS ID
From table

You can use COALESCE function
Select Name, coalesce(convert(varchar(20),ID), 'unknown')
From table

Related

Conversion failed when converting the vardhar value 'abc' to data type int

I am inserting data from one table to another so when inserting I got above error mentioned in title
Insert into dbo.source(
title
)
Select
Title from dbi.destination
title in dbo.source table is of INT data type and title in dbo.destination table is of Varchar data type and I have data like abc, efg, etc. in the dbo.destination table.
So how to solve this now or is it possible to convert and insert values?
You can use SQL Server try_cast() function as shown below. Here is the official documentation of TRY_CAST (Transact-SQL).
It Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
Syntax
TRY_CAST ( expression AS data_type [ ( length ) ] )
And the implementation in your query.
INSERT INTO dbo.source (title)
SELECT try_cast(Title AS INT)
FROM dbi.destination
Using this solution you need to be sure you have set the column allow null true otherwise it will give error.
If you do not want to set the allow null then you need minor changes in select query as shown below - passing the addition criteria to avoid null values.
Select ... from ... where try_cast(Title AS INT) is not null
You must use isnumeric method of SQL for checking is data numeric or not
CONVERT(INT,
CASE
WHEN IsNumeric(CONVERT(VARCHAR(12), a.value)) = 1 THEN CONVERT(VARCHAR(12),a.value)
ELSE 0 END)
Think about your data types - obviously you cannot have a text string like 'abc' in a column that is defined to hold integers.
It makes no sense to copy a string value into an integer column, so you have to confirm how you want to handle these - do you simply discard them (what is the impact of throwing data away?) or do you replace them with some other value?
If you want to ignore them and use NULL in place then use:
INSERT dbo.Source (Title)
SELECT CASE
WHEN ISNUMERIC(Title) = 1 THEN CAST(Title as INT)
ELSE NULL
END
FROM dbo.Destination
If you want to replace the value then simply change NULL above to the value you want e.g. 0
You can use regex to root out non numeric characters
Insert into dbo.source(
title
)
Select
case when Title not like '%[^0-9]%' then null else cast(Title as int) end as Title
from dbi.destination
Just filter only numeric field from destination table like as below:
Insert into dbo.source(
title
)
Select
Title from dbi.destination
where ISNUMERIC(Title) = 1

CASE returns Chinese characters when asked to return a VARBINARY column value

I am trying to retrieve values from a key/value table using the following query. In case the value of the key column is "OrderNumber" or "CustomerNumber", then, instead of the val column, I would like to have another column's value (valHash) from the same key/value table (we can almost call it a key/value/hashvalue table).
But when I run the query I get Chinese characters when my CASE meets its first condition:
SELECT IssueId,
customfield,
CASE
WHEN customfield IN ('OrderNumber', 'CustomerNumber') THEN valHash
ELSE val
END AS Value,
valHash
FROM MyTable
The valHash column data type is VARBINARY.
The problem may occur in Val. Since one column has one datatype, you could opt for this:
SELECT IssueId,
customfield,
CASE
WHEN customfield IN ('OrderNumber', 'CustomerNumber') THEN valHash
ELSE CAST (val AS VARBINARY (500))
END AS Value,
valHash
FROM MyTable
If you want everything as a string, you might want to use this:
SELECT IssueId,
customfield,
CASE
WHEN customfield IN ('OrderNumber', 'CustomerNumber') THEN CONVERT (NVARCHAR (50), Valhash, 2)
ELSE val )
END AS Value,
valHash
FROM MyTable
If you insist on differentiation between VARCHAR and VARBINARY is different cases, you need an extra column.

Conversion failed when converting the varchar value 'SAT' to data type int

I have a table ConsoleGames wherein all columns are of type varchar(50). When I try to create a new table console_games by amending existing datatypes by using the query:
CREATE TABLE console_games
(
game_rank integer,
game_name varchar(1200),
platform_name varchar(1200),
game_year integer,
genre varchar(200),
publisher varchar(1200),
na_sales float,
eu_sales float,
jp_sales float,
other_sales float
)
INSERT INTO console_games
SELECT *
FROM [dbo].[RAWConsoleGames]
I get the following error message:
Msg 245, Level 16, State 1, Line 17
Conversion failed when converting the varchar value 'SAT' to data type int.
When I look into the data in the table the value 'SAT' is in a column for which I am not changing the datatype. 'SAT' value exists in the Platform column which is of varchar type and I am not trying to change the type to int.
Any help will be appreciated.
Thanks
Clearly 'SAT' is not and will never convert to an INT.
Always best to specify the columns to insert ... things change
Now, if the source data is suspect, add a try_convert(). If the conversion fails, a null value will be returned
I don't know the column names of your source, so I substituted SomeColN
INSERT INTO console_games
SELECT try_convert(integer ,SomeCol1)
,try_convert(varchar(1200),SomeCol2)
,try_convert(varchar(1200),SomeCol3)
,try_convert(integer ,SomeCol4)
,try_convert(varchar(200) ,SomeCol5)
,try_convert(varchar(1200),SomeCol6)
,try_convert(float ,SomeCol7)
,try_convert(float ,SomeCol8)
,try_convert(float ,SomeCol9)
,try_convert(float ,SomeCol10)
FROM [dbo].[RAWConsoleGames]
Just for fun, try:
Select try_convert(int,'SAT')
Select try_convert(int,'25.25')
Select try_convert(int,'25')
You should always define the list of columns you're inserting into, and you should also always define the list of columns you're selecting from. Furthermore, I'd recommend to explicitly do any type conversions instead of leaving that up to SQL Server - if you do it yourself, you know when and what you're doing.
So I'd write that statement like this:
-- **DEFINE** the list of columns you're inserting into
INSERT INTO console_games (rank, name, Platform, year, genre, publisher,
sales, eu_sales, jp_sales, other_sales)
-- **DEFINE** the list of columns you're selecting, and any conversions
SELECT
game_rank, game_name, platform_name,
CAST(game_year AS VARCHAR(50)), genre,
publisher,
CAST(na_sales AS VARCHAR(50)),
CAST(eu_sales AS VARCHAR(50)),
CAST(jp_sales AS VARCHAR(50)),
CAST(other_sales AS VARCHAR(50))
FROM
[dbo].[RAWConsoleGames]

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

t-sql view conversion failed when filtering on converted column

I am trying to create view by filtering some table, and include some converted to different type column into select list. View filter excludes from result set rows in which this column can not be converted to that type. Then I select rows from this view and filter rows using this converted column. And I always get error Conversion failed when converting the nvarchar value '2aaa' to data type int
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table _tmp_aaa (id int identity(1, 1), value nvarchar(max) not null)
go
insert _tmp_aaa (value) values ('1111'), ('11'), ('2aaa')
go
create view _tmp_v_aaa
as
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
go
Query 1:
select * from _tmp_v_aaa where value = 11
Are there any workarounds?
Add to your view ISNUMERIC to check if string is numeric value:
CREATE VIEW _tmp_v_aaa
AS
SELECT
id,
[value] = CAST((CASE WHEN ISNUMERIC([value]) = 1 THEN [value] ELSE NULL END) AS INT)
FROM _tmp_aaa
WHERE [value] LIKE '1%'
AND ISNUMERIC([value]) = 1
I tried some tricks... Obviously the optimizer tries to hand down your where criterium where it is not yet tranformed. This is one problem to be solved with a. multi-statement function. Their biggest disadvantage is the advantage in this case: the optimizer will not look into it, but just take their result "as is":
create function fn_tmp_v_aaa()
returns #tbl table(id INT, value INT)
as
BEGIN
INSERT INTO #tbl
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
RETURN;
END
select * from dbo.fn_tmp_v_aaa() where value=11;
If you look at the execution plan , predicates are passed down to the table something like....
And your query gets translated to something like .....
select id, cast(value as int) as value
from tmp_aaa
where CONVERT(INT, value,0) like '1%'
AND CONVERT(INT, value,0) = CONVERT(INT, 11,0)
Now if you run this query you will get the same error you get when you query against the view.
Conversion failed when converting the nvarchar value '2aaa' to data type int.
When the predicate CONVERT(INT, value,0) like '1%' is converted , you have INT on one side of the expressions and varchar on another, INT being the higher precedence, sql server tries to convert whole expression to INT and fails hence the error message.

Resources