There is a one value 15000000.00 with Numeric datatype in SQL server.
How can i get or convert the value 15000000.00 to 15,000,000?
The database server is the wrong place to do this. Localization should be handled in the presentation layer, not the datastore.
Since you're working with the money type, or you want the result to be a money type it could be as simple as:
SELECT CONVERT(VARCHAR, #money_val, 1) -- you may have to cast to money from int first
Check out this link for a deeper discussion:
Here is an excerpt:
Comma-formatting is available only for
MONEY data types. If you want to
comma-format INT, DECIMAL etc, you
should cast it to MONEY and do a
convert with style flag 1.
DECLARE #m DECIMAL(10,2) SELECT #m =
'23456789.25'
SELECT
CONVERT(VARCHAR, #m, 1) AS DecimalValue,
CONVERT(VARCHAR, CAST(#m AS MONEY), 1) AS MoneyValue /*
DecimalValue
MoneyValue
23456789.25 23,456,789.25
*/
This is not a conversion. 15.000.000,00 (german writing) is the string representation of 15 million. A decimal data type does not store the string, but the value.
All string represenration you see are basically visualizations - in enterprise manager or software according to the settings (locale) when generating the string.
I've always used the following with success
SELECT
Convert(VARCHAR, Cast(100000.01 AS MONEY), 1) Amount
Results:
Amount
-----------------------------
100,000.01
You don't want to save your numeric data in formats. You can do this when selecting:
SELECT CONVERT(varchar(12), value, 1) AS formattedvalue FROM table
The last 1 is a convert style that puts in the . and , signs (depending on your local settings and numeric type).
If you ask me, I wouldn't even let the SQL database server worry about this and format the number in code itself.
Related
I am trying to convert date to number like below, not sure which function works better.
Database used is SQL Server.
Table details
create table test
(
id varchar(255),
call_date varchar(255)
);
insert into test('26203', '14-Aug-2020');
I need output as 4405726203 -- its concatenation of date (14-Aug-2014) + id (26203)
This is too long for a comment.
SQL Server allows you to convert a datetime to a float. That would be:
select cast(dte as float)
from (values (convert(datetime, '14-Aug-2020'))) v(dte)
However, the corresponding floating point value is 44055 (https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=d142a64db0872e7572eb4fbd6d5d5fe7). It is a bit of mystery what your intention is.
You could subtract 2, but that seems arbitrary. You could calculate the number of days since 1899-12-30. But that also seems arbitrary.
In any case, once you figure out how to convert the date to the number you want, just use concat() to combine the values.
I have found the solution:
convert(varchar,CAST(CONVERT(datetime,call_date) as bigint)) + id
Under the hood, a SQL Server DateTime is a tuple of 2 32-bit integers:
The first integer is a count of days since since the epoch, which for SQL Server is 1 January 1900
The second integer is a count of milliseconds since start of day (00:00:00.000). Except that the count ticks up in 3- or 4-milliscond increments. Microsoft only knows why that decision was made.
You can get the count of days since the epoch with
convert( int, convert( date, t.call_date ) )
[wrap that in convert(varchar, ... ) to turn it into a string]
Looks like your id is already a varchar, so you can say:
select compound_key = convert(varchar,
convert(int,
convert(date,
call_date
)
)
)
+ t.id
from test t
I would suggest padding both fields with leading zeros to a fixed length so as to avoid possible collisions (assuming you're trying to generate a key here). Signed 32-bit integer overflows a 2.1 billion-ish, so 9 digits for each field is sufficient.
This works
select concat(datediff(d, 0, cast(call_date as date)), id)
from
(values ('26203','14-Aug-2020')) v(id, call_date);
Results
4405526203
I have been given some data where there is a 'float' column that contains a date with a 1 in the front of it. I.e the value 1171030 represents 30th October 2017.
I am stuck in attempting to convert it to a normal date, when attempting to remove the one a dot appears (i.e. .171030).
Would really appreciate some guidance.
Many thanks
Yuck! Let's try datefromparts():
select datefromparts((val - 100000) / 10000, floor(val / 100) % 100, val % 100)
Or, here is another approach:
select convert(date, right(convert(varchar(255), cast(val as int)), 6))
SQL Server is actually pretty flexible in the date formats it understands.
I'm assuming this was probably produced by a non-Y2K compliant method such as JavaScript getYear() which simply returns current year minus 1900. It's not clear to me whether this data is coming from a flat file or it is already imported into a database table.
If you treat this value as a character string:
case length(val)
when 7 then cast('20' + right(val, 6) as date)
when 6 then cast('19' + val as date)
end
If you truly have a float (or int) value:
cast(cast(cast(19000000 + #val as int) as char(8)) as date)
In this case you'll need to convert through a character value rather than going straight to date. Be careful with string conversions from float to char. If you prefer shorter then you may be able to get away with this one:
cast(str(19000000 + #val, 8) as date);
You might get errors by assuming a length of 8 but that's probably a good way to catch and prevent problems.
I have been using SQL Server 2005, and I need to store some columns in database in Money format.
But SQL Server stores them like this --> 0000.0000, but I only want 2 digits after the decimal point ---> 0000.00
Do I have to control this in the program or there is a way to change this format in SQL Server 2005 ?
Thanks in advance
I would normally do these formatting stuffs in the front end. But if you still have to do it within the DB layer itself then make use of ROUND function.
SELECT CAST(ROUND(1234.1234, 2) AS MONEY)
Would also suggest you to check out the Performance storage comparison between Money & Decimal post written by Aaron Bertrand: https://sqlblog.org/2008/04/27/performance-storage-comparisons-money-vs-decimal
Money Vs Decimal Vs Float Decision Flowchart (Extract from SQLCAT.com):
Source: http://sqlcat.com/sqlcat/b/technicalnotes/archive/2008/09/25/the-many-benefits-of-money-data-type.aspx
Use Round() function. Returns a numeric value, rounded to the specified length or precision.
More here.
Round(value,2,1)
Second parameter specifies precision to be two decimal places.
Third parameter with value one specifies truncate rather than round off.
try this it works for SQL Server 2008 and below (2012 have already a FORMAT() function that you can use)
this will only works for data type Money and SmallMoney
declare #v money -- or smallmoney
set #v = 1000.0123
select convert(varchar(25), #v, 0)
select convert(varchar(25), #v, 1)
select convert(varchar(25), #v, 2)
select convert(varchar(25), #v, 126)
select '$' + convert(varchar(25), #v, 0)
select '$' + convert(varchar(25), #v, 1)
select '$' + convert(varchar(25), #v, 2)
select '$' + convert(varchar(25), #v, 126)
Hope this help!
I want to convert dateformat from mm/dd/yyyy to yyyy/mm/dd. I want the output in datetime format.
I tried this
convert(datetime,convert(varchar,getdate(),111),123)
but doesn't work. The error is "explicit conversion to datetime not available"
What is the best way to solve this problem? I'm using Sybase.
Try this
select convert(varchar,CAST('12/11/2010' as DateTime),111)
That won't work. The DATETIME data type has its own format that is really the amount of time that has passed since a fixed reference date; if you ask for a DATETIME it will always be returned according to that format.
How it is displayed to an end user is a function of the client. You can use CONVERT to convert it to a string and specify a format for how it is displayed in the string, but then you're returning a string, not a DATETIME. You can return it as a DATETIME (which has no inherent display format), and then it is up to the client application or OS to define how it is formatted for display. In client applications you also typically have formatting functions that display a date/time according to a format you specify. And if you haven't specified it explicitly in an application, then the display of the date/time will typically be defined by the localization settings in the OS.
Basically, there is a difference between the data type - DATETIME - and its representation to end users.
Formatting is something that should be done in the presentation tier not the data tier. However, most vendors, like Sybase, provide the ability to do rudimentary formatting:
Select Cast( Year(GetDate()) As char(4) )
+ '/' + Right( '00' + Cast( Month(GetDate()) As varchar(2) ), 2 )
+ '/' + Right( '00' + Cast( Day(GetDate()) As varchar(2) ), 2 )
Try this query
select (CONVERT(varchar(10), GETDATE(), 120))
This is in MS SQL Server.
I have a varchar in the format yyyy-MM-dd-hh.mm.ss.nnnnnn
For example: 2010-09-17-20.52.31.870000
I want to convert this into a datetime... but ISDATE function in MSSQL says that is not a valid date and CONVERT won't work. Is there a way to use the convert function so that I can tell it what format the date is in?
I also want to check first that it is a valid date since the varchar input may contain nothing or it may contain an invalid date.
For example, invalid data of 2010-xx-r7-99.53esdfd.31.870000... I would skip that data and not even try to convert.
As far as I'm aware, SQL Server 2005 only supports milliseconds up to 3 digits, so you could replace the periods with colons, and grab the left and right portions (ignoring the hyphen between the day and hours) and come up with something like this:
DECLARE #myDate varchar(50)
SET #myDate = '2010-09-17-20.52.31.870000'
PRINT isdate(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':')) -- Should print '1'
PRINT cast(left(#myDate, 10) + ' ' +
replace(substring(#myDate, 12, 12), '.', ':') as datetime)
... which will effectively give you 870 milliseconds
The ISO 8601 standard separates the date and time with the letter T. Maybe that's all it needs to convert successfully? Some conversion implementations accept a space there too. I've never seen a hyphen there.
You would have to change the punctuation a bit to make it work, and reduce the precision from microseconds to millisecond. This works:
convert(datetime, '2010-09-17 20:52:31.870', 121)
What you are getting in is a bit wonky, but this works (tested):
DECLARE #temp as varchar(50)
SET #temp = '2010-09-17-20.52.31.870'
SET #temp = replace(#temp,'.',':')
set #temp = stuff(#temp,11,1,'T')
set #temp = stuff(#temp,20,1,'.')
select #temp
select cast(#temp as datetime)
NB I cut off the extra 0s, you could do this with substring if there really are those extra ones.