Converting VARCHAR with divide operand to INT - sql

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))

Related

Multiplying 2 column values in Dynamic 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;

Conversion failed when converting '2010-10-14 12:55:13' from character string

I have created a function as below, where I pass date as varchar and it should return the value as shown below. But its throwing conversion error. please help.
CREATE FUNCTION dbo.MyFunction3(#dateValue varchar) RETURNS varchar
AS
BEGIN
DECLARE #retval varchar(30)
set #retval=FORMAT(CAST(#dateValue as datetime) - CAST('04:00' AS datetime),'yyyy-MM-dd HH:mm:ss')
RETURN #retval
END
go
Compiled successfully..
When I ran select dbo.MyFunction3('2010-10-14 12:55:13'),
Its giving an error as
Conversion failed when converting date and/or time from character string.
Please assist..
A famous pitfall is not declaring a length when specifying a varchar. When you don't define a length, it defaults to 1. This means you only send the value 2 to your function, the rest is truncated. The solution is simply to specify a length:
CREATE FUNCTION dbo.MyFunction3(#dateValue varchar(19)) RETURNS varchar(19)
create FUNCTION dbo.MyFunction3(#dateValue varchar(50)) RETURNS varchar(50)
AS
BEGIN
DECLARE #retval varchar(30)
set #retval=FORMAT(CAST(#dateValue as datetime) - CAST('04:00' AS datetime),'yyyy-MM-dd HH:mm:ss')
RETURN #retval
END
go
select dbo.MyFunction3('2010-10-14 12:55:13.000')

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 )

How to do math with GUIDs in SQL Server

I need to do some math with SQL Server GUIDs in a trigger and I'm having difficulty figuring out how to convert a uniqueidentifier to a numeric(38,0).
One potential problem: my understand is that both of these datatypes are 16-byte "integers". If I'm wrong here, please correct me.
Otherwise, how would I go about this conversion? I've tried CAST and CONVERT and keep getting Explicit conversion from data type uniqueidentifier to numeric is not allowed. as an error message whenever I try. I'd really like to not have to parse each character and do hex math in a UDF to do this.
Is this possible?
Here's my script to repro this real quick:
DECLARE #guid uniqueidentifier
SET #guid = NEWID()
DECLARE #a numeric(38,0)
SET #a = 2
PRINT CAST(#guid AS numeric(38,0)) -- fails
PRINT #guid / #a -- also fails
Unfortunately, I haven't stumbled on a conversion from a hexadecimal value in a VARCHAR to a NUMERIC short of looping through one digit at a time.
declare #GUID as UniqueIdentifier = NewId()
declare #Binary as VarBinary(64) = #GUID
declare #String as VarChar(64) = Convert( VarChar(64), #Binary, 2 )
select #GUID as 'GUID', #Binary as 'Binary', #String as 'String'