Converting int value to a char that is too small - sql

Try the following on MSSQL 2005:
select convert(char(2), 123)
The key here is that char(2) is too small to accept the value '123'. I would expect to see a truncation error here, but instead the value "*" is returned.
Update:
A few of the answers showed how to cast in a way that will cause an error. That's not really what I need. We have lots of code that uses a specific field that used to be declared char(2) but has since been changed to int. My goal here is to make sure that code that hasn't been converted will fall over if it encounters data that it can't handle. So we can go fix it.
Interestingly, dsolimano notes that changing the above type to nchar causes the expected error, and Justin Niessner notes that both of these are by design. Strange inconsistency given that nchar is for Unicode support, hey?
From the answers I have here, it appears that I sadly can't make the server throw the error for existing code.

Microsoft's convert/cast page seems to indicate that you can cast to nchar(2) if you want to get an error instead of * or truncation, and indeed that is what I get:
SELECT CAST(123 AS NCHAR(2))
Msg 8115, Level 16, State 2, Line 3
Arithmetic overflow error converting expression to data type nvarchar.

Scroll down the following MSDN Page:
CAST and CONVERT (Transact-SQL)
Until you get to the heading Truncating and Rounding Results
You'll see that the behavior you're seeing is the defined behavior.
If you want the truncation to occur so that you get only two digits of the number, then you can try:
select cast(convert(varchar(10), 123) as char(2))

Just cast it to a variable length string before you cast it to a string that is too small.
Select Cast( Cast( 123 as varchar(10) ) As char(2) )

SQL Server will truncate strings without a problem. So you could convert the value to a varchar first, and then cast it to char(2):
select convert(char(2), cast(123 as varchar(128))

Depends what you mean by "prevent" this from happening? What would you like to happen instead? Nothing?
DECLARE #number INT
SET #number = 123
IF(#number < 100) SELECT CONVERT(char(2), #number)

Related

Nicer way to convert string to int

Is there a nicer way to convert NVARCHAR to INT on SQL Server?
SELECT CONVERT(INT, CONVERT(FLOAT, N'5.0'))
Why do simple CONVERT or CAST cause errors?
SELECT CONVERT(INT, N'5.0')
SELECT CAST(N'5.0 AS INT)
Why do simple CONVERT or CAST cause errors?
Because the value you are trying to convert has a decimal point. And integers don't have decimal points.
You can get around this using DECIMAL as well as floating point numbers:
SELECT CONVERT(decimal(10, 0), N'5.0')
DECIMAL accepts the decimal places (even more than 1) and rounds the value to the appropriate integer, so the result can be either larger or smaller than the input.
This has the same range as integer, so it is pretty equivalent -- and you can convert back:
SELECT CONVERT(int, CONVERT(decimal(10, 0), N'5.0'))
Note that these are still subject to overflow errors, so I recommend TRY_CONVERT().
You can combine try_convert and isnull functions together. try_convert will return null when it fails to convert. And isnull will use the fallback value if the first argument is null. But a good part of it it will use first arguments datatype so end result will be an int if use the below code :
declare #text nvarchar(20) = N'5.6'
select isnull(try_convert(int,#text),convert(float,#text))
Fiddle

Showing this error "Conversion failed when converting date and/or time from character string." in SQL

My sp is
EXEC _REPORTS #StartDate=N'17-Sep-2016',
#EndDate=N'17-Sep-2016',
#CustomerID=0,
#ProductID=0,
#BranchID=0,
#NumberOfRecords=100,
#PageNo=1,
#IsBuy=1
here the region of date used in where
AND FCSB.FCBuySellDate
BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)
The reason is primarily you are getting some wrong formatted data to convert, For example
declare #StartDate nvarchar(15) = N'17-Septt-2016'
select CONVERT(datetime,#StartDate,105)
You will get this error
Conversion failed when converting date and/or time from character string.
If you get correct date you get it converted, one way to ignore this error is to do TRY_CONVERT which willl return NULL. Best way to solve this problem is to identify why it is getting wrong date as parameter and fix that.
select TRY_CONVERT(datetime,#StartDate,105)
check for null value in FCSB.FCBuySellDate. It might be cause of an error
try this
AND FCSB.FCBuySellDate BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)
AND isnull(FCSB.FCBuySellDate,'') <> ''
Also try this, convert column in datetime
AND CONVERT(datetime,FCSB.FCBuySellDate) BETWEEN CONVERT(datetime,#StartDate,105) AND CONVERT(datetime,#EndDate,105)

Convert nvarchar scientific notation value into number in SQL Server 2014

I have a column loaded into SQL Server with these nvarchar values:
ColumnName
==========
6.19e+014
.....
6.19e+014
Now, what would be the easiest way to convert this value into numbers again.
Kindly suggest. Thanks!
declare #String varchar(25)='6.19e+014'
Select cast(#String as float)
Returns 619000000000000
This will cast to FLOAT without issue:
SELECT CAST('6.19e+014' AS FLOAT)
If what you really want is the specific value that got converted to scientific notation in the first place, you'll have to go back in the process to before it got converted and fix that.
Also, try this
Select convert(numeric(15,0),ltrim(rtrim(str(column_name,15))))
from table_name

Converting a VARCHAR to NUMERIC - No Previous Post Answer Works For Me

I've read many responses to this same question, but none of the answers are working for my latest attempt at CASTing a VARCHAR to NUMERIC:
Cast(Cast(a.VARCHARFIELD as NUMERIC(20,0))as INT)
The error I get is:
The conversion of the varchar value '97264634555 ' overflowed an int column. Maximum integer value exceeded.
Unfortunately, the a.VARCHARFIELD contains accounts like 12345678999 but it also contains text or VARCHAR values like:
BALL
TWIN
12345678999
12345679000
First, you need to determine whether your value is a number. There is no ANSI standard method, but an approximation is to just see if it starts with a number.
Second, int is too small, so I would recommend a decimal format.
So something like this would work on the data you provided:
select (case when VARCHARFIELD between '0' and '99999999999999'
then cast(VARCHARFIELD as decimal(20, 0))
end)
The validation of number can be done much better in any particular database; the form given is sufficient for the data provided in the question.
EDIT:
In SQL Server, a more accurate method would be:
select (case when VARCHARFIELD NOT LIKE '%[^0-9]%'
then cast(VARCHARFIELD as decimal(20, 0))
end)

Convert numeric (contains special characters) to money

Given
declare #text varchar(4) ='3677.98*' , #text2 varchar(4) ='1245367.98%'
I want the output as follows:
3,677.98* and 1,245,367.98%
I tried below:
select convert(varchar,cast(3677.98 as money),1) --output as 3,677.98
If I try select convert(varchar,cast(3677.98* as money),1) it gives the error Incorrect syntax near the keyword 'as'.
If you want to convert a varchar to Money format, the only currency symbols it can use are in this chart, from MSDN. * and % do not qualify.
If you want to store the number amount and the special character, you will need to either store them as a varchar or use two columns, a money and a varchar.
You could write a UDF which identifies the decimal separator and works out from there, adding commas (or locale-appropriate equivalent) to the output as it goes. This won't be great for your query elapsed times, however.