Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Insert into sql with "-" char



I have result    exp  1.00
 
How to insert into to have value -1.00?
 
Thank you


What I have tried:

using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.mp_list (iznos_sa_pdv, kupac) VALUES(@iznos_sa_pdv)", con))  
{  
cmd.Parameters.Add("@iznos_sa_pdv", SqlDbType.VarChar, 255).Value = ukupnolabel.Text;  
}  
Posted
Updated 12-Dec-19 1:30am
Comments
Afzaal Ahmad Zeeshan 12-Dec-19 7:07am    
Never mind

And what gets stored in the database after this code executes?
Goran Bibic 12-Dec-19 7:16am    
This is part of code, in database is value 1.00
I need to save in database value -1.00

Need Help like this or...

cmd.Parameters.Add("@iznos_sa_pdv", SqlDbType.VarChar, 255).Value = '-'ukupnolabel.Text;
Dave Kreskowiak 12-Dec-19 8:41am    
Why are you storing numbers as text in the database?

A "brute-force" solution could be as simple as:
C#
cmd.Parameters.Add("@iznos_sa_pdv", SqlDbType.VarChar, 255).Value = $"-{ukupnolabel.Text}";

But be careful: if there is already a negative value in the textbox, you will end up with a value which is not a proper number.

It may be better to parse the string to a double, negate it, and provide the result back to the query:
C#
double value;
if (double.TryParse(ukupnolabel.Text, out value))
{
   value = -value;
   cmd.Parameters.Add("@iznos_sa_pdv", SqlDbType.VarChar, 255).Value = value.ToString();
}
else
{
   // Invalid value provided.
}


But there is an issue with your query: you specifiy two columns for INSERT statement but only provide a value for one of them.

Moreover, you should use proper data types in your database: if iznos_sa_pdv column is meant to hold real numbers, then it should not have a varchar type in the first place. It would then allow you to write
C#
double value;
if (double.TryParse(ukupnolabel.Text, out value))
{
   value = -value;
   cmd.Parameters.Add("@iznos_sa_pdv", SqlDbType.Float).Value = value;
}
else
{
   // Invalid value provided.
}
 
Share this answer
 
v2
Comments
Goran Bibic 12-Dec-19 7:37am    
cmd.Parameters.AddWithValue("@pdv", iznosSaPdvom - (novaCijenaBezPdva * double.Parse(row.Cells["kolicina"].Value.ToString())));


How to put here - ?
phil.o 12-Dec-19 7:38am    
Don't do it in a single line. Decompose your values and apply the logic I provided in my solution.
If you want to change a value in an existing row, you don't INSERT - that always adds a new row.
Instead, you use UPDATE:
SQL
UPDATE MyTable SET MyColumn = @MyParameter WHERE MyIDColumn=@IDOFTheRowToChange
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900