SQL query error: Conversion failed when converting the varchar value - sql

I search about the error, but I only find different answers that didn't work for me.
I have this query, in SQL Server:
DECLARE #column_name varchar (25),
#data_column int,
#table_name varchar (25)
DECLARE #mySql nvarchar (MAX)
SET NOCOUNT ON;
SET #column_name = 'Excellent'
SET #table_name = 'CSAT'
SET #data_column = 10
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+') VALUES('+#data_column+')'
EXEC (#mySql)
When I execute it, it shows me this error:
Conversion failed when converting the varchar value 'INSERT INTO CSAT(Excellent) VALUES(' to data type int.
All the columns are Int and allow nulls.
I have to make a conversion or something? I appreciate your help!

#data_column is an int, so you need to convert it to varchar because you are building a string.
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+')
VALUES('+ Convert(Varchar(10), #data_column)+')'
When sql server encounters an expression that mixes strings and int, it attempts to convert the string to an int (instead of the the other way around). This is documented here: SQL Server Data Type Precedence

add some space like this
SET #mySql = 'INSERT INTO '+#table_name+' ('+convert(varchar(50),#column_name)+') VALUES('+#data_column+')'

The sql is trying to make a sum of your string on line:
SET #mySql = 'INSERT INTO '+#table_name+'('+#column_name+') VALUES('+#data_column+')'
Change the #data_column parameter from int to varchar or use a CONCAT function to create your SQL command:
SET #mySql = CONCAT('INSERT INTO ',#table_name,' (',#column_name,') VALUES(',#data_column,')')

You should use Parametrised Query to do this, Also use appropriate datatype for object names...
something like this....
SET NOCOUNT ON;
DECLARE #column_name SYSNAME
,#data_column INT
,#table_name SYSNAME
,#mySql NVARCHAR(MAX);
SET #column_name = 'Excellent'
SET #table_name = 'CSAT'
SET #data_column = 10
SET #mySql = N' INSERT INTO '+ QUOTENAME(#table_name)
+ N' ('+ QUOTENAME(#column_name) +') '
+ N' VALUES( #data_column )'
Exec sp_executesql #mySql
,N'#data_column INT'
,#data_column

Related

Conversion failed when converting the varchar value 'njtestagt' to data type int

I am struggling with few days with the issue.
I can't figure out how to fix it.
Declare #DbName varchar (50)
Declare #AgencyID varchar(50)
set #DbName='UPC_qat_NewBusiness'
set #AgencyID='1234568'
SET #Query = N'DELETE FROM ' + #DbName + '.dbo.PMSPAG00 WHERE AGNMMCO IN (select MasterCompanyId from ISLocation isLoc join ISAgencyLocation IsAg on IsAg.LocationIndexNbr=isLoc.LocationIndexNbr where AgencyId='+#AgencyID+') and AGNMNBR='+#AgencyID
Execute(#Query)
Why I am getting this error :
"Conversion failed when converting the varchar value 'njtestagt' to data type int"
There is nothing in it or that value in the database records.
Please help me anyone.
Thanks in Advance.
Change the set statement of agencyid
set #AgencyID='''1234568'''
or
SET #DbName='UPC_qat_NewBusiness'
SET #AgencyID='1234568'
SET #Query = N'DELETE FROM ' + #DbName
+ '.dbo.PMSPAG00 WHERE AGNMMCO IN (select MasterCompanyId from ISLocation isLoc
join ISAgencyLocation IsAg on IsAg.LocationIndexNbr=isLoc.LocationIndexNbr
where AgencyId='''+ #AgencyID + ''') and AGNMNBR=''' + #AgencyID+ '''' --here
Since the Agencyid is a varchar column the values passed to that column should be enclosed with single quotes.
Note : Use print statement to debug the dynamic query

Difficulty using a CHAR in Dynamic SQL

I'm trying to pass in #accountType, a char value to a stored procedure that uses dynamic SQL. It is declared as char(4) in the procedure. The current error is Incorrect syntax near 'D' if I try to change it I get invalid column: D.
I cannot figure out how dynamic SQL wants me to indicate that the variable is a char. I've tried it many ways, here is the most recent:
set #q = 'Update ' + #statementTable +
' SET Account = '+ #padding + #accountNumber +
' WHERE ClosingDate BETWEEN CAST('''+CONVERT(VARCHAR(20),#proc_dateStart)+''' AS DATE) AND CAST('''+CONVERT(VARCHAR(20),#proc_dateEnd)+''' AS DATE)' +
' AND AccountType =' + ''''+ #accountType +''''
The value is coming from my C# code exactly like this: D
No single quotes or anything around the letter. Any ideas? I'm more than a bit stuck with this.
Something like this, you need to have the parameters actually within the string statement, then when you execute sp_executesql, you then pass what each of those parameters are.
DECLARE #q VARCHAR(MAX)
DECLARE #statementTable VARCHAR(50)
DECLARE #padding VARCHAR(50)
DECLARE #accountNumber CHAR(4)
DECLARE #proc_dateStart VARCHAR(50)
DECLARE #proc_dateEnd VARCHAR(50)
DECLARE #accountType VARCHAR(50)
SET #q = 'Update #statementTable
SET Account = ''#accountNumber''
WHERE ClosingDate BETWEEN CAST(''+CONVERT(VARCHAR(20),#proc_dateStart)+'' AS DATE) AND CAST(''+CONVERT(VARCHAR(20),#proc_dateEnd)+'' AS DATE)
AND AccountType = ''#accountType'''
EXEC sys.sp_executesql #sql, N'#statementTable VARCHAR(50),#accountNumber CHAR(4),#proc_dateStart VARCHAR(50), #proc_dateEnd VARCHAR(50),#accountType VARCHAR(50)',
#statementTable,#accountNumber,#proc_dateStart,#proc_dateEnd,#accountType;

CAST and CONVERT in T-SQL

Is it posible to CAST or CONVERT with string data type (method that takes data type parametar as string), something like:
CAST('11' AS 'int')
but not
CAST('11' AS int)
No. There are many places in T-SQL where it wants, specifically, a name given to it - not a string, nor a variable containing a name.
If you want to use dynamic sql, this should get you started:
DECLARE #datatype varchar(20)
DECLARE #sql varchar(4000)
SELECT #datatype = 'int'
SELECT #sql = 'PRINT CAST(''11'' AS '+#datatype+')'
exec (#sql)
Depending on what you exactly want/need you should read The Curse and Blessings of Dynamic SQL, especially the parts about sp_executesql
You would have to use dynamic sql to achieve that:
DECLARE #type VARCHAR(10) = 'int'
DECLARE #value VARCHAR(10) = '11'
DECLARE #sql VARCHAR(MAX)
SET #sql = 'SELECT CAST(' + #value + ' AS ' + #type + ')'
EXEC (#sql)
SQLFiddle DEMO with INT
// with datetime

Specifying Column Name As A Parameter in SELECT statement?

I need to do something like this, but it always fails with 'Error converting data type varchar to int':
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
SET #intParam = SELECT #ColName FROM myTable
How do I accomplish something like this? I can see the problem is that the SELECT statement simply returns the column name as a string, but I am not sure how to fix that. I am using SQL Server 2008R2.
You need to use dynamic sql:
build your dynamic SQL query (take a look at #SQL variable in sample below)
use output parameter to get value back from dynamic sql (take a look at #intParam and #intParam_out in sample below)
execute dynamic sql using sp_executesql
DECLARE #intParam INT
DECLARE #ColName VARCHAR(64)
SET #ColName='intcolumn'
DECLARE #SQL NVARCHAR(1000)
SET #SQL = 'SELECT #intParam_out = ' + #ColName + ' FROM myTable'
exec sp_executesql #SQL, N'#intParam_out int OUTPUT', #intParam_out = #intParam OUTPUT
Use Cast:
SET #intParam = SELECT cast(#ColName as int) FROM myTable

Using variable inside dynamic SQL

I have the below SQL..What I am trying to do is use the Parameter defined at the stored procedure level inside dynamic SQL:
CREATE PROCEDURE [dbo].[Test]
(#DealID NVARCHAR(500),
#OUTPUT NVARCHAR(MAX) OUTPUT,
#FeeType CHAR(1)
) -- I want to use this parameter inside dynamic SQL query
AS
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(MAX)
BEGIN
SET #exec_str = N'DECLARE #ParmDefinition NVARCHAR(500)
SELECT * FROM #FeeType' --This is where I want to use the variable
DECLARE #ParamDefinition nvarchar(max)
SET #ParamDefinition = N'#OUTPUT NVARCHAR(MAX) OUTPUT'
EXEC sp_executesql #exec_str, #ParamDefinition
Can someone please tell me how to do it?
Thanks
In SQL Server Identifiers can't be parameterized.
Since you are using dynamic SQL anyway, you can do something like this:
SET #exec_str= N'Select * from '+ #FeeType
EXEC(#exec_str)
However, this is vulnerable to SQL injection attacks. To reduce the risk to minimum you should check first that such a table name exists, and I would also use quotename just to be on the safe side:
IF EXISTS
(
SELECT 1
FROM Information_Schema.Tables
WHERE TABLE_NAME = #FeeType
)
BEGIN
SET #exec_str= N'Select * from '+ QUOTENAME(#FeeType)
EXEC(#exec_str)
END