Converting data types in SQL Server - sql

I need to change some data types. I have tried using the CAST keyword, but it is not fixing the issue. Any suggestions on how to re-write these two lines with CAST statements?
Data loss might occur when casting from VarChar(100) to VarChar(20).
Code:
SELECT TOP 1 #variableId = variableId
FROM #tempTable
Data loss might occur when casting from NVarChar(512) to NVarChar.
Code:
SELECT myVariable
FROM tableName
I tried doing something like the following, but still produces an error:
CAST((myVariable) as nvarchar)

CAST is used for converting between data types. It sounds more like you should use LEFT instead:
SELECT TOP 1 #variableId = LEFT(variableId,20)
FROM #tempTable
This won't give you any warning as the system assumes you already know you're going to lose the right 80 characters.

For using CONVERT instead of CAST:
CONVERT(nvarchar, myVariable)
Is a valid syntax and also:
CONVERT(varchar(20), myVariable)
But for getting a part of a string we use SUBSTRING() or LEFT() or RIGHT() functions like this:
SUBSTRING( value_expression , start_expression , length_expression )
Returns part of a character, binary, text, or image expression.
LEFT ( character_expression , integer_expression )
Returns the left part of a character string with the specified number of characters.
RIGHT ( character_expression , integer_expression )
Returns the right part of a character string with the specified number of characters.

Related

Error when aggregating due to conversion from varchar to bigint

Situation:
I want to aggregate a value from a table but i get the following error :
Error converting data type varchar to big int.
I've been reading countless of different solutions online but they don't seem to solve it.
Current query;
So based on the error message, i simply added the CAST function but it still doesnt work.
SELECT
base.target_date AS target_date
, base.game_id AS game_id
, base.device AS device
, ISNULL(CAST(SUM(use_point.point) AS bigint),0) AS result
FROM
cte AS base
LEFT JOIN cte2 AS use_point
ON base.target_date = use_point.target_date
AND base.game_id = use_point.device
AND base.device = use_point.device
GROUP BY
base.target_date
, base.device
, base.game_id
WITH ROLLUP
GO
I'm presuming that use_point.point is a VARCHAR, in which case simply change where you put your CAST statement:
, ISNULL(SUM(CAST(use_point.point AS bigint)), 0) AS result
Note that the CAST now takes place before the SUM.
Use TRY_CAST() instead. And it needs to be an argument to the SUM():
SELECT base.target_date, base.game_id, base.device,
COALESCE(SUM(TRY_CAST(use_point.point as bigint)), 0) as result
FROM . . .
Note that your column aliases are redundant, because you are assigning the default aliases.
You should also fix the data. Don't store numeric values as strings. To find the bad data, you can use:
select points
from use_points
where try_convert(points as bigint) is null and
points is not null;

When trying to convert column data type NVARCHAR to INT getting error

When trying to convert column data type NAVCHAR to INT receiving error. Simple code below:
SELECT [phone], FORMAT(CAST(PHONE AS int),'(000)-000-0000)')
FROM Sales.Customers
Your query should be something like this:
SELECT [phone], FORMAT(CAST(REPLACE([phone],'-','')AS INT), '(000)-000-0000)')
FROM Sales.Customers
So if there's an invalid character to be converted to in (for this scenario dash is the one to be replaced), it will replace it with blank then format it with the format you want.
ex: '030-3456789'
this will become (030)-345-6789
Seems like you have rows with phone numbers stored as strings, which can't be converted to an int. To find out which, execute:
SELECT *
FROM Sales.Customers
WHERE ISNUMERIC(phone) = 0;
HTH
I would suggest using TRY_CAST():
SELECT [phone],
FORMAT(TRY_CAST(PHONE AS int), '(000)-000-0000)')
FROM Sales.Customers;
This returns NULL if the value cannot be converted -- which is better than getting an error.

SQL Character extraction

I would like to extract everything on the right side of the "underscore". I want to get 0000. I tried
select right('M_0000',charindex('_','M_0000')-1)
but end up with just 0. Why?
Since you are using CHARINDEX, i assume you are using SQL-SERVER.
So in your second field you should say how many characters you want. You can achieve that by doing LEN('M_0000') - charindex('_') :
select right('M_0000',len('M_0000') - charindex('_','M_0000'))
sqlfiddle demo
You were ending up with just one 0 because charindex('_') is 1, and you are telling the RIGHT function that you want 1 char from the right.
From the docs:
RIGHT ( character_expression , integer_expression )
character_expression Is an expression of character or binary data.
character_expression can be a constant, variable, or column.
character_expression can be of any data type, except text or ntext,
that can be implicitly converted to varchar or nvarchar. Otherwise,
use the CAST function to explicitly convert character_expression.
integer_expression Is a positive integer that specifies how many
characters of character_expression will be returned. If
integer_expression is negative, an error is returned. If
integer_expression is type bigint and contains a large value,
character_expression must be of a large data type such as
varchar(max).
You can use SUBSTRING instead of RIGHT:
select SUBSTRING('M_0000',charindex('_','M_0000')+1, LEN('M_0000')) // start at character n + 1

how to convert different datatypes to int in sql

I have a nvarchar(200) column in a table that contains a mix of integers (as strings) and non-integer strings and symbols also. E.g. Some sample data :-
Excuse me for my typing in my initial post I mentioned varchar(200) but in fact it is 'nvarchar(200)'
02
0
.../
125
00125
/2009
1000
0002589
000.00125
Marathi numbers like & letters
how can I order this Column?
You can use CAST to convert a varchar to an INT given that varchar is holding a proper number.
SELECT CAST(varCharCol as Int)
E.g.
col1 as Varchar(10)
col1 = '100' converting to INT will be successufl
but if col1 = '100 xyz' will be unsucessful in the process.
Looking at your string you may have to use number of LTRIM, REPLACE to get hold of the digits or using a regex to get comma separated numbers. That too it's not very clear how your original string looks like.
References.
Many DBMS have CAST() functions where you can convert one datatype to another.
For MySQL have a look at this site
You can Use CAST and Convert to convert string type value to int type. but be sure the value should numeric.
select convert(int,'123')
select CAST('123' as int)
You can use this query
SELECT CASE
WHEN ISNUMERIC(colName)=1 THEN ROUND(colName, 0)
ELSE 0 END AS [colName]
FROM tblName

Converting a String to HEX in SQL

I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral
Here is the select I am using now:
SELECT SomeStringColumn from SomeTable
Here is the select I would like to use:
SELECT hex( SomeStringColumn ) from SomeTable
Unfortunately nothing is that simple... Informix gives me that message:
Character to numeric conversion error
Any idea?
Can you use Cast and the fn_varbintohexstr?
SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary))
FROM SomeTable
I'm not sure if you have that function in your database system, it is in MS-SQL.
I just tried it in my SQL server MMC on one of my tables:
SELECT master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:
SELECT hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM Customer
The following works in Sql 2005.
select convert(varbinary, SomeStringColumn) from SomeTable
Try this:
select convert(varbinary, '0xa3c0', 1)
The hex number needs to have an even number of digits. To get around that, try:
select convert(varbinary, '0x' + RIGHT('00000000' + REPLACE('0xa3c','0x',''), 8), 1)
If it is possible for you to do this in the database client in code it might be easier.
Otherwise the error probably means that the built in hex function can't work with your values as you expect. I would double check the input value is trimmed and in the format first, it might be that simple. Then I would consult the database documentation that describes the hex function and see what its expected input would be and compare that to some of your values and find out what the difference is and how to change your values to match that of the expected input.
A simple google search for "informix hex function" brought up the first result page with the sentence: "Must be a literal integer or some other expression that returns an integer". If your data type is a string, first convert the string to an integer. It looks like at first glance you do something with the cast function (I am not sure about this).
select hex(cast SomeStringColumn as int)) from SomeTable
what about:
declare #hexstring varchar(max);
set #hexstring = 'E0F0C0';
select cast('' as xml).value('xs:hexBinary( substring(sql:variable("#hexstring"), sql:column("t.pos")) )', 'varbinary(max)')
from (select case substring(#hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)
I saw this here:
http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx
Sorrry, that work only on >MS SQL 2005
OLD Post but in my case I also had to remove the 0x part of the hex so I used the below code. (I'm using MS SQL)
convert(varchar, convert(Varbinary(MAX), YOURSTRING),2)
SUBSTRING(CONVERT(varbinary,Addr1 ) ,1,1) as Expr1