Multiplying 2 column values in Dynamic SQL - sql

DECLARE updatesql nvarchar(MAX)
SET #updatesql = N'update '+ #TableName +' SET
Total_Revenue=CAST(COALESCE(Total_Hours,0) AS FLOAT) * CAST(COALESCE(Rate,0) AS FLOAT)
where associate_ID='+ #associateId
EXECUTE (#updatesql)
This is giving the error message: Conversion failed when converting the varchar value '27.72081' to data type int.

You're casting numeric values to VARCHAR inside your dynamic statement. Remove the CASTs and it should be good.
Your resulting statement should read something like this when printed:
update table1 SET
Total_Revenue=COALESCE(Total_Hours,0) * COALESCE(Rate,0)
where associate_ID=1;
You should also use 0.0 in your COALESCE so that your formula multiplies a decimal type with another decimal type. As is you are multiplying a decimail and an INT. (I assume that Total_Hours and/or Rate is a decimal type based on the value in the error message you provided.)
Update after question edit:
Your CAST is in the wrong place. You can't COALESCE a VARCHAR and an INT. Your statement should now look something like this:
update table1 SET
Total_Revenue=COALESCE(CAST(Total_Hours AS FLOAT),0.0) * COALESCE(CAST(Rate AS FLOAT),0.0)
where associate_ID=1;

This is probably because of associate_id. Pass it in as a parameter:
SET #updatesql = N'
update '+ #TableName +'
SET Total_Revenue=CAST(COALESCE(Total_Hours,0) AS FLOAT) * CAST(COALESCE(Rate,0) AS FLOAT)
WHERE associate_ID = #associateId';
EXEC sp_executesql #updatesql, N'#associate_id int', #associate_id=#associate_id;

Related

Converting VARCHAR with divide operand to INT

I have a VARCHAR which will return the value something like this '40/4'.
Is there a way to convert this VARCHAR to an INT? I tried casting but it is not working.
Sample:
Declare #test varchar(6) = '40/4'
Select cast (#test as int) * 4
Expected: 40
Actual:
Conversion failed when converting the varchar value '40/4' to data type int
Note: The value 40/4 is something coming from a message saved in one of the systems and that cannot be changed.
Appreciate any help on this.
CAST/CONVERT won't work because '40/4' is not a number, its a string that happens to represent a mathematical expression.
One way to solve this is by using dynamic SQL e.g.
declare #test varchar(6) = '40/4';
declare #sql nvarchar(max) = 'select ' + #test + ' * 4';
exec sp_executesql #sql;
Returns: 40
If you're just after the first valid integer value before the / (or just the first non-numeric character) you can try
Declare #test varchar(6) = '40/4'
Select Try_Convert(int,Left(#test,IsNull(NullIf(PatIndex('%[^0-9]%',#test),0),6)-1))

Rounding a decimal value with dynamic variable

I need to round a value of a column in table A based on another column in table B in a SQL function.
DECLARE #currencyround INT
SELECT #currencyround = ISNULL(currencyround, 2)
FROM dbo.PRTL_currencySettings
When I put value of #currencyround directly in the query like the following, it's working fine:
SELECT
CAST(POS.BALANCE AS DECIMAL(18, 2)) AS DBAmount
FROM
dbo.POS_SALES POS
When I put value of #currencyround like the following, it's showing error:
Incorrect syntax near '#currencyround'.
SELECT
CAST(POS.BALANCE AS DECIMAL(18, #currencyround)) AS DBAmount
FROM
dbo.POS_SALES POS
If you need specific metadata you could use dynamic SQL:
DECLARE #currencyround int;
SELECT #currencyround=ISNULL(currencyround,2) FROM dbo.PRTL_currencySettings;
DECLARE #sql NVARCHAR(MAX) =
N'select CAST(POS.BALANCE AS DECIMAL(18,<currencyround>)) AS DBAmount
FROM dbo.POS_SALES POS';
SET #sql = REPLACE(#sql, '<currencyround>', #currencyround);
EXEC(#sql);
But personally I would not write such code. I would rather format the number in the application layer.
What do you not understand? Type definitions don't allow variables. You could do this with dynamic SQL but that seems like overkill.
If you care about what how the variable is output, use str() or format() to create the format that you want.
If you need to round the values, then how about this:
ROUND(POS.BALANCE, #currencyround)

Error converting data type varchar to numeric and overflow

declare #Commission decimal(18,2)
select #Commission=percentage from Commission
declare #qry varchar(Max)
set #qry='select 5 +'+#Commission +''
EXEC(#qry)
Here
The Error converting data type varchar to numeric.
Don't pass values into dynamic SQL as strings. Instead, learn to use sp_executesql:
declare #Commission decimal(18, 2);
select #Commission = percentage
from Commission;
declare #qry varchar(Max);
set #qry='select 5 + #Commission';
exec sp_executesql #qry, 'N#Commission decimal(18, 2)', #Commission=#Commission;
SQL Server's implicit conversion rules makes it attempt to implicitly convert your varchar to decimal. You need to explicitly convert the decimal to varchar:
set #qry='select 5 +'+ CAST(#FranchiseeCommission as varchar(20))
set #qry='select 5 +'+convert(nvarchar(max),#FranchiseeCommission)+''
Try it like this:
SET #qry='select 5 +'+CAST(#FranchiseeCommission AS varchar(30))+''
Since your variable is a decimal, you have to cast it as varchar in order to combine it with your string.
There is always concat() if 2012+
set #qry=concat('select 5 +',#Commission)

Convert int in string to integers in T-SQL

I need to convert string to integers, but I'm getting a type error.
declare #stringinteger nvarchar(255) null;
set #stringinteger='1,2,3,4'
select *
from user
where id in (#stringinteger)
The error I get:
Conversion failed when converting the nvarchar value '1,2,3,4' to data type int
You have two methods to handle this, dynamic SQL and splitting the string.
For the latter, you can use string_split() (introduced in SQL Server 2016) or a similar function (they are all over the web, google "string split sql server"):
select *
from user
where id in (select cast(value as int) from string_split(#stringinteger, ',')) ;
The dynamic SQL looks like:
declare #stringinteger nvarchar(255) null;
set #stringinteger = '1,2,3,4';
declare #sql nvarchar(max);
set 'select *
from user
where id in (#stringinteger)';
set #sql = replace(#sql, '#stringinteger', #stringinteger);
exec sp_executesql #sql;
Note that in SQL Server, you should always provide a length for character types. If you leave it out, then the default varies by context -- and your code may not do what you expect.

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 )