Issue converting varchar to INT in sql server - sql-server

I have seen this question all over stackoverflow, but it seems that there are a wide number of solutions tailored to the situation. It seems I have a unique situation as far as I can tell. I am running this sql statement
use IST_CA_2_Batch_Conversion
GO
--T-SQL script to populate the Match type column
declare #MatchType varchar(16),
#PK varchar(500),
#CAReturnCode VARCHAR(255),
#CAErrorCodes VARCHAR(255)
declare cursor1 cursor fast_forward for
select
["Ref#"],
["Return Code"],
["Error Codes"]
from CACodes2MatchType
open cursor1
fetch next from cursor1 into #PK,#CAReturnCode,#CAErrorCodes
while ##fetch_status = 0
begin
set #MatchType = dbo.GetMatchType(#CAReturnCode,#CAErrorCodes)
update CACodes2MatchType
set [Match Type] = #MatchType
where ["Ref#"] = #PK
fetch next from cursor1 into #PK,#CAReturnCode,#CAErrorCodes
end
close cursor1
deallocate cursor1
It will fail at
set #MatchType = dbo.GetMatchType(#CAReturnCode,#CAErrorCodes)
Here is the beginning code for the GetMatchType function:
-- Batch submitted through debugger:
SQLQuery14.sql|6|0|C:\Users\b01642a\AppData\Local\Temp\~vs1C8E.sql
CREATE FUNCTION [dbo].[GetMatchType](#CAReturnCode VARCHAR(255), #CAErrorCodes
VARCHAR(255))
RETURNS VARCHAR(16)
BEGIN
DECLARE #MatchType VARCHAR(16);
DECLARE #errorCodes TABLE(Pos INT, Code CHAR(2));
DECLARE #country INT; -- 1 is US, 2 is Canada
DECLARE #numMinorChanges INT;
DECLARE #numMajorChanges INT;
DECLARE #numSingleCodes INT;
DECLARE #returnCode INT;
DECLARE #verified VARCHAR(16);
DECLARE #goodFull VARCHAR(16);
DECLARE #tentativeFull VARCHAR(16);
DECLARE #poorFull VARCHAR(16);
DECLARE #multipleMatch VARCHAR(16);
DECLARE #unmatched VARCHAR(16);
SET #verified = 'Verified';
SET #goodFull = 'Good Full';
SET #tentativeFull = 'Tentative Full';
SET #poorFull = 'Poor Full';
SET #multipleMatch = 'Multiple Match';
SET #unmatched = 'Unmatched';
SET #returnCode = CAST(#CAReturnCode AS INT);
I will get the error: Msg 245, Level 16, State 1, Line 21
Conversion failed when converting the varchar value '"1"' to data type int.
This error occurs at the last line of the code segment I have shown:
SET #returnCode = CAST(#CAReturnCode AS INT);
This is code that was written by a colleague and supposedly had worked for him. I have had to troubleshoot some errors but I cannot debug this one. I understand alot of people will create a dbo.split function? I don't know if this option will help me in this scenario. I have tried setting #returnCode to a varchar and getting rid of the CAST on #CAReturnCode. As a result, the debugger will make it past that line but raises issues with the rest of the code. I am assuming there is an issue with how I am casting #CAReturnCode? Any help would be much appreciated.

The problem is that #CAReturnCode contains non-numeric characters.
-- Msg 245, Level 16, State 1, Line 21 Conversion failed when converting the varchar value '"1"' to data type int.
See, the outer single quotes are the error message's formatting, but the inner double quotes are in the #CAReturnCode value. So the solution here is to ensure that the variable contains only numeric characters prior to converting. If double quotes are the only possibility, you can do a quick and dirty fix like this:
set #returnCode = cast(replace(#CAReturnCode, '"', '') as int)
If there are more possibilities, you could do multiple REPLACE calls, or you could build a better character-trimming function that will remove all the characters you specify at once yourself.

Related

SQL Procedure has no parameters and arguments were supplied

So here is the code for the stored procedure and my execution. I keep getting this message when I try to execute my command:
Msg 8146, Level 16, State 2, Procedure sp_LabelFilm, Line 0
Procedure sp_LabelFilm has no parameters and arguments were supplied.
Any idea why? I am trying to update a column in the table tblfilm to say if a movie is short, medium, or long based on its run time.
ALTER PROCEDURE [dbo].[sp_LabelFilm]
AS
BEGIN
DECLARE #Minutes INT, #duration char(10)
DECLARE Filmcursor CURSOR FOR
(SELECT filmruntimeminutes, Duration FROM tblFilm)
OPEN filmcursor
FETCH NEXT FROM filmcursor INTO #duration
WHILE (##FETCH_STATUS = 0)
BEGIN
SELECT #Minutes = FilmRunTimeMinutes FROM tblFilm
IF #Minutes < 120
SET #duration = 'short'
ELSE IF #Minutes < 150
SET #duration = 'medium'
ELSE
SET #duration = 'long'
FETCH NEXT FROM filmcursor INTO #duration
UPDATE tblFilm
SET Duration = #duration
END
CLOSE filmcursor
DEALLOCATE filmcursor
END
DECLARE #Minutes INT, #duration CHAR(10)
EXECUTE [dbo].[sp_LabelFilm] #minutes, #duration
the error means exactly what it says. That you are passing arguments (variables #minutes and #duration) but there are no parameters defined on the stored procedure.
To declare parameters (input variables) you actually declare them before the AS like so:
use Movies
go
alter PROC [dbo].[sp_LabelFilm]
#Minutes INT
,#duration CHAR(10)
AS
BEGIN
DECLARE Filmcursor CURSOR
......
Notice you don't need to use the key word DECLARE and once they are a declared as parameters you don't actually need to declare them again.
Next I am not totally sure what you are attempting to accomplish with the parameters in the stored procedure but it actually looks like you don't want to pass them but rather you want to get them as out put which would be like this:
use Movies
go
alter PROC [dbo].[sp_LabelFilm]
#Minutes INT OUTPUT
,#duration CHAR(10) OUTPUT
AS
BEGIN
DECLARE Filmcursor CURSOR
....
And your execution statement would look like this:
declare #Minutes INT, #duration char(10)
execute [dbo].[sp_LabelFilm] #minutes = #Minutes OUTPUT, #duration = #duration OUTPUT
I had defined the parameters on the stored procedure, before the AS, but still I was facing the same problem until I realized that the procedure had 'create' instead of 'alter'. Changing it to alter procedure worked for me.(Faced this issue while I was trying to debug).
Apart from the first answer which is apt - In my case I did not have any parameters and while EXEC was getting a similar error.
However the difference being - I was putting a "go" below the EXEC statement.
After removing the go it was executed properly.

Getting Truncation error in SQL SERVER while executing Stored procedure

I am getting the below error while executing a stored procedure
USE [Smart2uat]
GO
/****** Object: StoredProcedure [dbo].[SPJOB_ALLLOC] Script Date: 2/11/2016 12:37:40 PM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO
ALTER PROCEDURE [dbo].[SPJOB_ALLLOC] AS
declare #cardno as varchar(8)
declare #iodate as datetime
declare #iotime as varchar(8)
declare #holdername as varchar(100)
declare #IO_MSKID as varchar(7)
declare #IO_LOCATION_CODE as varchar(3)
declare #IO_COMPANY_CODE as varchar(3)
declare #IO_ACTIVITY_CODE as varchar(6)
declare #IO_FIRST_NAME as varchar(20)
declare #IO_THIRD_NAME as varchar(20)
declare #IO_EMPLOYEE_CODE as varchar(3)
declare #rows as integer
declare curatt1 cursor for
select iodate,cardno,iotime,holdername from iodatatmp where isnull(cardno,'')<>'' and isnull(cardno,'') not like 'XXXX%' order by iotime
open curatt1
fetch next from curatt1 into #iodate,#cardno,#iotime,#holdername
WHILE ##FETCH_STATUS = 0
BEGIN
if not exists(select CardNo from iodata where iodate= #iodate and cardno= #cardno)
begin
select #IO_MSKID = ''
select #IO_MSKID=MSKID,#IO_LOCATION_CODE=LOCATION_CODE,#IO_COMPANY_CODE=COMPANY_CODE,#IO_ACTIVITY_CODE=ACTIVITY_CODE,#IO_FIRST_NAME=FIRST_NAME,#IO_THIRD_NAME=THIRD_NAME,#IO_EMPLOYEE_CODE=EMPLOYEE_CODE from Employee_Mast where card_number = #cardno
IF #IO_MSKID <> ''
insert into iodata(cardno,iodate,iotime,holdername,IO_MSKID,IO_LOCATION_CODE,IO_COMPANY_CODE,IO_ACTIVITY_CODE,IO_FIRST_NAME,IO_THIRD_NAME,IO_EMPLOYEE_CODE)
values(#cardno,#iodate,#iotime,#holdername,#IO_MSKID,#IO_LOCATION_CODE,#IO_COMPANY_CODE,#IO_ACTIVITY_CODE,#IO_FIRST_NAME,#IO_THIRD_NAME,#IO_EMPLOYEE_CODE)
end
fetch next from curatt1 into #iodate,#cardno,#iotime,#holdername
END
close curatt1
deallocate curatt1
delete from iodata where cardno like 'XXXX%'
error is
Msg 8152, Level 16, State 14, Procedure SPJOB_ALLLOC, Line 31
String or binary data would be truncated.
The statement has been terminated.
(0 row(s) affected)
Can you please help me..? I am attaching the table design of iodatatmp on which the cursor is fetching and the destination table - Iodata
I have checked the length of the variable...and seems everything fine....Kindly help me..Thanks in advance
The error you are getting is caused by the fact that the size of some of the varchar type columns in IODataTmp are larger than the equivalent column in IOData.
For instance IODataTmp.Holdername is declared as varchar(32) and yet IOData.Holdername is declared as varchar(20) and so if you have a value in IODataTmp.Holdername that is longer than 20 characters it will fail when it tries to insert into IOData.Holdername. Another issue you have is that variables you have declared in the stored procedure to hold the values are a different size again, #holdername is declared as varchar(100).
The solution is to ensure that all the column and variable sizes for a piece of data are the same.

TSQL - Conversion failed on Output parameter

I have the following procedure;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
--re runnable.
IF EXISTS (SELECT 1 FROM sys.objects WHERE name = 'spGetMessageArray' AND type = 'P' )
BEGIN
DROP PROCEDURE dbo.spGetMessageArray
END
GO
CREATE PROCEDURE dbo.spGetMessageArray
#message VARCHAR(50),
#messageArray VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON
SELECT #messageArray = (SELECT CAST(MessageId AS VARCHAR(5))+','
FROM Messages
WHERE Message = #message
FOR XML Path(''))
-- Remove trailing comma if necessary
SELECT #messageArray = LEFT(#messageArray, LEN(#messageArray) - 1)
RETURN #messageArray
END
When I run this as just a query (not as an sp), I get the results I want (33, 44, 53) as a comma separated string.
When I call this using;
DECLARE #message VARCHAR(50) = 'Safety'
DECLARE #messageArray VARCHAR(50) =''
EXEC dbo.spGetMessageArray #message, #messageArray = #messageArray OUTPUT
PRINT #messageArray
I get an error:
Conversion failed when converting the varchar value '33,44,53' to data type int.
Can anyone explain what I'm misunderstanding. I'm guessing the INT is some form of count of rows affected or something. I'm just so confused by that damn int. As far as I can tell, I'm just using VARCHAR

Calling dynamic SQL Server stored procedure - expects parameter which was not supplied

I'm trying to call a stored procedure, the name of which is provided by looping through a table. The stored procedure is in another database.
However, I keep getting the message
Procedure or function 'sp_KPI_People_Added_Count' expects parameter
'#Period', which was not supplied.
But it is being supplied.
I have set the statement and parameter definition to NVarChar and prefixed them with N. I've also tried this on the parameters themselves but apparently that's not required.
All the print output is as expected and if I call an execute with the text, it works fine.
So I'm stuck. Any pointers would be warmly welcomed.
Thanks,
Chris.
Declare #KPI_Value Decimal(14,4)
Declare #StoredProcedure NVarChar(200)
Declare #Periodic Char(1)
Declare #ExecSql NVarChar(200)
Declare #ParameterDefinition AS NVarChar(200)
Declare KPI_Cursor CURSOR LOCAL FOR
SELECT SProc, Periodic from KPI where Section = 2
FOR UPDATE OF Current_Value
Open KPI_Cursor
Fetch Next From KPI_Cursor into #StoredProcedure, #Periodic
Declare #Required_Period VARCHAR(5)
SET #Required_Period='MTD'
While ##FETCH_STATUS = 0 BEGIN
Set #KPI_Value = 0 -- Have tried with and without this
If #Periodic = 'Z' BEGIN
SET #ExecSQL = N'Prod.dbo.' + #StoredProcedure;
/* Specify Parameter Format */
SET #ParameterDefinition = N'#Period VarChar(5), #Result_Type VarChar(10), #Result Decimal(14,4) OUTPUT';
/* Execute Transact-SQL String */
print #ExecSQL
print #ParameterDefinition
print #Required_Period
print #KPI_Value
EXECUTE sp_executesql #ExecSQL, #ParameterDefinition, #Required_Period, 'Result', #KPI_Value Output
END
Fetch Next from KPI_Cursor into #StoredProcedure, #Periodic
END
Close KPI_Cursor
Deallocate KPI_Cursor
The stored procedures have parameters as follows:
ALTER PROCEDURE [dbo].[sp_KPI_People_Added_Count]
#Period VarChar(5), -- MTD or YTD
#Result_Type VarChar(10), -- Summary, Result or Detail
#Result Decimal(14,4) OUTPUT -- The returned result
AS
....
The output is as follows:
Prod.dbo.sp_KPI_People_Added_Count
#Period VarChar(5), #Result_Type VarChar(10), #Result Decimal(14,4) OUTPUT
MTD
0.0000
Msg 201, Level 16, State 4, Procedure sp_KPI_Cust_Added_Count, Line 0
Procedure or function 'sp_KPI_People_Added_Count' expects parameter '#Period', which was not supplied.
An alternative way...
EXEC has the little used form EXEC #module_name_var
So you can do this
If #Periodic = 'Z' BEGIN
SET #module_name_var = N'Prod.dbo.' + #StoredProcedure;
EXEC #module_name_var #Required_Period, 'Result', #KPI_Value Output
END
One observation about your original code...
Use N'Result' for the 2nd parameter. sp_executesql says (my bold)
[ #param1= ] 'value1'
Is a value for the first parameter that is defined in the parameter string. The value can be a Unicode constant or a Unicode variable. There must be a parameter value supplied for every parameter included in stmt.

t-sql replace on text field

I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.
I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.
Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.
Here is the sample query to update table with text column using REPLACE function. Hope this is useful for you.
UPDATE <Table> set textcolumn=
REPLACE(SUBSTRING(textcolumn,1,DATALENGTH(textcolumn)),'findtext','replacetext')
WHERE <Condition>
I am afraid you cannot do it within a function
When you try to declare a function like:
create function dbo.textReplace(
#inText as text)
returns text
as
begin
return 'a' -- just dummy code
end
You will get the following error:
The text data type is invalid for return values.
In other words you could not write a simple equivalent of REPLACE function for the text data type
This is my code snippet for this scenario:
DECLARE #oldtext varchar(1000)
DECLARE #newtext varchar(1000)
DECLARE #textlen int
DECLARE #ptr binary(16)
DECLARE #pos int
DECLARE #id uniqueidentifier
SET #oldtext = 'oldtext'
SET #newtext = 'newtext'
SET #textlen = LEN(#oldtext)
DECLARE mycursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT [UniqueID]
,TEXTPTR([Text])
,CHARINDEX(#oldtext, [Text]) - 1
FROM [dbo].[myTable]
WHERE [Text] LIKE '%' + #oldtext +'%'
OPEN mycursor
FETCH NEXT FROM mycursor into #id, #ptr, #pos
WHILE ##fetch_status = 0
BEGIN
UPDATETEXT [dbo].[myTable].Text #ptr #pos #textlen #newtext
FETCH NEXT FROM mycursor into #id, #ptr, #pos
END
CLOSE mycursor
DEALLOCATE mycursor
You would have to cast the text field to a varchar(8000) or nvarchar(4000) if you are replacing over an ntext field.
MyField = REPLACE(CAST(MyField as VARCHAR(4000)), "string1", "string2")
This ofcourse will only work if you can guarantee the content in the field is <= 4000/8000 characters in length.
You can also use the SUBSTRING() function, which returns a varchar when passed a text value.
For instance:
MyVarchar = SUBSTRING(myTextField, 1, DATALENGTH(myTextField))
If you're populating a varchar with a specific length, you can truncate to fit:
MyVarchar100 = SUBSTRING(myTextField, 1, 100)

Resources