Converting varchar to int, SQL Server - sql-server

I have code like this:
CREATE FUNCTION gantistok (#id VARCHAR(8),
#id_t INT)
RETURNS INT
BEGIN
DECLARE #tahu INT,
#tempe INT,
#hasil INT;
SELECT #tahu = CONVERT(INT, stok)
FROM barang
WHERE id_barang = #id;
SELECT #tempe = CONVERT(INT, jumlah)
FROM det_trans
WHERE id_det_trans = #id_t;
SET #hasil = #tahu - #tempe;
RETURN #hasil
END
Why doesn't it work? I am getting this error:
Msg 402, Level 16, State 1, Procedure gantistok, Line 5
The data types text and varchar are incompatible in the equal to operator.

you are using wrong syntax
it should be
CONVERT(expr,type)
and type must be SIGNED [INTEGER]
REFERENCE

MySQL? SQL Server? which one?
What is type of id_barang stok for table barang?
Guessing the problem expression is id_barang=#id
The SQL Server convert() function does not allow convert TEXT to int(INT4).

problem is on id_barang = #id.
id_barang contains a value that RDBMS is not able to convert to integer.
id_barang is a varchar.
So if you can't convert id_barang to integer, then you have to convert #id to varchar in the query:
SELECT #tahu = CONVERT(INT, stok)
FROM barang
WHERE id_barang = CONVERT(varchar(50), #id);
I'm using varchar(50) because I don't know what kind of varchar exactly id_barang is.
I would suggest to always do it this way.
Even if id_barang would not contain non-integer values at the moment...it's still a text column!
Someone could insert a non-integer value anytime, so I would always make sure that my queries will work in this case as well.

Related

SQL Server - error converting data type nvarchar to float

I am inserting table A to table B. The problematic column looks like -$25.2. I first replaced the $ and tried insert. Got this error
Error converting data type nvarchar to float.
I then checked by
SELECT *
FROM B
WHERE ISNUMERIC([Col Name]) <> 1
and no results were returned.
This is odd. It is supposed to return something.
What should I check next?
I also tried something like
CAST(REPLACE([Col Name], '-$', '') AS FLOAT)
Try using this
DECLARE #Text nvarchar(100)
SET #Text = '-$1234.567'
SET #Text = Replace(#Text,'$', '')
Select CONVERT(float, #Text) AS ColumnValue
Select ABS(CONVERT(float, #Text)) AS ColumnValue
While the 'money' data type isn't great for doing calculations, in this scenario you can use it as an intermediary.
declare #a nvarchar(10)
set #a = '-$25.2'
select
#a,
cast(cast(#a as money) as float)
Only use this though if your data only goes to a max of 4 decimal places, otherwise you will lose precision in the conversion.

t-sql view conversion failed when filtering on converted column

I am trying to create view by filtering some table, and include some converted to different type column into select list. View filter excludes from result set rows in which this column can not be converted to that type. Then I select rows from this view and filter rows using this converted column. And I always get error Conversion failed when converting the nvarchar value '2aaa' to data type int
SQL Fiddle
MS SQL Server 2008 Schema Setup:
create table _tmp_aaa (id int identity(1, 1), value nvarchar(max) not null)
go
insert _tmp_aaa (value) values ('1111'), ('11'), ('2aaa')
go
create view _tmp_v_aaa
as
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
go
Query 1:
select * from _tmp_v_aaa where value = 11
Are there any workarounds?
Add to your view ISNUMERIC to check if string is numeric value:
CREATE VIEW _tmp_v_aaa
AS
SELECT
id,
[value] = CAST((CASE WHEN ISNUMERIC([value]) = 1 THEN [value] ELSE NULL END) AS INT)
FROM _tmp_aaa
WHERE [value] LIKE '1%'
AND ISNUMERIC([value]) = 1
I tried some tricks... Obviously the optimizer tries to hand down your where criterium where it is not yet tranformed. This is one problem to be solved with a. multi-statement function. Their biggest disadvantage is the advantage in this case: the optimizer will not look into it, but just take their result "as is":
create function fn_tmp_v_aaa()
returns #tbl table(id INT, value INT)
as
BEGIN
INSERT INTO #tbl
select id, cast(value as int) as value from _tmp_aaa where value like '1%'
RETURN;
END
select * from dbo.fn_tmp_v_aaa() where value=11;
If you look at the execution plan , predicates are passed down to the table something like....
And your query gets translated to something like .....
select id, cast(value as int) as value
from tmp_aaa
where CONVERT(INT, value,0) like '1%'
AND CONVERT(INT, value,0) = CONVERT(INT, 11,0)
Now if you run this query you will get the same error you get when you query against the view.
Conversion failed when converting the nvarchar value '2aaa' to data type int.
When the predicate CONVERT(INT, value,0) like '1%' is converted , you have INT on one side of the expressions and varchar on another, INT being the higher precedence, sql server tries to convert whole expression to INT and fails hence the error message.

Short guid in SQL Server / converting from a character string to uniqueidentifier

I need to create a column witch will contain short guid. So I found out something like this:
alter table [dbo].[Table]
add InC UNIQUEIDENTIFIER not null default LEFT(NEWID(),6)
But I get the error:
Conversion failed when converting from a character string to uniqueidentifier.
I've been trying
LEFT(CONVERT(varchar(36),NEWID()),6)
and
CONVERT(UNIQUEIDENTIFIER,LEFT(CONVERT(varchar(36),NEWID()),6))
But I am still getting the same error.
There is no such thing as "short guid". Guid, or uniqueidentifier is a 16 byte data type. You can read about it in MSDN. It means that the length must always be 16 bytes and you cannot use 6 characters as you are trying to do.
In the same MSDN article you can find description how you can initialize this type:
A column or local variable of uniqueidentifier data type can be
initialized to a value in the following ways:
By using the NEWID function.
By converting from a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a
hexadecimal digit in the range 0-9 or a-f. For example,
6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier
value.
In your case you are trying to convert only 6 characters to uniqueidentifier which obviously fails.
If you want to use just 6 characters, just use varchar(6):
alter table [dbo].[Table]
add InC varchar(6) not null default LEFT(NEWID(),6)
Keep in mind that in this case this guid is not guaranteed to be unique.
Using CRYPT_GEN_RANDOM instead of NEWID can improve random distribution of the string.
SELECT LEFT(CAST(CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER) AS VARCHAR(50)), 6)
I just made this one since I couldn't find a good answer on the internet.
Please keep in mind this is a 64 bit representation of a 128bit value, so it has twice the collision possibilities that a real GUID would have. Does not handle 0.
Function takes a NEWID value: 6A10A273-4561-40D8-8D36-4D3B37E4A19C
and shortens it to : 7341xIlZseT
DECLARE #myid uniqueidentifier= NEWID()
select #myid
DECLARE #bigintdata BIGINT = cast(cast(reverse(NEWID()) as varbinary(max)) as bigint)
DECLARE #charSet VARCHAR(70) = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE #cBase int = LEN(#charSet)
DECLARE #sUID varchar(22) = ''
DECLARE #x int
WHILE (#bigintdata <> 0)
BEGIN
SET #x = CAST(#bigintdata % #cBase as INT) + 1
SET #bigintdata = #bigintdata / #cBase
SET #sUID = SUBSTRING(#charSet, #x, 1) + #sUID;
END
SELECT #sUID

When using ISNULL, you can potentially return 2 different types

Given the following example:
declare #t1 AS VARCHAR(10)
SET #t1 = 'asdf'
SELECT ISNULL(#t1, 0) AS test1
Now if #t1 was NULL, the call to ISNULL would return 0 which is an INT.
So this means you have 2 potential data types being return for the same column correct?
This will work fine Sql server does am implicit Conversion and converts 0 into string '0' because of the datatype of the column being returned.
DECLARE #Test_TABLE TABLE(Column1 VARCHAR(10))
INSERT INTO #Test_TABLE VALUES
('ALPHA'),(NULL),('Beta'),('Gemma')
SELECT ISNULL(Column1, 0)
FROM #Test_TABLE
This will throw an error as when sql server tries to convert to the datatype of the column which is INT it fails and it throws an error
DECLARE #Test_TABLE1 TABLE(Column1 INT)
INSERT INTO #Test_TABLE1 VALUES
(1),(NULL),(2),(3)
SELECT ISNULL(Column1, 'Is null')
FROM #Test_TABLE1
Msg 245, Level 16, State 1, Line 5 Conversion failed when converting
the varchar value 'Is null' to data type int.
Your can see one datatype takes precedence on other and only One data type is returned not two :)

mssql convert varchar to float

I have a field value productlength of 0.123. This is from a view and has a data type of varchar.
I need to convert it to a float or numeric value so as o perform math comparisons.
convert(float,productlength)
and
cast(productlength as float) both do not work.
error varchar cant be converted to float or somethiing liek that.
From what I have read varchar can simply not be converted to a numeric string?
Any clever ways around this?
You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:
declare #thing varchar(100)
select #thing = '122.332'
--This returns 1 since it is numeric.
select isnumeric(#thing)
--This converts just fine.
select convert(float,#thing)
select #thing = '122.332.'
--This returns 0 since it is not numeric.
select isnumeric(#thing)
--This convert throws.
select convert(float,#thing)
Use
Try_convert(float,[Value])
See
https://raresql.com/2013/04/26/sql-server-how-to-convert-varchar-to-float/
DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE #INPUT VARCHAR(5) = '0.12',#INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, #INPUT) YOUR_QUERY ,
case when isnumeric(#INPUT_1)=1 THEN CONVERT(float, #INPUT_1) ELSE **#INPUT_1** END AS YOUR_QUERY_ANSWERED
as #INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.

Resources