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

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

Related

How to select a column with a string

This is my code:
declare #MaxPointNumber INT=499, #pointNumber INT = 5;
select ('point'+CAST(#pointNumber as varchar))
from #TempHold
And this is the result:
point5 should be the name of column, but somehow it becomes a new value in the table.
Can anyone help me understand what is going on?
As stated earlier you need dynamic sql
DECLARE #sql VARCHAR(200)
DECLARE #MaxPointNumber INT=499, #pointNumber INT = 5;
SET #sql = 'SELECT ' + ('point'+CAST(#pointNumber as varchar)) +
' from #TempHold'
EXEC (#sql)
you are selecting from Temphold. this is acting as your column name. the table you are retrieving from.
figured it out:
set #xxx=CAST(#pointNumber as varchar);
exec( 'select point'+ #xxx +' from #TempHold')

SQL query error: Conversion failed when converting the varchar value

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

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;

Conversion failed when converting the nvarchar value ... to data type int

I created the procedure listed below:
CREATE procedure getdata
(
#ID int,
#frm varchar(250),
#to varchar(250)
)
AS
BEGIN
DECLARE #SQL nvarchar(500)
set #SQL = 'select'
set #SQL = #SQL + ' EmpName, Address, Salary from Emp_Tb where 1=1 '
IF (#ID <> '' and #ID is not null)
Begin
SET #sql=#sql+' AND Emp_Id_Pk=' +#ID
End
END
print #sql
--execute (#sql)
I try to execute it using:
**execute getdata 3,'','';**
But I'm getting the following error:
Conversion failed when converting the nvarchar value 'select EmpName,
Address, Salary from Emp_Tb where 1=1 AND Emp_Id_Pk=' to data type int
Please help.
You are trying to concatenate a string and an integer.
You need to cast #ID as a string.
try:
SET #sql=#sql+' AND Emp_Id_Pk=' + CAST(#ID AS NVARCHAR(10))
Try Using
CONVERT(nvarchar(10),#ID)
This is similar to cast but is less expensive(in terms of time consumed)
I was using a KEY word for one of my columns and I solved it with brackets []
I use the latest version of SSMS or sql server management studio. I have a SQL script (in query editor) which has about 100 lines of code. This is error I got in the query:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the nvarchar value 'abcd' to data type int.
Solution - I had seen this kind of error before when I forgot to enclose a number (in varchar column) in single quotes.
As an aside, the error message is misleading. The actual error on line number 70 in the query editor and not line 2 as the error says!
don't use string concatenation to produce sql, you can use sp_executesql system stored prcedure to execute sql statement with parameters
create procedure getdata #ID int, #frm varchar(250), #to varchar(250) as
begin
declare #sql nvarchar(max), #paramDefs nvarchar(max);
set nocount on;
set #sql = N'select EmpName, Address, Salary from Emp_Tb where #id is null or Emp_Id_Pk = #id';
set #paramDefs = N'#id int';
execute sp_executesql #sql, #paramDefs, #id = #ID;
end
see sp_executesql
I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.
My invalid SQL query looked like this:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)
This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.
I changed it to:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')
And it worked.
You got this Error because you tried to convert column DataType from String to int which is
leagal if and only if
you dont have row in that table with string content inside that column
so just make sure your previously inserted Rows is compatible with the new changes
I have faced to the same problem, i deleted the constraint for the column in question and it worked for me. You can check the folder Constraints.
Capture :
You must use CONCAT and not the +
SET #sql = CONCAT(#sql,' AND Emp_Id_Pk=' ,#ID )

How do I pass a column as a parameter in Stored Procedure?

How do I pass and use the column name to retrieve a bigint variable in the actual column?
DECLARE #personID BIGINT,
DECLARE #queryString varchar(500)
Set #queryString = 'Select #personID = ' + #PersonColumnID + ' from dbo.Loss_Witness where WitnessID = #witnessID'
exec(#queryString)
Error message states "Must declare variable '#personID'." I also tried
Set #queryString = 'Select ' + #personID + ' = ' + #witnessPersonID + ' from dbo.Loss_Witness where WitnessID = #witnessID'
And got the error message "Error converting data type varchar to bigint."
Any thoughts?
You need to specify that #personID is an out parameter with the OUTPUT keyword:
DECLARE #SQL NVARCHAR(max)
SET #SQL = 'SELECT #personID = w.' + #PersonColumnID + '
FROM dbo.Loss_Witness w
WHERE w.witnessID = #witnessID '
BEGIN
EXEC sp_executesql #SQL, #personID = #personID OUTPUT, #witnessID
END
There's another example here.
Also note that there is potentially an SQL Injection security hole in your code. If you're not sanitizing #PersonColumnID then you could be in big trouble.