简体   繁体   中英

Conversion failed when converting the varchar value '43302001-8' to data type int

When I try to execute the following:

DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT TOP ' + CAST((:intValue) AS VARCHAR(20)) +  't_stamp, PART_NUM, ' + :Column  + ' FROM dbo.press_7_recipes_log WHERE PART_NUM = ' + CAST(:text AS VARCHAR(20))
Exec (@sqlText)

I am getting the following

error:com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the varchar value '43302001-8' to data type int.

Any help would be greatly appreciated, not sure what else is required here.

:intValue is of type int4
:text is of type string
:Column is of type string (This is pulling a specified column from the database and why I think this needed to be a dynamic query)

Tried multiple attempts at googling the issue and changing the command with the same outcome. If I change the PART_NUM in the where to a column that is of type int the code works fine, any string related column does not.

The problem is that after your preparation the query becomes: SELECT TOP 666 t_stamp, PART_NUM, ANOTHER_COLUMN FROM dbo.press_7_recipes_log WHERE PART_NUM = 43302001-8

And since 43302001-8 is an INTEGER=43301993, SQL Server converts PART_NUM column to INT, which doesn't work since it probably contains non-integers.

You need to change your dynamic query to this me thinks:

DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT TOP ' + CAST((:intValue) AS VARCHAR(20)) +  't_stamp, PART_NUM, ' + :Column  + ' FROM dbo.press_7_recipes_log WHERE PART_NUM = ''' + REPLACE(CAST(:text AS VARCHAR(20)), '''', '''''') + ''''
Exec (@sqlText)

This will change WHERE to: PART_NUM = '43302001-8'

But as others noticed, you have a lot of possibilities for SQL Injections here. So i'd probably get rid of this code and rewrite it to avoid dynamic SQL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM