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.
Related
See I have a COBOL column like this
05 AMOUNT PIC 999V99.
Here the V means decimal is implied. So value 123.45 will be represented as 12345
In order to convert it back to decimal(5,2) in Netezza, I tried the following
CAST('12345' AS DECIMAL(5,2)) --This will cause overflow, of course
CAST('12345' AS DECIMAL(5))/100 --Works, but looks awkward
Does any one know a better way to convert '12345' back to decimal(5,2) in Netezza?
Thanks
I use the method of converting it to pack decimal and then to numeric type.
I noticed an extra character is needed when converting to PACKED DECIMAL. The extra character can be any character.
Prefix TOOLKIT.SQLEXT. is where our extension function installed.
SELECT TOOLKIT.SQLEXT.PACKEDDECIMAL2STR(TOOLKIT.SQLEXT.NUM2PACKEDDEC('12345'||' ') ,2)::NUMERIC(5,2);
Result:
123.45
SELECT TOOLKIT.SQLEXT.PACKEDDECIMAL2STR(TOOLKIT.SQLEXT.NUM2PACKEDDEC('-12345'||' ') ,2)::NUMERIC(5,2);
Result:
-123.45
Try this:
select cast(substr(a.field,1,3)||'.'||substr(a.field,4,2) AS DECIMAL(5,2))
from (select '12345' as field) a
I am using Sybase and I am doing a select which returns me a column called "iftype", but its type is int and I need to convert into varchar. When I try to do the select without the convert function I get this error:
Error code 257, SQL state 37000: Implicit conversion from datatype 'VARCHAR' to 'INT' is not allowed. Use the CONVERT function to run this query.
I dont know how to implement the function CONVERT. Can anyone help me, please ?
Use the convert function.
SELECT CONVERT(varchar(10), field_name) FROM table_name
Use the STR function:
SELECT STR(field_name) FROM table_name
Arguments
float_expression
Is an expression of approximate numeric (float) data type with a decimal point.
length
Is the total length. This includes decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point. decimal must be less than or equal to 16. If decimal is more than 16 then the result is truncated to sixteen places to the right of the decimal point.
source: https://msdn.microsoft.com/en-us/library/ms189527.aspx
You can use CAST function:
SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name
Actually you don't need to use STR Or Convert. Just select 'xxx'+LTRIM(ColumnName) does the job.
Possibly, LTRIM uses Convert or STR under the hood.
LTRIM also removes need for providing length. It seems to be working for integer or float without worry of truncation.
SELECT LTRIM(ColumnName) FROM TableName
also, LTRIM is better than STR as
SELECT STR(1234567890.123)
gives 1234567890
whereas
SELECT LTRIM(1234567890.123)
gives 1234567890.123
SELECT Cast(Cast([field_name] AS BIGINT) AS NVARCHAR(255))
FROM table_name
CONVERT(DATA_TYPE , Your_Column) is the syntax for CONVERT method in SQL. From this convert function we can convert the data of the Column which is on the right side of the comma (,) to the data type in the left side of the comma (,) Please see below example.
SELECT CONVERT (VARCHAR(10), ColumnName) FROM TableName
I've got a column in my database which contains a price, stored as a varchar(10). The format that I need to pull it out as has a comma, but no decimal. So, if the price is 1500.00121, it should come out as "1,500", with comma intact. So here is what I have so far:
CONVERT(varchar, CAST(p.Price1 AS money), 1)
This still has the decimal place to ".xx" in it. How can I remove the decimal and trailing numbers while retaining the comma?
Why not stored it in Decimal(10,2) datatype? It's much better than storing it in VARCHAR since you don't have extra casting to another datatype.
You can use CAST and ROUND function:
SELECT ROUND(CAST('1500.00121' AS DECIMAL(10,4)), 0, 1)
That's it. The CAST function converts datatype to another datatype. The ROUND function returns a numeric value, rounded to the specified length or precision.
The original syntax for ROUND is
ROUND ( numeric_expression , length [ ,function ] )
Where Function parameter is the type of operation to perform. Function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
SQLFiddle Demo
ROUND (MSDN)
Decimal (MSDN)
I hope it will work
declare #q money = 1500.123
select parsename(convert(varchar,convert(money,#q), 1),2)
No sql server on hand but Something like
Declare #correctlyTyped Money
Set #correctlyTyped = Convert(Money, SomeBadlyTypedField)
Select
Substring(#correctlyTyped,0,DataLength(#correctlyTyped) - CharIndex('.',#correctlyTyped ))
Convert it to money, then select everything up to the decimal point.
Note this is relying on the locale / collation of the data. In mainland Europe for instance, , is the decimal separator and . is the thousand separator.
I have a question that bothers me. How can i convert a varchar to number when inside the varchar value consists of alphabets.
For my varchar price column values:
14dollars10cents
15dollars20cents
By converting it to varchar to number price column, the values should be:
1410
1520
I know that if the varchar does not consists any alphabets, it can auto convert by"
SELECT CONVERT(INT, PRICE) FROM Table
Is there any way to get rid of the alphabets in the middle as I would like to do mathematical function on it.
Updated attempt of putting fixed point number in:
SELECT CAST (Replace(REPLACE(PRICE, 'dollars', '.'),'cents','') AS Number(4,2)))
FROM TEST;
Thanks
You could just use REGEXP_REPLACE to remove all non digit characters:
SELECT REGEXP_REPLACE(price, '[^[:digit:]]')
FROM table;
To then convert this to a number:
SELECT TO_NUMBER(REGEXP_REPLACE(price, '[^[:digit:]]'))
FROM table;
If you want to add the point in then you can do that with REGEXP_REPLACE too:
SELECT TO_NUMBER(REGEXP_REPLACE(val, '^([0-9]*)([^[:digit:]]*)([0-9]*)(.*)$', '\1.\3'))
FROM table;
Voila...
SELECT CAST(REPLACE(YourVarcharCol, 'dollars', '') AS INT) FROM Table
The issue with this is it will break if the varchar still contains alpha-numeric characters.
How about using translate to strip out the unwanted characters.
SELECT TO_NUMBER(TRANSLATE('14dollars10cents','1234567890dolarscents','1234567890')) FROM DUAL
No I don't think there is direct way.
you can do string parsing to get your integer value.
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)