Capten
Capten

Reputation: 38

Data Type Money C#

Someone please help me I don't know why!

When I insert a value for example 3469,2 into my SQL Server database, I get 34692,0000

The column is of type Money and the value is the type double

// code
public void updateligne_facture(String Ref, int Qte,String Reffacture,float prixvente,int tva)
{
        SqlConnection con = new SqlConnection();
        con.ConnectionString = @"Data Source=AKRAM-PC\SQLEXPRESS;Initial Catalog=MM_DataBase;Integrated Security=True";

        con.Open();

        double prix = Qte * prixvente;

        double prix_ttc = prix * (1 + (tva/ 100D));

        String requete = "update lc SET lc.Quantite='" + Qte + "',lc.Prix_HT='"+prix+"',lc.Prix_TTC='"+prix_ttc+"' FROM LIGNES_FACTURE as lc  JOIN  MM_ARTICLE as art ON lc.ID_Article=art.ID  JOIN MM_Facture as f ON lc.ID_Facture=f.ID   WHERE art.AR_Ref='" + Ref + "' AND f.Ref='" + Reffacture + "'";
        SqlCommand command = new SqlCommand(requete, con);
        command.ExecuteNonQuery();
        con.Close();
    }

Upvotes: 1

Views: 4272

Answers (2)

Uwe Hafner
Uwe Hafner

Reputation: 4989

You probably have a problem with decimal separator. From your naming of the variables you have a french(?) system locale. So converting your variable to string inserts a comma for the decimal separator.
Your SQL Server wants a dot as a decimal separator if you use a SQL Statement. so your 3469,2 gets a 34692.

to work around it either
- use a parameterized query which will take care of it (strongly recommended) or
- format the string conversion of your variable to use a dot as a decimal separator. But this will have several downsides as: You are dependent on locales of SQL Server and are prone to injection attacks if you ever use user entries as variable input.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

According to Microsoft type mapping guide, SQL Server's Money type is mapped to decimal in C#.

Note: a proper way to make your query is to use parameters, like this:

decimal prix = (decimal)(Qte * prixvente);
decimal prix_ttc = prix * (1 + (tva/ 100M));

String requete = @"UPDATE lc 
                   SET lc.Quantite = @qte, 
                       lc.Prix_HT = @prix,
                       lc.Prix_TTC = @prix_ttc
                   FROM LIGNES_FACTURE as lc
                   JOIN  MM_ARTICLE as art ON lc.ID_Article=art.ID
                   JOIN MM_Facture as f ON lc.ID_Facture=f.ID
                   WHERE art.AR_Ref = @ref 
                     AND f.Ref = @reffacture";
SqlCommand command = new SqlCommand(requete, con);
command.Parameters.Add("@qte", qte);
command.Parameters.Add("@prix", prix);
... // Set other parameters here
command.ExecuteNonQuery();

Upvotes: 3

Related Questions