Click here to Skip to main content
15,909,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I've got this SQL function

USE [TEGS2]
GO
/****** Object:  UserDefinedFunction [dbo].[udfHazPropsList]    Script Date: 22/10/2021 22:24:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER FUNCTION [dbo].[udfHazPropsList](@ConsignmentNote varchar(255),@HazCode varchar(255))
RETURNS varchar(max)
AS
BEGIN
		DECLARE @ResultVar varchar(max)
	DECLARE @HazProps varchar(max)

	--get a string of all the codes compined
	select @HazProps=stuff( (select ',' + ltrim(rtrim( hazprops ))
    from vwWasteReturn WHERE consignmentNotenumber=@ConsignmentNote AND ewc_code=@HazCode
    for xml path('')),1,1,'');

	--now split the screen, removing duplicates and sorting 
	SET @HazProps =REPLACE(@HazProps,'HP','')

	;with cte as
	(
	 select distinct(Item) from dbo.delimitedSplit8K(@HazProps,',')
    )
	, cte2 as 
	(
	  select  cast(item as integer) as x from cte where ISNUMERIC(item)=1
	)


	select @ResultVar=stuff( (select ', ' + 'HP'+ cast(x as varchar)
    from cte2
    order by x
    for xml path('')),1,1,'');

	REturn @resultvar

END


It has been working fine until this afternoon when it now returns the message - [Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting the varchar value '14' to data type int - the data in the table hasn't changed and I can't work out why it is now doing this?

The code has to combine strings of codes e.g HP14, HP2, HP1 and HP1, HP3, HP5 in a different record would become HP1, HP2, HP3, HP5 and HP14.

Any help would be much appreciated.

Thanks

What I have tried:

Looking for typos in records which has caused this issue in the past e.g. using . instead of , between the different codes
Posted
Updated 23-Oct-21 8:56am
v2

The basic problem is your DB design: you should never store numeric (or Date / Time based) data in strings.

Change your design to use appropriate data types throughout (and alter your presentation software to check, validate, and provide numeric data via parameterised queries) and the need to cast data fields - and thus a whole nest of problems - goes away.
 
Share this answer
 
OK thanks - as an update though, just realised this function works on the same sort of data in another table - why is it particularly the number 14 that is causing this issue? I'm completely stumped to be honest and any help would be very much appreciated?

Thanks in advance!
 
Share this answer
 
Comments
Richard Deeming 25-Oct-21 6:45am    
If you want to reply to a solution, click the "Have a Question or Comment?" button under that solution and post a comment.

Do not post your comment as another "solution".

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900