Conversion failed when converting the nvarchar value '%' to data type int - sql

I have an Object Data Source which pulls information from the database where if we don'd have a value for this particular parameter then we want to get all records. So I have a LIKE statement and I'm using a wildcard to return all entries, but this is giving me the error message
System.Data.SqlClient.SqlException (0x80131904): Conversion failed when converting the nvarchar value '%' to data type int.
The table structure for the relevant column is:
[columnName] VARCHAR(50)
The SQL is something similar to:
SELECT [columns] from [table] where [column] LIKE #param
Then in VB I add the parameter:
Dim sessionParam As New Parameter
sessionParam.Name = "param"
sessionParam.DefaultValue = "%"
sessionParam.Type = TypeCode.String
SqlDataSource1.SelectParameters.Add(sessionParam)
So far I've tried casting the parameter value, casting the column, using dbType for the parameter instead of type, but nothing seems to work and I just get the same error. I suspect the column is reading as an int as this column is a mix of values so some are numbers, some are text, therefore SQL is making the 'educated guess' that that value needs to be an int

Conversion failed when converting the nvarchar value '%' to data type int
Is pretty clear that you have a datatype issue. And the wildcard of '%' is certainly not a integer. You are probably having the issue because the column in where [column] LIKE #param is probably an integer. So even though you identify the parameter as string it is still trying to do an integer to string comparison.
So you are comparing like WHERE Integer LIKE String and that throws a datatype conversion error because SQL will automatically try to convert your string to an integer.
To solve if you want to search for a number as a string which doesn't seem like a good idea you would do something like:
WHERE CAST([column] AS VARCHAR(10)) LIKE #param.

Instead of using LIKE if the parameter is NULL, try this instead.
SELECT [columns] from [table] where #param is null or [column] = #param
If you pass in a NULL parameter everything is returned. If it isn't null, then only where the column matches the parameter will be returned.

Related

Trigger to convert empty string to 'null' before it posts in SQL Server decimal column

I've got a front table that essentially matches our SSMS database table t_myTable. Some columns I'm having problems with are those with numeric data types in the db. They are set to allow null, but from the front end when the user deletes the numeric value and tries to send a blank value, it's not posting to the database. I suspect because this value is sent back as an empty string "" which does not translate to the null allowable data type.
Is there a trigger I can create to convert these empty strings into null on insert and update to the database? Or, perhaps a trigger would already happen too late in the process and I need to handle this on the front end or API portion instead?
We'll call my table t_myTable and the column myNumericColumn.
I could also be wrong and perhaps this 'empty string' issue is not the source of my problem. But I suspect that it is.
As #DaleBurrell noted, the proper place to handle data validation is in the application layer. You can wrap each of the potentially problematic values in a NULLIF function, which will convert the value to a NULL if an empty string is passed to it.
The syntax would be along these lines:
SELECT
...
,NULLIF(ColumnName, '') AS ColumnName
select nullif(Column1, '') from tablename
SQL Server doesn't allow to convert an empty string to the numeric data type. Hence the trigger is useless in this case, even INSTEAD OF one: SQL Server will check the conversion before inserting.
SELECT CAST('' AS numeric(18,2)) -- Error converting data type varchar to numeric
CREATE TABLE tab1 (col1 numeric(18,2) NULL);
INSERT INTO tab1 (col1) VALUES(''); -- Error converting data type varchar to numeric
As you didn't mention this error, the client should pass something other than ''. The problem can be found with SQL Profiler: you need to run it and see what exact SQL statement is executing to insert data into the table.

Conversion failed : converting from a character string to uniqueidentifier

I have the following function which returns the following result set when this string is called.
SELECT item
FROM dbo.DelimitedSplit8K('985B773F-5E36-47D4-9E84-E0CE35B34337,32237666-86F3-41FD-BCDE-794571CDAEA2',',')
Result set:
item
------------------------------------
985B773F-5E36-47D4-9E84-E0CE35B34337
32237666-86F3-41FD-BCDE-794571CDAEA2
Now the purpose of this function is to get the two or more IDs cause I will be passing multiple IDs from my C# program to one variable in my stored procedure.
Problem
The problem seems to be simple enough but I am not sure as to why it's occurring.
CREATE PROC [dbo].[usp_printMulitTest]
#multiApplicationId_FK uniqueidentifier = '',
#pDelimiter CHAR(1) = NULL
AS
;WITH image_CTE(imgBinary, imgCode, appID) AS
(
SELECT
[image], imageCode_FK, app
FROM
[dbo].Images
WHERE
CAST('985B773F-5E36-47D4-9E84-E0CE35B34337,32237666-86F3-41FD-BCDE-794571CDAEA2' AS UNIQUEIDENTIFIER)
IN ((SELECT item
FROM dbo.DelimitedSplit8K(CAST('985B773F-5E36-47D4-9E84-E0CE35B34337,32237666-86F3-41FD-BCDE-794571CDAEA2' AS UNIQUEIDENTIFIER),',')))
)
SELECT *
FROM image_CTE
This stored procedure works fine when I hard code the variables.
However, when I convert it to this
WHERE CAST(app AS UNIQUEIDENTIFIER)
IN((SELECT item FROM dbo.DelimitedSplit8K(CAST(#multiApplicationId_FK AS UNIQUEIDENTIFIER),',' )))
to get the results for the app IDs that I pass in, I get an error
Conversion failed when converting from a character string to uniqueidentifier
While looking for solutions two that were pointed out is the incorrect formation of the unique identifier and not using cast, however I checked the numbers and used a cast/convert and there has been no change.
Grateful for assistance in this.

Value does not apply to variable in SQL Anywhere

when I try to execute this function I get a error. When I execute the command without a function and without using variables it works, therefore I think the value does not apply to my variable, the declaration or the setting of variable does not work. It doesn't matter if I use SELECT or SET to set the variable, I get the same error which literally just says: The command could not be executed.
CREATE FUNCTION ueberpruefe_kfz_status (#kennzeichen CHAR(15))
RETURNS VARCHAR
AS
BEGIN
DECLARE #ergebnis VARCHAR
SELECT STATUS
INTO #ergebnis
FROM KFZ
WHERE KENNZEICHEN = #kennzeichen
RETURN #ergebnis
END
Here are some screenshots of the structure, sample data and the error:
https://picload.org/folder/ldpwa.html
As per your table structure seen in the image, it seems like your column STATUS is of type CHAR.
Try to Change your function return type from VARCHAR to CHAR like-
RETURNS CHAR
And type of variable #ergebnis to CHAR like-
DECLARE #ergebnis CHAR
You may specify length along with CHAR, like CHAR(15), which should be greater than or equal to the length of your STATUS column.

SQL Server: ISNULL on uniqueidentifier

I am trying to compare a column col1 and a variable #myvar in a WHERE clause. Both usually contain GUIDs, but may also have NULL values.
I thought I could get around the fact that NULL=NULL evaluates to FALSE by using WHERE ISNULL(col1, '')=ISNULL(#myvar, ''). That would compare two empty strings instead, and evaluate to TRUE.
This will, however, produce the following error message:
Msg 8169, Level 16, State 2, Line 3 Conversion failed when converting
from a character string to uniqueidentifier.
I tried
DECLARE #myvar uniqueidentifier = NULL
SELECT ISNULL(#myvar,'') as col1
Same error message.
Two questions:
First, I am trying to convert a uniqueidentifier variable - even though it has a NULL value - to an (empty!) string, not the other way around, as the error message suggests. What gives?
Second, is there a better way to word that WHERE clause I need, to allow for comparing uniqueidentifiers that might be NULL?
I think below expression can be used to check if the GUID column is empty
CAST(0x0 AS UNIQUEIDENTIFIER)
some thing like
...WHERE GuidId <> CAST(0x0 AS UNIQUEIDENTIFIER)
Since the first argument you are passing isnull is not a literal null, it will determine the return type of that call, a uniqueidentifier in your case. The second argument, '', cannot be cast to this type, hence the error you're getting.
One way around this is just to explicitly check for nulls:
WHERE (#myvar IS NULL AND col1 IS NULL) OR (col1 = #myvar)
The reason ISNULL isn't working for you is that the replacement value (the value to be used if the check expression really is null) must be implicitly convertible to the type of the check expression.
Your WHERE clause can use a col IS NULL AND #var IS NULL to check that state.
As others have pointed out, exclude the NULL values from the results and THEN do the comparison. You can use COALESCE to exclude NULL values from comparisons.
Try the following code:
WHERE ISNULL([Guid], NEWID()) = #myvar
Here is another way to overcome this issue:
DECLARE #myvar uniqueidentifier = NEWID()
SELECT * FROM TABLE
Where ISNULL(col1,#myvar) = ISNULL(Col2,#myvar)
This will resolve your error. Conversion failed when converting from a character string to uniqueidentifier.
I needed something similar on a where clause to compare 2 fields.
Declaring a uniqueidentifier variable is causing performance issues.
So I've used something like this.
WHERE COALESCE(Table1.Field1, CAST('00000000-0000-0000-0000-000000000000' AS UNIQUEIDENTIFIER))=COALESCE(Table2.Field2, CAST('00000000-0000-0000-0000-000000000000' AS UNIQUEIDENTIFIER))

comparing input parameter with xml value using like in sql

I have an SQL table with a column which stores xml like this
<AdditionalInfo><RegistrantID>16279</RegistrantID></AdditionalInfo>
I have created a stored procedure like this:
CREATE PROC hr_GetJobStatusByRegistrantId
#registrantId VARCHAR
AS
BEGIN
SELECT TOP 1
[IsSubscribed]
FROM [Hrge].[dbo].[hr_Jobs]
where AdditionalInfo LIKE '%<AdditionalInfo><RegistrantID>%' + #registrantId + '%</RegistrantID></AdditionalInfo>%'
END
When I run this stored procedure, I get null:
exec hr_GetJobStatusByRegistrantId '16279'
If I make this parameter integer then I get convertion to int error.
Please suggest me solution to this.
(Just expanding the comment into an answer)
You should always specify the width of a char or a varchar field, because unless you do the default kicks in. The documentation says:
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
which means that in your case you have actually defined #registrantId as VARCHAR(1) so the value of '16279' was trimmed to a single character ('1') and you actually searched for
%<AdditionalInfo><RegistrantID>%1%</RegistrantID></AdditionalInfo>%
in the database. This actually returned the IsSubscribed flag for the first record it found in the DB that had a '1' anywhere in the RegistrantID field. You got lucky that the value was something wrong, so you noticed it.
Additionally you are using % around your parameter. This means that when you search for a RegistrantID of 123, you'll get results for 123, 1234, 2123, 51236, etc, etc, and then just take the first one, whichever that one is (decided by the database, since there is no order clause). It's my guess that you need an exact match, so you should remove those, and just use
'%<AdditionalInfo><RegistrantID>' + #registrantId
+ '</RegistrantID></AdditionalInfo>%'
Also, it the RegistrantId is actually a number, it would be nice if the interface of the procedure reflected that, so it could be defined with
#registrantId int
and then converted to a string in the query
'%<AdditionalInfo><RegistrantID>' + cast(#registrantId as varchar(10))
+ '</RegistrantID></AdditionalInfo>%'