Conversion failed when converting the varchar value '%' - sql-server

I need to search the ffg table using the parameter ID(int) to the column Id(int), if ID is not supplied, I would like to return all data from that table. I have tried this query below:
SELECT *
FROM TableName
WHERE Id LIKE ISNULL (#id, '%')
But this query returns the error:
Conversion failed when converting the varchar value '%' to data type
int.

You are comparing an integer with "%"and you also using LIKE which both are wrong.
You need to use this
SELECT *
FROM TableName
WHERE (Id = #id) or (#id is null)

This is what you have to do inside ISNULL:
SELECT *
FROM TableName
WHERE ID = ISNULL(#id, ID))
Here, if #id is null, the ID (the column value itself) is passed for comparison, which will always match and results in returning all data in the table.

This is because of the ISNULL rule:
replacement_value must be of a type that is implicitly convertible to the type of check_expresssion.
In your condition:
ISNULL(#id, '%')
When #id is NULL, SQL Server tries to convert '%' to INT which causes the conversion error.
To return all rows if #id is NULL, you can do this:
SELECT *
FROM TableName
WHERE
(Id = #id OR #id IS NULL)

you need to caste Id because it is integer so do like:
Where CAST(Id AS TEXT) LIKE '123%')

Related

Trying to create function but getting incompatible data type when setting it to actual return type

I'm trying to create a simple function in Snowflake under my schema. All it does is query a table.
Something to the effect of:
CREATE FUNCTION MYNEWFUNCTION (DATE_KEY_INPUT INT)
RETURNS TABLE (COLUMN1 date, COLUMN2 int, COLUMN3 varchar(255) )
as '
SELECT
COLUMN1
,COLUMN2
,COLUMN3
FROM "TABLE"."DBO"."TABLENAME"
where column1 = date_key_input
';
But I'm getting the following error:
Declared return type 'VARCHAR(255)' for column 'COLUMN3' is incompatible with actual return type 'VARCHAR(255)'
I'm lost... its not compatible with the actual data type? What am I missing here...?
The data type from the original table is varchar(255), in the function I've set it to varchar(255) - why is it rejecting?
Also I should note the source is a view not a table, so concretely, I'm trying to create a function which creates a table from a view...
Collation Limitations in Snowflake:
At present Collation and UDFs (user-defined functions) do not always work together. For example, you cannot return a collated string value from a UDF; the server complains that the actual return type is incompatible with the declared return type. You also cannot pass a collated string value to a UDF.
Reference :https://docs.snowflake.com/en/sql-reference/collation.html
There were a couple things going on in your example:
the first issue was the returns clause defining the length of the varchar, you won't need the length
the second was the input parameter/argument not having the right datatype, or
the query was not constructed correctly (col1 was date, col2 was int).
Working example below.
CREATE TABLE my_table (col1 date, col2 integer, col3 varchar(255));
INSERT INTO my_table VALUES (current_date(), 1, 'Hello World'), (current_date(), 2, 'Goodbye');
CREATE OR REPLACE FUNCTION MYNEWFUNCTION (x integer)
RETURNS TABLE (col1 date, col2 integer, col3 varchar)
as
$$
SELECT col1, col2, col3
FROM my_table
where col2 = x
$$
;
SELECT * from TABLE(MYNEWFUNCTION(1));

Can not select rows where column values are empty string in SQL Server?

I have a column which has varchars like "172.54". I am trying to insert into another table where this columns datatype is float. I am getting error saying can not convert datatype varchar to float. So I do
SELECT *
FROM TBL
WHERE ISNUMERIC(COLNAME) <> 1
And I get no results. But casting is not working. So I look and I have empty strings in that column. So I try to
SELECT *
FROM TBL
WHERE COLNAME = ''
And also every other different amount of spaces.
I ultimately just want to convert the empty strings to null
Also len(colname) = 1
declare #test varchar(10) = ' ' -- any number of spaces is equivalent to ''
select try_convert( float, #test ) as floatval -- '' gives you 0
select case when #test = '' then NULL else try_convert( float, #test ) end as floatval -- value '' returns NULL instead of 0
I guess you column has some characters other than numeric data. Also empty string will be converted to zero it will not throw error.
To filter Numeric data use
COLNAME not like '%[^0-9]%'
Try something like this
insert into tablename (col1,col2)
SELECT col1,col2 FROM TBL
COLNAME not like '%[^0-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.

Conversion failed when converting from character string to uniqueidentifier

I have a query which selects a table based on the provided uniqueidentifier Id so when i provides Id to a value it returns the result but if i am passing it like below i am getting an error message. Please suggest how to use Convert or Cast in this case to resolve this issue.
Thanks
SELECT * FROM TBL WHERE ID=''
Assuming #id is a string parameter, and that the ID column is not nullable, you could do something silly like this:
SELECT * FROM TBL WHERE ID = COALESCE(NULLIF(#id, ''), ID);
But really you should be passing NULL if there is no value, not an empty string. This shouldn't be a string parameter in the first place.
According to the comments on this answer, the solution should be something like this (in pseudo-code):
if textbox1.Text.ToString().Equals('') {
SELECT * FROM TBL
}
else {
SELECT * FROM TBL WHERE ID='"+textbox1.text+"'
}
You may do the IF in the C# application.

MSSQL Stored Procedure: Compare Parameter with Column if ISNUMERIC

I have following table "Managers" (simplified):
ID, int
Name, nvarchar(100)
In a stored procedure that has one argument ("Search", type nvarchar), I want to select every row where
The ID-Column is exactly #Search OR
The Name-Column contains #Search.
At the moment, my select in the stored procedure looks something like this:
SELECT ID, Name FROM Managers WHERE
(ISNUMERIC(#Search) = 1 AND [ID] = CAST(#Search AS INT)) Or
Contains([Name], #Search)
If I call the stored procedure with #Search = 1321 (example), the select works.
But if I have a #Search - parameter that is not numeric (example "HES"), I get the following error:
Conversion failed when converting the nvarchar value 'HES' to data type int.
How can I fix this?
Thanks in advance
Raphi
SELECT ID, Name FROM Managers
WHERE [ID] = CASE
WHEN ISNUMERIC(#Search) = 1 AND #Search NOT LIKE '%.%' THEN CAST(#Search AS INT)
ELSE -1
END
OR Contains([Name], #Search)

Resources