Why do I get "Conversion failed when converting the varchar value ' 50 record is not found' to data type int." error while calling the below function - sql

CREATE FUNCTION Fn_MaxSal_emp
(#dept int)
RETURNS varchar(100)
AS
BEGIN
DECLARE #maxsal int
SET #maxsal = (SELECT MAX(sal) FROM emp WHERE deptno = #dept)
IF #maxsal IS NOT NULL
BEGIN
RETURN #maxsal
END
RETURN (TRY_CAST(#dept AS varchar(100)) + ' record not found')
END
SELECT dbo.fn_maxsal_emp(50) AS maxsal
deptno = 50 record is not in the table, so I should get '50 record is not found' as output but gets the error message as shown in the title

It looks like you are are using another function than you have posted here. The error messages says that the varchar value " record 50 is not found" is not convertable to int. Which is correct. But the function you posted would never generate that varchar value. This function would produce "50 record not found"
Please check if you are calling the correct function, perhaps there is an old version in the database and not the version you posted here.
I tried your function here and it works: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=be0ea9d1e6715d77bbc8fa4773702f01 I just changed the returns a little bit because i think it's bad practice to do not specify an explicit cast.

This error is created when first trying to call the function, before even reaching the try_cast() line, because you can't put the ** value from the error message in the #dept variable used to call the method in the first place. That's where the cast from varchar to int fails.

Related

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.

SQL Server Stored Procedure with varchar parameter returns wrong results

I have created a stored procedure which takes a parameter of type varchar(5). My stored procedure was working fine, and returning the correct result, until the time I passed it a string of 6 or more characters.
What happened is that it ignored 6th onward character, and returned result only based on first 5 characters, which was a wrong result. I expect it to throw an error when I am passing a longer string.
Is this a bug or there is way to change this behavior of SQL Server?
create procedure usp_testproc
#param1 varchar(5)
as
begin
if #param1 = '12345'
begin
select 'you got this right'
end
else
begin
select 'String Mismatch'
end
end
No matter whether we call
exec usp_testproc '12345'
or
exec usp_testproc '123456'
we get the same result
varchar(5)
It means you will get only the first 5 chars so it will ignore the rest, the number inside of the "()" shows how many symbols you will store in this param. You can ensure yourself with the longest possible string that can be returned from your procedure and it will be fine
Here's a little extra that you can read :
char and varchar (docs.microsoft)
You need to specify the correct type of the input parameter:
create procedure usp_testproc #param1 varchar(<max number of chars here>)
as...
The stored procedure is working perfectly according what is done inside it. The bug is in your implementation. Your SP accepts max 5 chars long string, but you are expecting it to do work with the strings longer than 5 chars, this is contradiction. So you have to modify your SP in order to get your desired result, you can easily increase the length of the varchar parameter to an acceptable range so that the input does not exceed it. So you can do something like this :
create procedure usp_testproc #param1 varchar(50)
as
begin
if len(#param1)<6
begin
if #param1='12345'
begin
select 'you got this right'
end
else
begin
select 'String Mismatch'
end
end
else
begin
select 'Parameter length is high!'
end
end

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.

Throw a customized error when more chars than expected are passed in a SQL function attribute

I have created a SQL Server function like that:
function [schema].[function_name]
(#ids varchar(5))
but when I call it like with an #ids attribute with more chars than expected e.g.,
select *
from db.schema.function_name('ABCDEFGHIJKLMNOPQRST')
I get no error. How can I throw a customized error in that case? Such as "you passed more chars than expected".
This should be simple
create function dbo.test
(
#id varchar(30)
)
returns varchar(30)
as
begin
if len(#id)>10
begin
return 'Length exceeded'
end
return 1
end
Testing :
select dbo.test(replicate('a',14))
returns
Length exceeded

MonetDB Prepare Statement in Function

I'm trying to create a function that takes the parameters for the column, the table, the limit, and offset. Basically, I want to be able to get a specified number of rows data from a specified table from a specified column.
However, I'm unable to get the following code to work - I get several errors such as:
syntax error, unexpected SELECT, expecting ':' in: "create function get_banana(lim int, off int, tbl varchar(32), col varchar(32)) r"
syntax error, unexpected RETURN in: "return"
syntax error, unexpected END in: "end"
These errors seem kind of meaningless.
My code is as follows:
CREATE FUNCTION GET_BANANA(lim int, off int, tbl varchar(32), col varchar(32))
RETURNS TABLE (clm int)
BEGIN
PREPARE SELECT col FROM tbl LIMIT ? OFFSET ?;
RETURN EXEC (lim, off);
END;
I'd appreciate any help :) Thanks!
I see at least two issues
EXEC needs the identifier that is returned by PREPARE, e.g.:
sql>prepare select * from tables;
execute prepared statement using: EXEC 2(...)
sql>exec 2();
The function parameters tbl and col are string values. You cannot use them as table/column identifiers.
Having said that, I am not even sure if PREPARE can be used inside a function.
No, PREPARE is a top-level statement modifier.