Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have SQL query as following :

SQL
SELECT TOP (99.9999999) PERCENT CAST(CAST(LEFT(SpecialCode, CHARINDEX('/', SpecialCode) - 1) AS NVARCHAR) AS INT) AS Expr1
	,CAST(CAST(RIGHT(SpecialCode, CHARINDEX('/', SpecialCode) - 6) AS NVARCHAR) AS INT) AS Expr2
	,MemberCode	,SpecialCode	,StartingDate	,JoinDate
	,EndDate	,BirthDate	,NAME	,FirstName
	,MiddleName	,LastName	,Nationality	,Nationality2
	,Education	,Address	,City	,Country	,PostalCode
	,Homephone1	,Homephone2	,Workaddress	,WorkPhone1
	,Ext1	,WorkPhone2	,Ext2	,Mobile1	,Mobile2
	,FaxNumber	,Email	,EmergencyTel	,NoOfYearsTennis
	,ClubName	,NationalRank	,Year	,class	,NoOfYearsTournament
	,Note	,MSRelation	,RelatedMemberCode	,MScategory
	,Member	,ParentCard1	,ParentCard2	,ExpDate	,position
	,worktype	,NonActive	,MSKind	,MSType	,CardNumber
	,CardReceived	,Discount	,Religious	,Gender	,Organization
	,RelatedMemberCodeOld	,CreateUserId	,CreateDateAndTime	,UserId
	,DateAndTime	,HasNotEmail	,VillaOwner	,Homephone3	,Mobile3
	,Email2	,Email3	,BirthPlace	,NationalNo	,EndDateNationalNo
	,MiritialStatusID	,WifeNo	,GeneralAssembly
FROM dbo.Members
WHERE (Member = 1)
	AND (SpecialCode IS NOT NULL)
ORDER BY expr1
	,EXPR2

Field SpecialCode found in Members Table and have values like that

006403/1 when i run query above it give me error

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value '/' to data type int.

why and how to solve this error .

What I have tried:

Conversion failed when converting the nvarchar value '/' to data type int.
Posted
Updated 4-Jun-18 18:25pm
v2

1 solution

I'm guessing, data issue? Possible one of the SpecialCode value not in ######/# format?

Here how I replicate the error.
SQL
DECLARE @SpecialCode VARCHAR(50)
SET @SpecialCode = '012345/'
SELECT CAST(CAST(RIGHT(@SpecialCode, CHARINDEX('/', @SpecialCode) - 6) AS NVARCHAR) AS INT) 

SELECT CAST(CAST(LEFT(@SpecialCode, CHARINDEX('/', @SpecialCode) - 1) AS NVARCHAR) AS INT)

Result:
Msg 245, Level 16, State 1, Line 3
Conversion failed when converting the nvarchar value '/' to data type int.

Not clear what your objective are, but if that the case, the quick work around is to replace the / with empty string

SQL
DECLARE @SpecialCode VARCHAR(50)
SET @SpecialCode = '012345/'
SELECT  CAST(CAST(LEFT(@SpecialCode, CHARINDEX('/', @SpecialCode) - 1) AS NVARCHAR) AS INT),
CAST(
	REPLACE(CAST(RIGHT(@SpecialCode, CHARINDEX('/', @SpecialCode) - 6) AS NVARCHAR),'/','') AS INT) 


Result: 12345 0
 
Share this answer
 
v2

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