Showing posts with label format. Show all posts
Showing posts with label format. Show all posts

Monday, March 26, 2012

More date format grief

I'm investigating a bug a customer has reported in our database
abstraction layer, and it's making me very unhappy.

Brief summary:
I have a database abstraction layer which is intended to mediate
between webapps and arbitrary database backends using JDBC. I am very
unwilling indeed to write special-case code for particular
databases. Our code has worked satisfactorily with many databases,
including many instances MS SQLServer 2000 databases using the
com.microsoft.sqlserver.SQLServerDriver.

However, in this instance, the database won't accept dates. It won't
accept dates in the java.sql.Date.toString() format (which is the ANSI
SQL 92 format) and it won't accept dates in the ISO8601 format if they
have a zone offset (which in the general case they do) - even if that
zone offset is 'Z'.

I find, by reading on Usenet, that SQL Server doesn't have a default
date format. Furthermore, it doesn't take it's date format from
Windows Regional settings.

So how, for the love of God and Little Fishes, do I persuade a SQL
Server database to accept ANSI SQL 92 dates, permanently, not on a
per-session basis?

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

;; all in all you're just another click in the call
;;-- Minke BouyedSimon,

I'll agree this is very frustrating, but there is no
easy answer, since there is no international standard for
representation of datetime values. ISO-8601 has a huge
number of options, and SQL Server accepts at least a couple
of the ISO-8601 alternatives.

If you have timezone information in data and want one
product that works with all back ends, then you've probably
got trouble. Not all products support timezones, so your
data will end up with different values on different products.
If you want consistency, either eliminate or convert the
timezone data in your front end, and send every back end you
connect to datetime values as strings of the form
'YYYYMMDD HH:MM:SS' (seconds optional or with fractional
seconds as well).

I thought you could also use '{d YYYY-MM-DD}' and it would
work regardless of settings (unlike 'YYYY-MM-DD' which depends
on date format settings). Not sure about this last bit, though.

Does SQL Server have a default date format? This is several questions:

Q. Does SQL Server display dates as character strings in a
consistent way?
A. SQL Server doesn't display anything. IDEs and front-ends do.

Q. Does SQL Server CAST dates to strings with a consistent format?
A. No. This depends on language settings.

Q. Can SQL Server convert dates to strings with a consistent format?
A. Yes, with CONVERT(varchar..., <format>) and string functions.

Q. Does SQL Server import every ISO-8601-allowed date correctly?
A. No. It does import a few of them correctly and consistently:
YYYYMMDD HH:MM:SS.fff and YYYY-MM-DDTHH:MM:SS.fff for example.
As far as I know, there is no timezone support.

Q. Does CONVERT(datetime, ...) with format codes convert
consistently?
A. No. The documentation does not make this clear, but
all the numerical, delimited formats except for the ISO
format with the T depend on the connection's language or
dateformat setting (dateformat overrides language, I believe).

Why doesn't SQL Server consistently convert SQL-92 date strings?
Good question. It converts SQL-92 timestamp (without timezone)
correctly, but not date-only.

It will, if the date format at the time of conversion is mdy,
ymd, or myd, but I don't think that's a great solution.

What's the safest date format to use?
Probably 'YYYYMMDD HH:MM:SS.[fff]', an ISO format, since if
someone truncates it to date-only, it won't break, like the
SQL-92 timestamp form.

-- Steve Kass
-- Drew University
-- Ref: 4BA55F69-6565-4B87-BB19-E223787FDB91

Simon Brooke wrote:
> I'm investigating a bug a customer has reported in our database
> abstraction layer, and it's making me very unhappy.
> Brief summary:
> I have a database abstraction layer which is intended to mediate
> between webapps and arbitrary database backends using JDBC. I am very
> unwilling indeed to write special-case code for particular
> databases. Our code has worked satisfactorily with many databases,
> including many instances MS SQLServer 2000 databases using the
> com.microsoft.sqlserver.SQLServerDriver.
> However, in this instance, the database won't accept dates. It won't
> accept dates in the java.sql.Date.toString() format (which is the ANSI
> SQL 92 format) and it won't accept dates in the ISO8601 format if they
> have a zone offset (which in the general case they do) - even if that
> zone offset is 'Z'.
> I find, by reading on Usenet, that SQL Server doesn't have a default
> date format. Furthermore, it doesn't take it's date format from
> Windows Regional settings.
> So how, for the love of God and Little Fishes, do I persuade a SQL
> Server database to accept ANSI SQL 92 dates, permanently, not on a
> per-session basis?|||Steve Kass <skass@.drew.edu> writes:

> Simon Brooke wrote:
> > I have a database abstraction layer which is intended to mediate
> > between webapps and arbitrary database backends using JDBC. I am very
> > unwilling indeed to write special-case code for particular
> > databases. Our code has worked satisfactorily with many databases,
> > including many instances MS SQLServer 2000 databases using the
> > com.microsoft.sqlserver.SQLServerDriver.

> > However, in this instance, the database won't accept dates. It won't
> > accept dates in the java.sql.Date.toString() format (which is the ANSI
> > SQL 92 format) and it won't accept dates in the ISO8601 format if they
> > have a zone offset (which in the general case they do) - even if that
> > zone offset is 'Z'.
> > I find, by reading on Usenet, that SQL Server doesn't have a default
> > date format. Furthermore, it doesn't take it's date format from
> > Windows Regional settings. So how, for the love of God and Little
> > Fishes, do I persuade a SQL
> > Server database to accept ANSI SQL 92 dates, permanently, not on a
> > per-session basis?

> Q. Does SQL Server import every ISO-8601-allowed date correctly?
> A. No. It does import a few of them correctly and consistently:
> YYYYMMDD HH:MM:SS.fff and YYYY-MM-DDTHH:MM:SS.fff for example.

Yes, but, actually, that's not a valid ISO-8601 format, because it
doesn't include a timezone. Furthermore, I don't have the luxury of
being able to generate custom code for every database. Surely it must
be _possible_ to persuade SQL Server to conform to ANSI 92?

> Why doesn't SQL Server consistently convert SQL-92 date strings?
> Good question. It converts SQL-92 timestamp (without timezone)
> correctly, but not date-only.

No, it doesn't. That is where all this grief started: we've been
sending that to SQL Server for years and in every other installation
it has worked, but now we have a customer using MS SQL Server 2000 who
is having that fail consistently and repeatedly on one of their boxes
(they have another box running identical software on which it is not
failing, and on our box which we've one everythintg possible to make
identical it doesn't fail). I've done everything I can to find a
difference in setup between the boxes and so far I've failed.

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

;; all in all you're just another click in the call
;;-- Minke Bouyed|||
Simon Brooke wrote:
> Steve Kass <skass@.drew.edu> writes:
>
>>Simon Brooke wrote:
>>
>>>I have a database abstraction layer which is intended to mediate
>>>between webapps and arbitrary database backends using JDBC. I am very
>>>unwilling indeed to write special-case code for particular
>>>databases. Our code has worked satisfactorily with many databases,
>>>including many instances MS SQLServer 2000 databases using the
>>>com.microsoft.sqlserver.SQLServerDriver.
>
>>>However, in this instance, the database won't accept dates. It won't
>>>accept dates in the java.sql.Date.toString() format (which is the ANSI
>>>SQL 92 format) and it won't accept dates in the ISO8601 format if they
>>>have a zone offset (which in the general case they do) - even if that
>>>zone offset is 'Z'.
>>>I find, by reading on Usenet, that SQL Server doesn't have a default
>>>date format. Furthermore, it doesn't take it's date format from
>>>Windows Regional settings. So how, for the love of God and Little
>>>Fishes, do I persuade a SQL
>>>Server database to accept ANSI SQL 92 dates, permanently, not on a
>>>per-session basis?
>
>>Q. Does SQL Server import every ISO-8601-allowed date correctly?
>>A. No. It does import a few of them correctly and consistently:
>> YYYYMMDD HH:MM:SS.fff and YYYY-MM-DDTHH:MM:SS.fff for example.
>
> Yes, but, actually, that's not a valid ISO-8601 format, because it
> doesn't include a timezone. Furthermore, I don't have the luxury of
> being able to generate custom code for every database. Surely it must
> be _possible_ to persuade SQL Server to conform to ANSI 92?
My reference is ISO8601:2000E (December, 2000), and I don't see
where a timezone is required. Do you have the paragraph number?

Section 5.4 describes point-in-time representations, and says "The
zone designator is empty if use is made of the local time of the
day in accordance...", referring to earlier sections that give
offer hhmm, hh:mm, hhmmss, hh:mm:ss, hh:mm,m, hhmm,m, hh, etc.,
etc., as possible date formats.

It also gives Basic (no hyphens) and extended (with hyphens) formats
for everything, without as far as I can see mandating one or the
other. It would be nice if SQL Server understood them all, but it
does understand the one with hyphens and a T (ISO allows the T to be
omitted if no ambiguity results, though I couldn't see where
any would regarding other ISO formats - probably missed something
crazy like week numbers in BC years that used a T.)

SQL Server also understands the one with no hyphens or T.
It looks ok in ISO to omit date separators but include time
separators.
>>Why doesn't SQL Server consistently convert SQL-92 date strings?
>>Good question. It converts SQL-92 timestamp (without timezone)
>>correctly, but not date-only.
>
> No, it doesn't. That is where all this grief started: we've been
> sending that to SQL Server for years and in every other installation
> it has worked, but now we have a customer using MS SQL Server 2000 who
> is having that fail consistently and repeatedly on one of their boxes
> (they have another box running identical software on which it is not
> failing, and on our box which we've one everythintg possible to make
> identical it doesn't fail). I've done everything I can to find a
> difference in setup between the boxes and so far I've failed.

My slip. SQL Server doesn't understand SQL-92

TIMESTAMP '2003-02-22 23:34:43.123' at all, as in

CAST(TIMESTAMP '2003-02-22 23:34:43.123' as DATETIME)

but I doubt you are construction CAST(TIMESTAMP ...
expressions. SQL Server uses
{ts '1996-12-19 11:11:11.000'} to represent
a timestamp literal, and interprets it unambiguously,
as far as I know, as it does the date literal format of
{d '1996-12-19'}

Without the {ts ... }, these strings alone, like all
numeric delimited date formats, when implicitely
converted to dates follow the relative positions of
d and m in the dateformat setting in effect implicit
from the language selection or explicitly set.

set dateformat dmy
go
declare @.d datetime
set @.d = {ts '1996-12-19 11:11:11.000'}
select @.d
go
declare @.d datetime
set @.d = {d '1996-12-19'}
select @.d
go
declare @.d datetime
set @.d = '1996-12-19 11:11:11.000'
select @.d
go
declare @.d datetime
set @.d = '1996-12-19'
select @.d

I don't know why you would have trouble with this if the
settings were right, but maybe there's some driver parameter
buried in the registry, or some other setting that's not
obvious. Perhaps someone wanted us_english but dmy, and
got the bright idea of modifying the syslanguages table!

Does that bum server error out on this??

set dateformat dmy
declare @.d datetime
set @.d = '2003-02-19'

If the server is installed as us_english, and no one
has changed the dateformat setting or modified syslanguages,
I think it should work and might be a case for product
support. On the other hand, I wouldn't
want a product that depended on the language of installation.

SK|||Simon

This may be useless, but you don't seem to have a lot SQL Server
2000-specific info.
SQL server interprets data based on a 'collation' which is set at
install time, and can be overridden manually in an SQL statement.
To find the default collation for the database, the user will need to
right click on the SQL server instance in Enterprise Manager and
choose 'properties'. The default collation is displayed as part of
the basinc database information.
This can only be changed if the databases on the server are rebuilt.
Some information below from the SQL server 'man pages'

I haven't had the problems you describe, but if there is a
configuration difference between two installs, which is causing the
problem you describe, this is likely to be it.
From what I understand, you are saying that one installation processes
the dates OK, and the other does not. So SQL Server 2000 will do the
job, it is just not configured correctly on one of the servers.

good luck

Ben McIntyre

<snip>
-----------------------

Collation Options for International Support
In Microsoft SQL Server 2000, it is not required to separately
specify code page and sort order for character data, and the collation
used for Unicode data. Instead, specify the collation name and sorting
rules to use. The term, collation, refers to a set of rules that
determine how data is sorted and compared. Character data is sorted
using rules that define the correct character sequence, with options
for specifying case-sensitivity, accent marks, kana character types,
and character width. Microsoft SQL Server 2000 collations include
these groupings:

Windows collations
Windows collations define rules for storing character data based on
the rules defined for an associated Windows locale. The base Windows
collation rules specify which alphabet or language is used when
dictionary sorting is applied, as well as the code page used to store
non-Unicode character data. For more information, see Collations.

SQL collations
SQL collations are provided for compatibility with sort orders in
earlier versions of Microsoft SQL Server. For more information, see
Using SQL Collations.

Changing Collations After Setup
When you set up SQL Server 2000, it is important to use the correct
collation settings. You can change collation settings after running
Setup, but you must rebuild the databases and reload the data. It is
recommended that you develop a standard within your organization for
these options. Many server-to-server activities can fail if the
collation settings are not consistent across servers.

----------------------
How To

How to rebuild the master database (Rebuild Master utility)
To rebuild the master database

Shutdown Microsoft SQL Server 2000, and then run Rebuildm.exe. This
is located in the Program Files\Microsoft SQL Server\80\Tools\Binn
directory.

In the Rebuild Master dialog box, click Browse.

In the Browse for Folder dialog box, select the \Data folder on the
SQL Server 2000 compact disc or in the shared network directory from
which SQL Server 2000 was installed, and then click OK.

Click Settings. In the Collation Settings dialog box, verify or change
settings used for the master database and all other databases.
Initially, the default collation settings are shown, but these may not
match the collation selected during setup. You can select the same
settings used during setup or select new collation settings. When
done, click OK.

In the Rebuild Master dialog box, click Rebuild to start the process.
The Rebuild Master utility reinstalls the master database.

Note To continue, you may need to stop a server that is running.
</snip>|||ben_spam@.mailcity.com (Ben McIntyre) writes:

> Simon
> This may be useless, but you don't seem to have a lot SQL Server
> 2000-specific info.
> SQL server interprets data based on a 'collation' which is set at
> install time, and can be overridden manually in an SQL statement.
> To find the default collation for the database, the user will need to
> right click on the SQL server instance in Enterprise Manager and
> choose 'properties'. The default collation is displayed as part of
> the basinc database information.
> This can only be changed if the databases on the server are rebuilt.
> Some information below from the SQL server 'man pages'
> I haven't had the problems you describe, but if there is a
> configuration difference between two installs, which is causing the
> problem you describe, this is likely to be it.
> From what I understand, you are saying that one installation processes
> the dates OK, and the other does not. So SQL Server 2000 will do the
> job, it is just not configured correctly on one of the servers.

OK, thanks for that. The collation sequence on the database on our
test box (which _does_ work) is SQL_Latin1_General_CP1_CI_AS. My
customer isn't yet in this morning so I can't ring and check what his
is.

I'll post a resolution once I get it sorted in case anyone searches
google any time in the future for a similar problem.

Just so that, in future, I know the general solution, which 'bit' of the
collation name is it which affects date sequencing? I mean, for
example, if in future I have a similar problem with a customer not in
the Latin1 area, what collation advice to I offer?

Cheers

Simon

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

[ This mind intentionally left blank ]|||> Just so that, in future, I know the general solution, which 'bit' of the
> collation name is it which affects date sequencing?

You mean datetime datattype? That is not affected by collations at all. If this is your problem, you
might want to post the problem at hand again (It has been "aged out").

--
Tibor Karaszi, SQL Server MVP
Archive at: http://groups.google.com/groups?oi=djq&as ugroup=microsoft.public.sqlserver

"Simon Brooke" <simon@.jasmine.org.uk> wrote in message
news:87n0dtot6r.fsf@.gododdin.internal.jasmine.org. uk...
> ben_spam@.mailcity.com (Ben McIntyre) writes:
> > Simon
> > This may be useless, but you don't seem to have a lot SQL Server
> > 2000-specific info.
> > SQL server interprets data based on a 'collation' which is set at
> > install time, and can be overridden manually in an SQL statement.
> > To find the default collation for the database, the user will need to
> > right click on the SQL server instance in Enterprise Manager and
> > choose 'properties'. The default collation is displayed as part of
> > the basinc database information.
> > This can only be changed if the databases on the server are rebuilt.
> > Some information below from the SQL server 'man pages'
> > I haven't had the problems you describe, but if there is a
> > configuration difference between two installs, which is causing the
> > problem you describe, this is likely to be it.
> > From what I understand, you are saying that one installation processes
> > the dates OK, and the other does not. So SQL Server 2000 will do the
> > job, it is just not configured correctly on one of the servers.
> OK, thanks for that. The collation sequence on the database on our
> test box (which _does_ work) is SQL_Latin1_General_CP1_CI_AS. My
> customer isn't yet in this morning so I can't ring and check what his
> is.
> I'll post a resolution once I get it sorted in case anyone searches
> google any time in the future for a similar problem.
> Just so that, in future, I know the general solution, which 'bit' of the
> collation name is it which affects date sequencing? I mean, for
> example, if in future I have a similar problem with a customer not in
> the Latin1 area, what collation advice to I offer?
> Cheers
> Simon
> --
> simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/
> [ This mind intentionally left blank ]|||Ben McIntyre (ben_spam@.mailcity.com) writes:
> SQL server interprets data based on a 'collation' which is set at
> install time, and can be overridden manually in an SQL statement.
> To find the default collation for the database, the user will need to
> right click on the SQL server instance in Enterprise Manager and
> choose 'properties'. The default collation is displayed as part of
> the basinc database information.

Collation apply to string columns, not to datetime columns.

The two commands that affect how strings is interpreted are
SET DATEFORMAT and SET LANGUAGE.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Tibor Karaszi" <tibor.please_reply_to_public_forum.karaszi@.corners tone.se> writes:

> > Just so that, in future, I know the general solution, which 'bit' of the
> > collation name is it which affects date sequencing?
> You mean datetime datattype? That is not affected by collations at all. If this is your problem, you
> might want to post the problem at hand again (It has been "aged out").

Ouch, I feared that.

Briefly, I have a piece of cross-platform Java code which is used in
production environments against at least five different database
backends. Many installations use SQL Server and have been running
reliably since 1998, and several installations use SQL Server 2000
with the com.microsoft.sqlserver.SqlServerDriver satisfactorily.

Yesterday, one of our customers reported a problem and on
investigation we found that their (new) installation wasn't accepting
dates properly. It would not accept the date 28th August 2003 at all,
and when (at my suggestion) they tried 4th August 2003, they got back
8th April 2003, which showed we had a date format problem.

The code asks the database for the column type of each column and
formats the data appropriately; because SQL Server doesn't support
date fields it responds that the date/time fields which on other
databases would be date fields are of type java.sql.Types.TIMESTAMP,
and consequently my code formats them as ANSI 92 timestamp format,
namely

yyyy-mm-dd hh:mm:ss.fffffffff

As I say, we've got loads of SQL Server installations which are
working quite happily with this. We've got exactly one which isn't. We
haven't been able to reproduce the bug on our test machine. We haven't
been able to identify any difference in configuration between the
machine that doesn't work and ones which do.

I'm very unwilling indeed to write special purpose code for different
database backends as it will lead to maintenance problems (I know this,
because we have one special purpose hack to work around an Oracle
misfeature). I'd like to resolve this problem if I can by specifying
the required SQL Server configuration.

We've today sent the customer a patch which dumps and deletes the
database and recreates it with the collation which we have on our
test box but it sounds from what you are saying as though this is
unlikely to work.

Can you offer any other suggestions?

Many thanks

Simon, not much impressed by Microsoft at the best of times.

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

;; Friends don't send friends HTML formatted emails.|||[microsoft.public.sqlserver.setup removed - can't send to two mail
servers at once, unfortunately...]

Simon,

Can you see what

DBCC USEROPTIONS

returns on the connection that is failing? And if there are no
differences from other servers, whether the syslanguages table has not
been modified?

SK

Simon Brooke wrote:
> "Tibor Karaszi" <tibor.please_reply_to_public_forum.karaszi@.corners tone.se> writes:
>
>>>Just so that, in future, I know the general solution, which 'bit' of the
>>>collation name is it which affects date sequencing?
>>
>>You mean datetime datattype? That is not affected by collations at all. If this is your problem, you
>>might want to post the problem at hand again (It has been "aged out").
>
> Ouch, I feared that.
> Briefly, I have a piece of cross-platform Java code which is used in
> production environments against at least five different database
> backends. Many installations use SQL Server and have been running
> reliably since 1998, and several installations use SQL Server 2000
> with the com.microsoft.sqlserver.SqlServerDriver satisfactorily.
> Yesterday, one of our customers reported a problem and on
> investigation we found that their (new) installation wasn't accepting
> dates properly. It would not accept the date 28th August 2003 at all,
> and when (at my suggestion) they tried 4th August 2003, they got back
> 8th April 2003, which showed we had a date format problem.
> The code asks the database for the column type of each column and
> formats the data appropriately; because SQL Server doesn't support
> date fields it responds that the date/time fields which on other
> databases would be date fields are of type java.sql.Types.TIMESTAMP,
> and consequently my code formats them as ANSI 92 timestamp format,
> namely
> yyyy-mm-dd hh:mm:ss.fffffffff
> As I say, we've got loads of SQL Server installations which are
> working quite happily with this. We've got exactly one which isn't. We
> haven't been able to reproduce the bug on our test machine. We haven't
> been able to identify any difference in configuration between the
> machine that doesn't work and ones which do.
> I'm very unwilling indeed to write special purpose code for different
> database backends as it will lead to maintenance problems (I know this,
> because we have one special purpose hack to work around an Oracle
> misfeature). I'd like to resolve this problem if I can by specifying
> the required SQL Server configuration.
> We've today sent the customer a patch which dumps and deletes the
> database and recreates it with the collation which we have on our
> test box but it sounds from what you are saying as though this is
> unlikely to work.
> Can you offer any other suggestions?
> Many thanks
> Simon, not much impressed by Microsoft at the best of times.|||Hi,

Simon Brooke wrote:

[...]

> So how, for the love of God and Little Fishes, do I persuade a SQL
> Server database to accept ANSI SQL 92 dates, permanently, not on a
> per-session basis?

Back when I was a ASP programmer the way do deal with this was to format the
date like "dd-MMM-yyyy", where "MMM" is the three-letter abbreviation of
the month.
This works because the Database understands how to read the dd-MMM-yyyy
format. this behaviour is not particular to SQL Server, I just tried it in
JDBC/PostgreSQL (don't have access to MSSQL right now) and it works
also... I would be surprised if it didn't worked in JDBC/MSSQL.

CREATE TABLE public.tbl_test
(
datefield date
) ;

********** JAVA *************
Connection c = getConnection();
PreparedStatement statement = c.prepareStatement("INSERT INTO
tbl_test(datefield) VALUES (?)");

statement.setObject(1, "10-Sep-2003");
statement.execute();
statement.clearParameters();
statement.close();
**********************************

SELECT * FROM tbl_test;
datefield
----
2003-09-10
(1 row)

There is a catch though, you have to be carefull with what you write as
"MMM", if the DB server is configured in other language other than English
the month abbreviation must comply to that language.

I hope this helps.

Regards,
Luis Neves|||Simon Brooke (simon@.jasmine.org.uk) writes:
> The code asks the database for the column type of each column and
> formats the data appropriately; because SQL Server doesn't support
> date fields it responds that the date/time fields which on other
> databases would be date fields are of type java.sql.Types.TIMESTAMP,
> and consequently my code formats them as ANSI 92 timestamp format,
> namely
> yyyy-mm-dd hh:mm:ss.fffffffff
> As I say, we've got loads of SQL Server installations which are
> working quite happily with this. We've got exactly one which isn't.

Which smells no bit of luck, given that you post with a UK address.

Try this script:

SET DATEFORMAT dmy
SELECT convert(datetime, '2002-12-18 12:12:12.000') -- Fails
go
SET DATEFORMAT mdy
SELECT convert(datetime, '2002-12-18 12:12:12.000') -- Passes
go
SET LANGUAGE British
SELECT convert(datetime, '2002-12-18 12:12:12.000') -- Fails
go
SET LANGUAGE us_english
SELECT convert(datetime, '2002-12-18 12:12:12.000') -- Passes
go

The dateformat setting is a pure run-time setting. However, changing
language also changes the dateformat setting. And the language can
be set by a default on a login with sp_defaultlanguage. Finally, there
is a server configuration option that determines the default language
for new logins.

If your java app logs in with a certain login, you can probably mandate
that the default language of this login should be one that has a dateformat
of ymd or mdy, for instance Swedish.

If you can't mandate the language, it seems that you need to adapt your
app how much you hate it.

I should add that this problem appears because you are sending down
raw SQL statements to SQL Server, rather than parameterized queries
or RPC calls to stored procedures. If you do this, the client library
will handle the date format and pass SQL Server a binary value which
is not subject to settings. Whether this is possible to do in Java, I
have no idea, but client libraries such as ODBC and ADO supports it,
so why not JDBC?

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Steve Kass <skass@.drew.edu> writes:

> [microsoft.public.sqlserver.setup removed - can't send to two mail
> servers at once, unfortunately...]
> Simon,
> Can you see what
> DBCC USEROPTIONS
> returns on the connection that is failing?

I'm sorry, how do I do this? I'm not by any means a SQL Server
expert. I tried it in query analyzer and got:

Server: Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'sbcc'

When I try it over the JDBC connection I get:
DBCC USEROPTIONS
SQL Error
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]No rows affected.
DBCC USEROPTIONS;

SQL Error
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Syntax error at token 0, line 0 offset 0.

> And if there are no
> differences from other servers, whether the syslanguages table has not
> been modified?

There does not appear to be syslanguages table in the database. There
are plenty of other 'dbo.sysxxx' tables, but not syslanguages. This is
SQL Server 2000.

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/

A message from our sponsor: This site is now in free fall|||"Simon Brooke" <simon@.jasmine.org.uk> wrote in message
news:878yp38qg1.fsf@.gododdin.internal.jasmine.org. uk...
> Steve Kass <skass@.drew.edu> writes:
> > [microsoft.public.sqlserver.setup removed - can't send to two mail
> > servers at once, unfortunately...]
> > Simon,
> > Can you see what
> > DBCC USEROPTIONS
> > returns on the connection that is failing?
> I'm sorry, how do I do this? I'm not by any means a SQL Server
> expert. I tried it in query analyzer and got:
> Server: Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'sbcc'

Umm, here is simply a typo. This will work in Query Analyzter.|||Simon Brooke (simon@.jasmine.org.uk) writes:
> Steve Kass <skass@.drew.edu> writes:
>> [microsoft.public.sqlserver.setup removed - can't send to two mail
>> servers at once, unfortunately...]
>>
>> Simon,
>>
>> Can you see what
>>
>> DBCC USEROPTIONS
>>
>> returns on the connection that is failing?
> I'm sorry, how do I do this? I'm not by any means a SQL Server
> expert. I tried it in query analyzer and got:
> Server: Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'sbcc'

As Greg Strider pointed out, you gave a typo, and I don't want to
be sarcastic or anything, but double-checking what you typed, before
you ask for help, may increase your effectivenesss.

> When I try it over the JDBC connection I get:
> DBCC USEROPTIONS
> SQL Error
> java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]No rows
> affected.
> DBCC USEROPTIONS;
> SQL Error
> java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Syntax
> error at token 0, line 0 offset 0.

Some DBCC commands produces their output as messages, which could
confuse some drivers. However, USEROPTIONS always produce a result set.
Maybe the JDBC driver is too smart for its own good and performs its
own parsing, and don't recognize the command. Not knowing about
JDBC I cannot really help.

> There does not appear to be syslanguages table in the database. There
> are plenty of other 'dbo.sysxxx' tables, but not syslanguages. This is
> SQL Server 2000.

syslanguages is in master. I would hold it as unlikely that someone
has changed syslanguages.

In any case, I seem to recall that I tried to explained exactly what
was going on a couple of days ago. Did you see that post?

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||Simon Brooke <simon@.jasmine.org.uk> writes:

> Briefly, I have a piece of cross-platform Java code which is used in
> production environments against at least five different database
> backends. Many installations use SQL Server and have been running
> reliably since 1998, and several installations use SQL Server 2000
> with the com.microsoft.sqlserver.SqlServerDriver satisfactorily.
> Yesterday, one of our customers reported a problem and on
> investigation we found that their (new) installation wasn't accepting
> dates properly. It would not accept the date 28th August 2003 at all,
> and when (at my suggestion) they tried 4th August 2003, they got back
> 8th April 2003, which showed we had a date format problem.
> The code asks the database for the column type of each column and
> formats the data appropriately; because SQL Server doesn't support
> date fields it responds that the date/time fields which on other
> databases would be date fields are of type java.sql.Types.TIMESTAMP,
> and consequently my code formats them as ANSI 92 timestamp format,
> namely
> yyyy-mm-dd hh:mm:ss.fffffffff
> As I say, we've got loads of SQL Server installations which are
> working quite happily with this. We've got exactly one which isn't. We
> haven't been able to reproduce the bug on our test machine. We haven't
> been able to identify any difference in configuration between the
> machine that doesn't work and ones which do.

OK, just for the record here is the resolution of this issue.

What we found was that on the servers which worked, the user logins
used by the application had language set to 'English', and not either
'US English' or 'British English'. We set the language on the server
that didn't work to 'English', and it worked.

Many thanks to everyone who helped!

--
simon@.jasmine.org.uk (Simon Brooke) http://www.jasmine.org.uk/~simon/
Das Internet is nicht fuer gefingerclicken und giffengrabben... Ist
nicht fuer gewerken bei das dumpkopfen. Das mausklicken sichtseeren
keepen das bandwit-spewin hans in das pockets muss; relaxen und
watchen das cursorblinken. -- quoted from the jargon filesql

Friday, March 23, 2012

Monthly Reports - Date Format

I have a report that charts our weekly sales and monthly sales. I use the
following SQL statement to reflect 7 days or 30 days, which works but not
properly. I'd like for my report to run from Sunday to Sunday for the 7-day
report, and from the 1st of the month to the end of the month, regardless of
the number of days in the month. How do I modfify my statement to do this?
Here's my SQL statement for the 30-day or monthly report:
SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
(*) AS TOT
FROM Sysadm.receipt
WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
-30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
101), 101))
GROUP BY receipt_date, receipt_no, stamp
ORDER BY receipt_date
--
EnchantnetI used the following statement to run a report for the previous week, from
Saturday to Friday:
CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw, GETDATE()),
101), 101) AS StartDt,
CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 1 - DATEPART(dw, GETDATE()),
101), 101) AS EndDt
You could probably use a variation of this for your monthly report. I hope
this helps!
"Enchantnet" wrote:
> I have a report that charts our weekly sales and monthly sales. I use the
> following SQL statement to reflect 7 days or 30 days, which works but not
> properly. I'd like for my report to run from Sunday to Sunday for the 7-day
> report, and from the 1st of the month to the end of the month, regardless of
> the number of days in the month. How do I modfify my statement to do this?
> Here's my SQL statement for the 30-day or monthly report:
> SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
> (*) AS TOT
> FROM Sysadm.receipt
> WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
> -30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
> 101), 101))
> GROUP BY receipt_date, receipt_no, stamp
> ORDER BY receipt_date
> --
> Enchantnet|||Hey DAW,
Thanks for the code. However, I'm a newbie at this sort of stuff and I get
the following error when I entered your code: "ADO error: Incorrect syntax
near the keyword 'AS'. Statement(s) could not be prepared. Deferred prepare
could not be completed." Any idea? Do I need to include or define the
StartDt and EndDt elsewhere?
--
Enchantnet
"daw" wrote:
> I used the following statement to run a report for the previous week, from
> Saturday to Friday:
> CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw, GETDATE()),
> 101), 101) AS StartDt,
> CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 1 - DATEPART(dw, GETDATE()),
> 101), 101) AS EndDt
> You could probably use a variation of this for your monthly report. I hope
> this helps!
> "Enchantnet" wrote:
> > I have a report that charts our weekly sales and monthly sales. I use the
> > following SQL statement to reflect 7 days or 30 days, which works but not
> > properly. I'd like for my report to run from Sunday to Sunday for the 7-day
> > report, and from the 1st of the month to the end of the month, regardless of
> > the number of days in the month. How do I modfify my statement to do this?
> > Here's my SQL statement for the 30-day or monthly report:
> >
> > SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
> > (*) AS TOT
> > FROM Sysadm.receipt
> > WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
> > -30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
> > 101), 101))
> > GROUP BY receipt_date, receipt_no, stamp
> > ORDER BY receipt_date
> > --
> > Enchantnet|||I'm not sure what that particular error means, but your statement should look
something like:
select CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw,
GETDATE()), 101), 101) AS StartDt, CONVERT(datetime, CONVERT(nvarchar,
GETDATE() - 1 - DATEPART(dw, GETDATE()), 101), 101) AS EndDt
from ....
"Enchantnet" wrote:
> Hey DAW,
> Thanks for the code. However, I'm a newbie at this sort of stuff and I get
> the following error when I entered your code: "ADO error: Incorrect syntax
> near the keyword 'AS'. Statement(s) could not be prepared. Deferred prepare
> could not be completed." Any idea? Do I need to include or define the
> StartDt and EndDt elsewhere?
> --
> Enchantnet
>
> "daw" wrote:
> > I used the following statement to run a report for the previous week, from
> > Saturday to Friday:
> > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw, GETDATE()),
> > 101), 101) AS StartDt,
> > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 1 - DATEPART(dw, GETDATE()),
> > 101), 101) AS EndDt
> >
> > You could probably use a variation of this for your monthly report. I hope
> > this helps!
> >
> > "Enchantnet" wrote:
> >
> > > I have a report that charts our weekly sales and monthly sales. I use the
> > > following SQL statement to reflect 7 days or 30 days, which works but not
> > > properly. I'd like for my report to run from Sunday to Sunday for the 7-day
> > > report, and from the 1st of the month to the end of the month, regardless of
> > > the number of days in the month. How do I modfify my statement to do this?
> > > Here's my SQL statement for the 30-day or monthly report:
> > >
> > > SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
> > > (*) AS TOT
> > > FROM Sysadm.receipt
> > > WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
> > > -30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
> > > 101), 101))
> > > GROUP BY receipt_date, receipt_no, stamp
> > > ORDER BY receipt_date
> > > --
> > > Enchantnet|||Sorry, I had that wrong as far as what you need. Try this:
select ....
from...
where date between CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 -
DATEPART(dw, GETDATE()), 101), 101) AND CONVERT(datetime, CONVERT(nvarchar,
GETDATE() - 1 - DATEPART(dw, GETDATE()), 101), 101)
"daw" wrote:
> I'm not sure what that particular error means, but your statement should look
> something like:
> select CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw,
> GETDATE()), 101), 101) AS StartDt, CONVERT(datetime, CONVERT(nvarchar,
> GETDATE() - 1 - DATEPART(dw, GETDATE()), 101), 101) AS EndDt
> from ....
> "Enchantnet" wrote:
> > Hey DAW,
> >
> > Thanks for the code. However, I'm a newbie at this sort of stuff and I get
> > the following error when I entered your code: "ADO error: Incorrect syntax
> > near the keyword 'AS'. Statement(s) could not be prepared. Deferred prepare
> > could not be completed." Any idea? Do I need to include or define the
> > StartDt and EndDt elsewhere?
> > --
> > Enchantnet
> >
> >
> > "daw" wrote:
> >
> > > I used the following statement to run a report for the previous week, from
> > > Saturday to Friday:
> > > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw, GETDATE()),
> > > 101), 101) AS StartDt,
> > > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 1 - DATEPART(dw, GETDATE()),
> > > 101), 101) AS EndDt
> > >
> > > You could probably use a variation of this for your monthly report. I hope
> > > this helps!
> > >
> > > "Enchantnet" wrote:
> > >
> > > > I have a report that charts our weekly sales and monthly sales. I use the
> > > > following SQL statement to reflect 7 days or 30 days, which works but not
> > > > properly. I'd like for my report to run from Sunday to Sunday for the 7-day
> > > > report, and from the 1st of the month to the end of the month, regardless of
> > > > the number of days in the month. How do I modfify my statement to do this?
> > > > Here's my SQL statement for the 30-day or monthly report:
> > > >
> > > > SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
> > > > (*) AS TOT
> > > > FROM Sysadm.receipt
> > > > WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
> > > > -30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
> > > > 101), 101))
> > > > GROUP BY receipt_date, receipt_no, stamp
> > > > ORDER BY receipt_date
> > > > --
> > > > Enchantnet|||Perfect! Thank u, Thank u, Thank u!!!!!
--
Enchantnet
"daw" wrote:
> Sorry, I had that wrong as far as what you need. Try this:
> select ....
> from...
> where date between CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 -
> DATEPART(dw, GETDATE()), 101), 101) AND CONVERT(datetime, CONVERT(nvarchar,
> GETDATE() - 1 - DATEPART(dw, GETDATE()), 101), 101)
> "daw" wrote:
> > I'm not sure what that particular error means, but your statement should look
> > something like:
> >
> > select CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw,
> > GETDATE()), 101), 101) AS StartDt, CONVERT(datetime, CONVERT(nvarchar,
> > GETDATE() - 1 - DATEPART(dw, GETDATE()), 101), 101) AS EndDt
> > from ....
> >
> > "Enchantnet" wrote:
> >
> > > Hey DAW,
> > >
> > > Thanks for the code. However, I'm a newbie at this sort of stuff and I get
> > > the following error when I entered your code: "ADO error: Incorrect syntax
> > > near the keyword 'AS'. Statement(s) could not be prepared. Deferred prepare
> > > could not be completed." Any idea? Do I need to include or define the
> > > StartDt and EndDt elsewhere?
> > > --
> > > Enchantnet
> > >
> > >
> > > "daw" wrote:
> > >
> > > > I used the following statement to run a report for the previous week, from
> > > > Saturday to Friday:
> > > > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 7 - DATEPART(dw, GETDATE()),
> > > > 101), 101) AS StartDt,
> > > > CONVERT(datetime, CONVERT(nvarchar, GETDATE() - 1 - DATEPART(dw, GETDATE()),
> > > > 101), 101) AS EndDt
> > > >
> > > > You could probably use a variation of this for your monthly report. I hope
> > > > this helps!
> > > >
> > > > "Enchantnet" wrote:
> > > >
> > > > > I have a report that charts our weekly sales and monthly sales. I use the
> > > > > following SQL statement to reflect 7 days or 30 days, which works but not
> > > > > properly. I'd like for my report to run from Sunday to Sunday for the 7-day
> > > > > report, and from the 1st of the month to the end of the month, regardless of
> > > > > the number of days in the month. How do I modfify my statement to do this?
> > > > > Here's my SQL statement for the 30-day or monthly report:
> > > > >
> > > > > SELECT receipt_date, SUM(total_amt) AS Total_AMT, receipt_no, stamp, COUNT
> > > > > (*) AS TOT
> > > > > FROM Sysadm.receipt
> > > > > WHERE (receipt_date BETWEEN CONVERT(datetime, CONVERT(varchar, DATEADD(day,
> > > > > -30, GETDATE()), 101), 101) AND CONVERT(varchar, DATEADD(day, 0, GETDATE()),
> > > > > 101), 101))
> > > > > GROUP BY receipt_date, receipt_no, stamp
> > > > > ORDER BY receipt_date
> > > > > --
> > > > > Enchantnet

Month Format

Hello Experts!

I am trying to format the datetime field in my grouping. Right now I am using the expression =Month(Fields!TestDateTime.Value) in the edit group properties and it returns (for example) May 01 for the group. I would like it to show up as May 2007 instead. Would someone be kind enough to post what the correct expression should be?

Thanks,

Clint

Not sure if there is a better way, but this works:

Code Snippet

=MonthName(Month(Fields!DateOrderCreated.Value)) + " " + format(Fields!DateOrderCreated.Value,"yyyy")

|||Thanks, but that also does not work. It returns the same "May 01".|||What datatype is the field you are formatting?|||It is a datetime data typ|||

If it is a datetime data type, then you can use Format() on it using any of the standard formatting codes, like this:

Code Snippet

=Format(myDataField, "Mon yyyy")

|||Hmmmm still not working. What area should the code be put in to? I have tried the group properties, the field property value, and the custom format are of the field to no avail. It will either error out or return the same "May 01". I am working from the report layout area of the reporting services.|||LOL. Found the answer. Simply in the Format area, I just put a "Y" in the custom format field. thanks so much for your help though.

Monday, February 20, 2012

MONEY FORMAT presentation

Hi all,
I am tryng to locate the SQLServer vesion of Informix's DBMONEY env variable
which is used in the Informix env by tools like ISQL and I4GL to format
values stored as type MONEY into a nice presentation pattern. Is there such
a
property for SQLServer?
Why am I looking for this? Basically the application that we are building
handles all this preso stuff at the front-end, problem is we are trying to
rapid prototype a number of MIS reports (in SQLAnalyser) and the cllient is
used to seeing the numbers in a pre-formatted pattern as they currently use
ACCESS and the FORMAT function. Myself and my buddy are going slowly
blind/mad having to cast/convert values stored as money into strings to get
$'s and commas!
Slainte,
TaggartTaagart
DECLARE @.m AS DECIMAL (18,3)
SET @.m=100554545.36
SELECT convert(varchar,cast(@.m as money),1)
"Taggart" <Taggart@.discussions.microsoft.com> wrote in message
news:11E0F555-2BEF-4424-807C-3D6CEF31F6B7@.microsoft.com...
> Hi all,
> I am tryng to locate the SQLServer vesion of Informix's DBMONEY env
> variable
> which is used in the Informix env by tools like ISQL and I4GL to format
> values stored as type MONEY into a nice presentation pattern. Is there
> such a
> property for SQLServer?
> Why am I looking for this? Basically the application that we are building
> handles all this preso stuff at the front-end, problem is we are trying to
> rapid prototype a number of MIS reports (in SQLAnalyser) and the cllient
> is
> used to seeing the numbers in a pre-formatted pattern as they currently
> use
> ACCESS and the FORMAT function. Myself and my buddy are going slowly
> blind/mad having to cast/convert values stored as money into strings to
> get
> $'s and commas!
> Slainte,
> Taggart
>
>

MONEY FORMAT presentation

Hi all,
I am tryng to locate the SQLServer vesion of Informix's DBMONEY env variable
which is used in the Informix env by tools like ISQL and I4GL to format
values stored as type MONEY into a nice presentation pattern. Is there such a
property for SQLServer?
Why am I looking for this? Basically the application that we are building
handles all this preso stuff at the front-end, problem is we are trying to
rapid prototype a number of MIS reports (in SQLAnalyser) and the cllient is
used to seeing the numbers in a pre-formatted pattern as they currently use
ACCESS and the FORMAT function. Myself and my buddy are going slowly
blind/mad having to cast/convert values stored as money into strings to get
$'s and commas!
Slainte,
TaggartTaagart
DECLARE @.m AS DECIMAL (18,3)
SET @.m=100554545.36
SELECT convert(varchar,cast(@.m as money),1)
"Taggart" <Taggart@.discussions.microsoft.com> wrote in message
news:11E0F555-2BEF-4424-807C-3D6CEF31F6B7@.microsoft.com...
> Hi all,
> I am tryng to locate the SQLServer vesion of Informix's DBMONEY env
> variable
> which is used in the Informix env by tools like ISQL and I4GL to format
> values stored as type MONEY into a nice presentation pattern. Is there
> such a
> property for SQLServer?
> Why am I looking for this? Basically the application that we are building
> handles all this preso stuff at the front-end, problem is we are trying to
> rapid prototype a number of MIS reports (in SQLAnalyser) and the cllient
> is
> used to seeing the numbers in a pre-formatted pattern as they currently
> use
> ACCESS and the FORMAT function. Myself and my buddy are going slowly
> blind/mad having to cast/convert values stored as money into strings to
> get
> $'s and commas!
> Slainte,
> Taggart
>
>|||Hi Uri,
That's much better, but still missing the $'s. Apart from hardwiring the $
sign and then concatanating this to the result, any ideas?
What I don't get is the need to cast a column that is already set as money
(pity I didn't use decimal!?) to money, maybe we are missing something
fundamental but isn't this just consuming CPU resource for no apparent reason?
As ex-informix guys we are somewhat puzzled by this and, on a similar point,
all the manipulation one has to undertake for datetime columns when you only
want to use the date portion - presumably something to do with no date
datatype in SQLServer, which is something we find very strange both in the
additional manipulation and also in terms of datastorage?
Slainte,
Taggart|||On Sun, 4 Jun 2006 19:53:02 -0700, Taggart wrote:
>Hi Uri,
>That's much better, but still missing the $'s. Apart from hardwiring the $
>sign and then concatanating this to the result, any ideas?
Hi Taggart,
SQL Server is not intended to be used for formatting - that task is
usually handled by the front-end. As a result, SQL Server doesn't have
as much formatting features as some other tools.
If you're sure that your application is only used in dollar-using
countries, hardcoding the $ sign is probably the best solution. If the
app might be used all over the world, you'd be better off letting the
front-end determine the correct currency symbol from the useer's locale
settings and append that symbol to the amount.
>What I don't get is the need to cast a column that is already set as money
>(pity I didn't use decimal!?) to money, maybe we are missing something
>fundamental but isn't this just consuming CPU resource for no apparent reason?
There's no need for the extra CAST - Uri used it becuase the variable he
used in his example was not money. If your column is monmey, you can
just use
SELECT convert(varchar, Column_Name, 1)
>As ex-informix guys we are somewhat puzzled by this and, on a similar point,
>all the manipulation one has to undertake for datetime columns when you only
>want to use the date portion - presumably something to do with no date
>datatype in SQLServer, which is something we find very strange both in the
>additional manipulation and also in terms of datastorage?
Not having seperate date and time datatypes is indeed a pity.
However, there's no need for much manipulation to remove the time
portion from a datetime column. If you need the result as datetime (only
withoout time portion - or rather, with the default midnight time
portion), use
SELECT DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP), 0)
And if you need it in character format (for presentation purposes), use
CONVERT with an appropriate style parameter and define the length of the
result such that the time will be cut off, for instance
SELECT CONVERT(char(8), CURRENT_TIMESTAMP, 112)
--
Hugo Kornelis, SQL Server MVP|||Thanks Hugo your use of convert is much. much neater than my attempt!
"Hugo Kornelis" wrote:
> On Sun, 4 Jun 2006 19:53:02 -0700, Taggart wrote:
> >Hi Uri,
> >
> >That's much better, but still missing the $'s. Apart from hardwiring the $
> >sign and then concatanating this to the result, any ideas?
> Hi Taggart,
> SQL Server is not intended to be used for formatting - that task is
> usually handled by the front-end. As a result, SQL Server doesn't have
> as much formatting features as some other tools.
> If you're sure that your application is only used in dollar-using
> countries, hardcoding the $ sign is probably the best solution. If the
> app might be used all over the world, you'd be better off letting the
> front-end determine the correct currency symbol from the useer's locale
> settings and append that symbol to the amount.
> >What I don't get is the need to cast a column that is already set as money
> >(pity I didn't use decimal!?) to money, maybe we are missing something
> >fundamental but isn't this just consuming CPU resource for no apparent reason?
> There's no need for the extra CAST - Uri used it becuase the variable he
> used in his example was not money. If your column is monmey, you can
> just use
> SELECT convert(varchar, Column_Name, 1)
> >
> >As ex-informix guys we are somewhat puzzled by this and, on a similar point,
> >all the manipulation one has to undertake for datetime columns when you only
> >want to use the date portion - presumably something to do with no date
> >datatype in SQLServer, which is something we find very strange both in the
> >additional manipulation and also in terms of datastorage?
> Not having seperate date and time datatypes is indeed a pity.
> However, there's no need for much manipulation to remove the time
> portion from a datetime column. If you need the result as datetime (only
> withoout time portion - or rather, with the default midnight time
> portion), use
> SELECT DATEADD(day, DATEDIFF(day, 0, CURRENT_TIMESTAMP), 0)
> And if you need it in character format (for presentation purposes), use
> CONVERT with an appropriate style parameter and define the length of the
> result such that the time will be cut off, for instance
> SELECT CONVERT(char(8), CURRENT_TIMESTAMP, 112)
> --
> Hugo Kornelis, SQL Server MVP
>

Money format error

I use asp.net 2.0 and sql server 2005 for a web site (and Microsoft enterprise library).When I run aplication at local there is no problem but at the server I take this error:

Disallowed implicit conversion from data type varchar to data type money, table 'dbname.dbo.shopProducts', column 'productPrice'. Use the CONVERT function to run this query.

productPrice coloumn format is money. It was working correctly my old server but now it crashed.How can I solve this problem? And why it isn't work same configuration?

My code:

decimal productPrice;

Database db =DatabaseFactory.CreateDatabase("connection");

string sqlCommand ="update shopProducts set .................,productPrice='" + productPrice.ToString().Replace(",",".") +"',................where productID=" + productID +" ";

db.ExecuteNonQuery(CommandType.Text, sqlCommand)

Decimal should be able to covert to SqlMoney implicitly, why you convert the price to string before update it to the table? However, it's better to useParameterized Queries as possible as you can.

money format ..need some help..please

Hi everybody.
Here's my Product table

ID int,
Title nvarchar(50),
Price money

How can I get value from price field like this
IF PRICE is 12,000.00 it will display 12,000
IF PRICE is 12,234.34 it will display 12,234.34

Thanks very much...I am a beginner. Sorry for foolish question

Formatting is generally applied at the page where the data is going to be displayed as opposed to altering the datasource itself.

If you were going to databind your sql data to something such as a GridView, then you can alter the data's format by specifying a DataFormatString.

for currency you can use: {0:c}
for numeric data with 2 digits after the decimal you can use: {0:n2}

For example:

 
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Price" DataFormatString="{0:c}" HtmlEncode=False HeaderText="With Currency Symbol" /> <asp:BoundField DataField="Price" DataFormatString="{0:n2}" HtmlEncode=False HeaderText="Without Currency Symbol" /> </Columns></asp:GridView>
If you are actually looking to alter the data in sql server, please let us know.
|||

Thanksmbanavige very much for your answer. I use DataList to display my items and I want to display1 pricein my page. I try to use this code

<%If((Eval("Price") *100) mod 100 >0) { %>

<%#Eval("Price","{0:N2}")%>

<% } else {

%> <%#Eval("Price","{0:c}") %>

<% } %> . But it seem wrong. How can I do something like that ?

|||

I'm not sure i follow what you're trying to do with that code. If you want one price, then choose only one of the sample formats i provided

use this: <%#Eval("Price","{0:c}") %>

or this: <%#Eval("Price","{0:N2}")%>

but not both at the same time.

Unless you're dealing with unpredictalbe currencies, i'd probably just go with: <%#Eval("Price","{0:c}") %>

|||

mbanavige:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="Price" DataFormatString="{0:c}"
HtmlEncode=False HeaderText="With Currency Symbol" />
</Columns>
</asp:GridView>

Hi Mike,

What would cause a page with say ten colums, all formated in the same manner, to only have five colums display currency correctly and the remainder to just be numbers?

I have this weird scenario going on and it is not a syntax error, as I have checked in dozens of times.

|||

Did you set HtmlEncode to False for all the columns?

|||

Yes I did. I just did a character by character study of two similar pages. The first page is for one State the next page for a different State. Every single character is identical. Therefore I have no option to conclude that there must be some fundamental change in the SQL database tables themselves. each State has it's own table. I will go in and make sure that each field is set to exactly the same data type.

If there is any other possibility that you can think of, please let me know. I am certain that this is not a code issue, the code is working, the reason I am not getting the formatting to work is probably because what is expected in the DB table, is something else. I'll drop you a line after I have checked the tables.

|||

Oaky, I was correct, the problem was in the database. The fields in question on the working table were 'money' and the same fields in the non-working table were 'float'. The instant I changed over to 'money', the web pages formatted perfectly.

There is an interesting sideline to this. In the beginning all state tables were identical, and the database itself was hosted on remote servers in Dallas, Texas in the USA. The database is now hosted on remote servers in Sydney, Australia and when the databse was transferred it somehow mysteriously changed. The technique of restoring a backup on the new server, then attaching it, was how we did the transfer, but it was not 100% flawless. We could not then nor now figure out why some very minor changes occured, perhaps there may have been some slight version differences on server software.

At any rate it's all fixed now, so the moral to the tale is this, don't always assume your code is incorrect, sometimes, it might be other things, as in this case, an issue with the database.

Best wishes.

money format

Hi.
I have a money field and its value is greater than a thousand.For example its value = 32.885,60
I want to show the field's format like this (this number's format).
I mean the thousand separator should be .(dot) and the decimal separator should be ,(comma)
And I want two digit after the decimal separator.All these conditions matches with this number(32.885,60)
Could you help me?

hi muhsin,

write an embeddede function which returns your amount like this: amount.ToString("N")

|||

Dear,

Write the embedded fucntion (=format(field,'fomat')

HT

from

sufian

|||Can you write for me please?
I tried but it didn't work.
What should I write in the format style area?|||

Could you format the string in code and then do a string replace to replace the , with a . and the . with a ,?

|||

Hi Muhsin,

sorry this isn't an answer for you, but very curious as to the currency you are working in?

I am used to formatting it the other way around (32,885.60)

99

|||

this is your function:

shared function GetCurrencyFormat(byVal Amount As Double) As String

return Amount.ToString("N")

end function

to call the function go to your layout and write in the cell or textbox or whatever the following:

=Code.GetCurrencyFormat(Amount)

thats it

|||

SpaceCadet wrote:

this is your function:

shared function GetCurrencyFormat(byVal Amount As Double) As String

return Amount.ToString("N")

end function

to call the function go to your layout and write in the cell or textbox or whatever the following:

=Code.GetCurrencyFormat(Amount)

thats it

But this is not I want.
This is already a format in the properties of the textbox.
You don't need to write a function for this.
I want the thousand seperator to be dot and the decimal seperator to be comma.
Your solution's result is for example 15,250.30.
But I want 15.250,30.
Thanks anyway.
If you find another solution , please share it with me!|||You can accomplish this by adjusting the Language property for the textbox, or the entire report to a language that uses this format. The language settings can be specific to just number formats when just setting the NumeralLanguage property on the textbox. After setting these properties, just use "N" as the format code.

See the following link for more information about International Considerations for Reporting Services:
http://msdn2.microsoft.com/en-us/library/ms156493.aspx

Money format

hello everyone...,

i have problem in money format...

i have moneytable is containning:

userid money

A 20000,0000

B 40000,0000

userid type varchar(50)

money type money

i have store procedure like this:

ALTER PROCEDURE [dbo].[paid]
(
@.userid AS varchar(50),

@.cost AS money,
@.message as int="1" output
)
AS

begin transaction
declare @.money as money

select @.money = money
from moneytable
where userid=@.userid

if (@.money > @.cost)
begin
set @.money = @.money - @.cost
UPDATE moneytable
SET money = @.money
WHERE userid=@.userid
set @.message ='1'
end
else
begin
set @.message = '2'
end

COMMIT TRANSACTION

when i execute this procedure. i insert value to

userid A

cost 100,0000

it can not decrease, because cost 100,0000 is same with 1000000, why is like that?

i want cost 100,0000 is same with 100.

how can i do that?

thx...

use the dot. character in ploce of comma, "," is used for sepration not for decreasing the amount of number.

e.g:

100.0000=100

100,0000=1000000

thanks

|||

thx hkhaled...,

how can i make it todot. format?

because the system automatic to make all money incomma, format

in my city, i use money format like this example:

Rp 7.000,00 =7000

Rp 100,00 =100

how can i do it?

is there need to change type in database?

thx...

|||

this is usually inhereted from your system Control Panel if you want to have it changed go to your Computer Control Panel and then under theRegional and Language Options, Format tab,Customize this Format, click oncurrency tab and change theDecimal Symbol and Digits Grouping Symbol to the choice of your own.

thanks

|||

thx hkhaled..

it can not too..

my friend said to change money type in visual studio 2005 system. is it true?

how to change it?

thx..

|||

Maybe this example will help you:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

protected void Button1_Click(object sender, EventArgs e)
{
decimal dec = decimal.Parse(TextBox1.Text);
System.Globalization.NumberFormatInfo inf = new System.Globalization.NumberFormatInfo();
inf.CurrencyDecimalSeparator = ".";
Response.Write(dec.ToString(inf));
}

|||

thx kipo..

but i am not use code behind.

i am only execute data in store procedure..

when i execute, it display page told me to insert value like that:

userid default

cost default

message default

so i insert the value like that:

userid A

cost 100,0000

message default

after i click ok, it should decrease that cost with money in the table.

my moneytable display like that:

userid money

A 20000,0000

B 40000,0000

but it not decrease . because the system read 100,0000 is same with 1000000.

if i insert 1,0000 , it can decrease. and the money from userid A in table became 10000,0000.

i am confusion... the system can read data in table like 10000,0000=10000 .but can not read in store procedure..

it seem in store procedure read ike 100,0000=1000000.

how should i do? is there i need change code in store procedure?

thx...

money format

Hi.
I have a money field and its value is greater than a thousand.For example its value = 32.885,60
I want to show the field's format like this (this number's format).
I mean the thousand separator should be .(dot) and the decimal separator should be ,(comma)
And I want two digit after the decimal separator.All these conditions matches with this number(32.885,60)
Could you help me?

hi muhsin,

write an embeddede function which returns your amount like this: amount.ToString("N")

|||

Dear,

Write the embedded fucntion (=format(field,'fomat')

HT

from

sufian

|||Can you write for me please?
I tried but it didn't work.
What should I write in the format style area?|||

Could you format the string in code and then do a string replace to replace the , with a . and the . with a ,?

|||

Hi Muhsin,

sorry this isn't an answer for you, but very curious as to the currency you are working in?

I am used to formatting it the other way around (32,885.60)

99

|||

this is your function:

shared function GetCurrencyFormat(byVal Amount As Double) As String

return Amount.ToString("N")

end function

to call the function go to your layout and write in the cell or textbox or whatever the following:

=Code.GetCurrencyFormat(Amount)

thats it

|||

SpaceCadet wrote:

this is your function:

shared function GetCurrencyFormat(byVal Amount As Double) As String

return Amount.ToString("N")

end function

to call the function go to your layout and write in the cell or textbox or whatever the following:

=Code.GetCurrencyFormat(Amount)

thats it

But this is not I want.
This is already a format in the properties of the textbox.
You don't need to write a function for this.
I want the thousand seperator to be dot and the decimal seperator to be comma.
Your solution's result is for example 15,250.30.
But I want 15.250,30.
Thanks anyway.
If you find another solution , please share it with me!|||You can accomplish this by adjusting the Language property for the textbox, or the entire report to a language that uses this format. The language settings can be specific to just number formats when just setting the NumeralLanguage property on the textbox. After setting these properties, just use "N" as the format code.

See the following link for more information about International Considerations for Reporting Services:
http://msdn2.microsoft.com/en-us/library/ms156493.aspx

Money field

I am using Sql Server reporting services 2000. I have a money field which should show postive or negative amount. I used the format as currency. But it shows as ($40.00) for negative amount(it is placing it in braces) and $40.00 for positive amount. How can I show -$40.00??

HI, Nissan:

You can use this expression instead: =FormatCurrency(Fields!UnitPrice.Value,,,False,)

If i misunderstand you about your question, please feel free to correct me and i will try to help you with more information.

I hope the above information will be helpful. If you have any issues or concerns, please let me know. It's my pleasure to be of assistance

|||

HI, Nissan:

We are marking this issue as "Answered". If you have any new findings or concerns, please feel free to unmark the issue.
Thank you for your understanding!

Money data type format

Why does SQL add 4 zeros at the end of a money data type? I have to format my strings once they are retrieved because of this. I am not sure if I did something wrong, but shouldn't it only have 2 trailing zero's?No, thats the standard format. If you want 2 decimals, you need to use Decimal datatype with precision set to 2.