Problem Inserting Decimal Value Into SQL Server 2000
Aug 19, 2007
In my VS 2005 windows control I am inserting a record into a table using a proc.
One of the fields "Accuracy" should look like this 66.4, but when I isnert it from the proc itlooks like 66.0. If I bypass my proc and use an inser statement from SQL quey analyzer it look like it should 66.4.
--Insert the new game score
--===============================================================================================
insert into wmTurnTileScores
(PlayerName, Score, Rounds, Accuracy, CorrectPicks, IncorrectPicks)
values (@PlayerName, @Score, @Rounds, @Accuracy, @CorrectPicks, @IncorrectPicks)
--===============================================================================================
GO
Hi i have a insert stored procedure, which i need to insert a label.text which is 12.99 the problem i have is that it is inserting as 13.00 any ideas what i need to do??Dim Price As Decimal = CostLabel.Text then i am inserting with this param.... command113.Parameters.Add("@Cost", SqlDbType.Decimal).Value = Price
Im trying to insert a decimal into SQL 2000 using a stored procedure. I can successfully insert it using a direct T-SQL statement inside the code, but I cant insert it correctly when calling for a stored procedure.
For instance 12.5 will insert as 12.
Here is my SQL Parameter code: [code] MyCommand.Parameters.Add(New SqlParameter("@Num", SqlDbType.Decimal)) MyCommand.Parameters("@Num").Precision = 5 MyCommand.Parameters("@Num").Scale = 2 MyCommand.Parameters("@Num").Value = Convert.ToDecimal(TextBox1.Text) [/code]
I also declared @Num to be a decimal in my Stored Procedure.
As you can see I give the Parameter more than enough detail about the data type as well as convert the textbox value to a decimal, but it still rounds the value to an integer like data.
Again using a direct T-SQL statement inside the code works OK, but the stored procedure will not. ANyone got any ideas why this is happening.
I've been doing this in Access, but cannot find the answer to how to do it with SQL Server. From a web form, a user can select a number of different dates. The selected dates are held as text (not DateTime) in an ArrayList. Clicking the Submit button writes the contents of the form to a database table. This works for Access: insSQL &= "VALUES (@typEvent, @starts, @ends, @starts, @ends, @attend, @title, @room, @department, @contact, @address, @telephone, @email, @telefax, " For i = 0 to datesArray.Count - 1 insSql &= datesArray.Item(i) Next i insSQL &= "VALUES (@typEvent, @starts, @ends, @starts, @ends, @attend, @title, @room, @department, @contact, @address, @telephone, @email, @telefax, " For i = 0 to datesArray.Count - 1 insSql &= "#" & datesArray.Item(i) & "#, " Next i It doesn't work for SQL Server, and when trying to insert the value "01/29/2007" I get the error message: "The name '#1' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted." I have also tried the line: For i = 0 to datesArray.Count - 1 insSql &= satesArray.Item(i) Next i and get: "Incorrect syntax near the keyword 'VALUES'." I'm not sure where to find the information to correct my error. Any help would be appreciated. Tinker
This is my code: Dim myConn As SqlConnection Dim mycmd As SqlCommand myConn = New SqlConnection("Initial Catalog=science;" & _ "Data Source=localhost;Integrated Security=SSPI;") mycmd = New SqlCommand("INSERT into STEP1(firstname) VALUES('Amin')", myConn) myConn.Open() mycmd.ExecuteNonQuery() myConn.Close()
This is the error message I get: The name 'firstname' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.
Edited by SomeNewKid. Please post code between <code> and </code> tags.
This is probaly the easiest question you've ever read but here goes.
I have a simple checkbox value that i want to insert into the database but whatever i do it does not seem to let me.
Here is my code:
Sub AddSection_Click(Sender As Object, e As EventArgs) Dim myCommand As SqlCommand Dim insertCmd As String ' Build a SQL INSERT statement string for all the input-form ' field values. insertCmd = "insert into Customers values (@SectionName, @SectionLink, @Title, @NewWindow, @LatestNews, @Partners, @Support);" ' Initialize the SqlCommand with the new SQL string. myCommand = New SqlCommand(insertCmd, myConnection) ' Create new parameters for the SqlCommand object and ' initialize them to the input-form field values. myCommand.Parameters.Add(New SqlParameter("@SectionName", SqlDbType.nVarChar, 50)) myCommand.Parameters("@SectionName").Value = Section_name.Value
If New_window.Checked = false Then myCommand.Parameters.Add(New SqlParameter("@NewWindow", SqlDbType.bit, 1)) myCommand.Parameters("@NewWindow").Value = 0 else myCommand.Parameters.Add(New SqlParameter("@NewWindow", SqlDbType.bit, 1)) myCommand.Parameters("@NewWindow").Value = 1 End If
If Latest_news.Checked = false Then myCommand.Parameters.Add(New SqlParameter("@LatestNews", SqlDbType.bit, 1)) myCommand.Parameters("@LatestNews").Value = 0 else myCommand.Parameters.Add(New SqlParameter("@LatestNews", SqlDbType.bit, 1)) myCommand.Parameters("@LatestNews").Value = 1 End If
If Partners.Checked = false Then myCommand.Parameters.Add(New SqlParameter("@Partners", SqlDbType.bit, 1)) myCommand.Parameters("@Partners").Value = 0 else myCommand.Parameters.Add(New SqlParameter("@Partners", SqlDbType.bit, 1)) myCommand.Parameters("@Partners").Value = 1 End If
If Support.Checked = false Then myCommand.Parameters.Add(New SqlParameter("@Support", SqlDbType.bit, 1)) myCommand.Parameters("@Support").Value = 0 else myCommand.Parameters.Add(New SqlParameter("@Support", SqlDbType.bit, 1)) myCommand.Parameters("@Support").Value = 1 End If
myCommand.Connection.Open() ' Test whether the new row can be added and display the ' appropriate message box to the user. Try myCommand.ExecuteNonQuery() Message.InnerHtml = "Record Added<br>" & insertCmd Catch ex As SqlException If ex.Number = 2627 Then Message.InnerHtml = "ERROR: A record already exists with " _ & "the same primary key" Else Message.InnerHtml = "ERROR: Could not add record, please " _ & "ensure the fields are correctly filled out" Message.Style("color") = "red" End If End Try
I am trying to insert quoted strings into a database table, however, I cannot remember how to do so. For instance, I am trying to insert the following values into a SQL table:
My Friend's "Happy Birthday"
exactly as they are listed. How can I do that in a SQL insert statement?
I am manually replicating parts of a SQL Server CE database (running windows mobile 5.0) to a centralized SQL Server 2000 database.
My program is throwing an exception whenever I try to insert an image data type into the 2000 server from the PDA. I am using parameterized queries.
Error is as follows: [error] System.Data.SqlClient.SqlConnection.OnError() at System.Data.SqlClient.SqlInternalConnection.OnError() at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() at System.Data.SqlClient.TdsParser.Run() at System.Data.SqlClient.ExecuteReader() at System.Data.SqlClient.ExecuteNonQuery() at PDASync.Database.ExecuteIDRemote() [/error]
The code for my ExecuteIDRemote method works fine for other queries. It also works if I remove the image column from the offending query.
Hi, I would preciated if some could help me with this problem. My have used Mysql database and now i have to change my database to sql server. I have made a dump file from mysql db and i would like to insert that dumb file to sql server. Have any idea how it is possible?
Hi All, I am working on SQL Server 2000 ver 7.0. The Collation set for my Database Server is Latin. I want some way by which i can insert Japanese Characters in Database. Is it related to change the Collation or any other encoding format of database. Suppose the table 'Person' has fields id, Name, city If i enter name in a japanese characters, then while storing it does not recongnises this format.
insert into person values(8,'満員','osaka')
id name city 8 ?? osaka At the place of name '??' is displayed.
we have tables with many image columns. We fill these image columns via ODBC and SQLPutData as described in MSDN etc (using SQL_LEN_DATA_AT_EXEC(...), calling SQLParamData and sending the data in chunks of 4096 bytes when receiving SQL_NEED_DATA).
The SQLPutData call fails under the following conditions with sqlstate 08S01
- The database resides on SQL Server 2000 - The driver is SQL Native Client - The table consists e.g. of one Identity column (key column) and nine image columns - The data to be inserted are nine blocks of data with the following byte size:
1: 6781262 2: 119454
3: 269 4: 7611
5: 120054
6: 269
7: 8172
8: 120054
9: 269 The content of the data does not matter, (it happens also if only zero bytes are written), nor does the data origin (file or memory).
All data blocks including no 7 are inserted. If the first chunk of data block 8 should be written with SQLPutData the function fails and the connection is broken. There are errors such as "broken pipe" or "I/O error" depending on the used network protocol.
If data no 7 consists of 8173 bytes instead of 8172 all works again. (Changing the 4096 chunk size length does not help)
Has anybody encountered this or a similar phenomenon?
I am working with a legacy SQL server database from SQL Server 2000. I noticed that in some places that they use decimal data types, that I would normally think they should be using integer data types. Why is this does anyone know?
Example: AutomobileTypeId (PK, decimal(10,0), not null)
I am creating a table on SQL Server. One of the columns in this new table contains whole integer as wells as decimal values (i.e. 4500 0.9876). I currently have this column defined as Decimal(12,4). This adds 4 digits after the decimal point to the whole integers. Is there a data type that will have the decimal point only for decimal values and no decimal point for the whole integers?
I would like to cast (convert) data type decimal(24,4) to decimal(21,4). I could not do this using standard casting function CAST(@variable as decimal(21,4)) or CONVERT(decimal(21,4),@variable) because of the following error: "Arithmetic overflow error converting numeric to data type numeric." Is that because of possible loss of the value?
I wanted to convert a dataset from vb.net (2.0) to an .XLS file, by MS Jet. My national standard is using decimal commas, not decimal points for numbers signing the beginning of decimal places. But the MS Jet Engine uses decimal point,in default. Therefore, in the Excel file only string formatted cells can welcome this data, not number formatted. How can I solve or get around this problem? (with jet if it possible) iviczl
I'd like to convert a Decimal value into a string so that the entireoriginal value and length remains intact but there is no decimal point.For example, the decimal value 6.250 is selected as 06250.Can this be done?
I am designing some reports for a German branch of my company and need to replace decimal point with a comma and the thousand comma seperator with a decimal point.
e.g. ‚¬1,500,123.00 to ‚¬1.500.123,00
Is there a property that I can change in the report designer to allow this to happen or is this something I need to convert in a Stored Proc.
I have been trying to add values to a database and it keeps failing i have no idea what i am doing wrong please help the code is asp.net using vb. I have been having serious trouble passing check boxes in forms from day one both singularly and dynamically from datagrids if someone could show me some sample code of how to pass these sort of values into the component and on to the query in this way i would very much appreciate it.
Fuzzygoth
the error returned is
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: INSERT statement conflicted with COLUMN FOREIGN KEY constraint 'tblStation_FK00'. The conflict occurred in database 'TealSQL', table 'tblTravelPoint', column 'travelpointID'. The statement has been terminated.
I have marked the area of the code the error is returned in the colour Violet and with a ##
The code i am using is below
## The aspx page ##
<%@ Page Language="vb" Debug="true" Trace="True" Inherits="Devotion2Motion.AdminComp" Src="../CodeBehind/AdminModule.vb" %> <!-- Binds the ActivityResortInfo.ascx user control to the page --> <%@ Register TagPrefix="UserContol" TagName="D2MHeader" Src="../UserControls/Header.ascx" %> <%@ Register TagPrefix="UserContol" TagName="D2MFooter" Src="../UserControls/Footer.ascx" %> <%@ Register TagPrefix="UserContol" TagName="TravelPointDD" Src="../UserControls/TravelPointDD.ascx" %> <script language="vb" runat="server">
Sub Page_Load()
If IsPostback = True Then
Dim aInternational As Integer
Dim Station As String = Request.Form("StationFrm") Dim Type As String = Request.Form("TypeFrm") Dim Address1 As String = Request.Form("address1Frm") Dim Address2 As String = Request.Form("address2Frm") Dim City As String = Request.Form("cityFrm") Dim International As String = Request.Form("InternationalFrm") Dim TravelPoint As Integer = Request.Form("_ctl5:dsTravelPointDD")
If IsNothing(International) Then aInternational = "0" Else aInternational = "1" End If
Dim AdminTravelPoints As New Devotion2Motion.AdminComp() ' Select the country dropdown list
AdminTravelPoints.AddStation(Station, Type, Address1, Address2, City, aInternational, TravelPoint)
End If
Dim ReadResultTable As New Devotion2Motion.AdminComp() ' Select the country dropdown list dsResultSet.DataSource = ReadResultTable.GetStationtbl() dsResultSet.DataBind()
End Sub
</script>
<!-- This UserControl Pulls in the header UserControl and the Div Tag Positions it #css reffrence is TopControl --> <Div Class="TopControl"> <UserContol:D2MHeader runat="server"/> </Div>
##the vb componet that passess to the sql query ##
Public Function AddStation(ByVal Station As String, ByVal Type As String, ByVal Address1 As String, ByVal Address2 As String, ByVal City As String, ByVal aInternational As Integer, ByVal TravelPoint As Integer) As SqlDataReader
' Create Instance of Connection and Command Object Dim myConnection As New SqlConnection(ConfigurationSettings.AppSettings("strConn")) Dim myCommand As New SqlCommand("sp_call_Station_Insert", myConnection)
' Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure
' Add Parameters to SPROC Dim parameterStation As New SqlParameter("@Station", SqlDbType.NVarChar, 50) parameterStation.Value = Station myCommand.Parameters.Add(parameterStation)
' Add Parameters to SPROC Dim parameterType As New SqlParameter("@Type", SqlDbType.NVarChar, 50) parameterType.Value = Type myCommand.Parameters.Add(parameterType)
' Add Parameters to SPROC Dim parameterAddress1 As New SqlParameter("@Address1", SqlDbType.NVarChar, 50) parameterAddress1.Value = Address1 myCommand.Parameters.Add(parameterAddress1)
' Add Parameters to SPROC Dim parameterAddress2 As New SqlParameter("@Address2", SqlDbType.NVarChar, 50) parameterAddress2.Value = Address2 myCommand.Parameters.Add(parameterAddress2)
' Add Parameters to SPROC Dim parameterCity As New SqlParameter("@City", SqlDbType.NVarChar, 50) parameterCity.Value = City myCommand.Parameters.Add(parameterCity)
' Add Parameters to SPROC Dim parameteraInternational As New SqlParameter("@aInternational", SqlDbType.Int, 4) parameteraInternational.Value = aInternational myCommand.Parameters.Add(parameteraInternational)
' Add Parameters to SPROC Dim parameterTravelPoint As New SqlParameter("@TravelPoint", SqlDbType.Int, 4) parameterTravelPoint.Value = TravelPoint myCommand.Parameters.Add(parameterTravelPoint)
' Execute the command myConnection.Open()
## Dim result As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
' Return the datareader Return result
End Function
## The sql stored procedure ##
CREATE PROCEDURE [dbo].[sp_call_Station_Insert] ( @Station As nVarChar(50), @Type As nVarChar(50), @address1 As nVarChar(50), @address2 As nVarChar(50), @City As nVarChar(50), @aInternational As nVarChar(50), @TravelPoint As Int ) AS
DECLARE @ConVale As nVarChar(50)
SET @ConVale = (SELECT Station FROM tblStation WHERE @Station = Station)
If @ConVale = @Station
BEGIN SELECT * FROM tblStation END ELSE BEGIN insert into tblStation (Station, Type, address1, address2, city, International, TravelPoint) values (@Station, @Type, @address1, @address2, @City, @aInternational, @TravelPoint) SELECT * FROM tblStation
Hello.I've read many topics about this problem but i couldn't figure it out.I use form where user must insert 2 dates using texboxes.-One is required and other is optional.Sql 2000 is inserting either '20061105' or '2006.11.05' on insert update but select query returns 05.11.2006 on my report. Question 1.How do I insert or update dates from my form where date is entered dd.mm.yyyy to sql 2000 table?question 2. What to do if user left optional texbox date empty.I'm using SP and function with arguments (byval texbox1.text as date, byval texbox2.text as date)and parameters @date1, sqldbtype date =texbox1.text
To anyone that is able to help....What I am trying to do is this. I have two tables (Orders, andOrderDetails), and my question is on the order details. I would liketo set up a stored procedure that essentially inserts in the orderstable the mail order, and then insert multiple orderdetails within thesame transaction. I also need to do this via SQL 2000. Right now ihave "x" amount of variables for all columns in my orders tables, andall Columns in my Order Details table. I.e. @OColumn1, @OColumn2,@OColumn3, @ODColumn1, @ODColumn2, etc... I would like to create astored procedure to insert into Orders, and have that call anotherstored procedure to insert all the Order details associated with thatorder. The only way I can think of doing it is for the program to passme a string of data per column for order details, and parse the stringvia T-SQL. I would like to get away from the String format, and gowith something else. If possible I would like the application tosubmit a single value per variable multiple times. If I do it this waythough it will be running the entire SP again, and again. Anysuggestions on the best way to solve this would be greatlyappreciated. If anyone can come up with a better way feel free. Myonly requirement is that it be done in SQL.Thank you
Hi, Assume I have a table name "myTime". This table is simply only have 1 (one) DATETIME field "MyTestTime" (also serve as a primary number).Table MyTime- MyTestTime : SQLTYPE DATETIMETo insert a new row into this field, I simply wrote :SqlCommand sqlCommand = new SqlCommand("insert into MyTime values('2006-01-09')", sqlConnection); I got the value of "2006-01-09" from a textbox or other relevan control.I realize when I try to use "SELECT * FROM MyTime" statement, MSSQL server 2000 automatically convert my date value from "2006-01-09" to "01/09/2006" (from YYYY-MM-DD to MM/DD/YYYY). I don't know why this one must be converted to MM/DD/YYYY automatically (I believe this behavior is depend on some "setting option" in my MSSQL server - but I don't know which one).The challenge is :In my country, the actual date format is like German Date format (DD-MM-YYY). Well I know this is only "Customization" problem. But how insert datetime value given from sql query to a datetime variable?// Connect to database, make a query, get the datareader result, and bla bla blaDateTime aDateTime = new DateTime;aDateTime = Convert.ToDateTime(myDataReader["PostDate"].ToString());// close connectionMy question isHow can I make sure that aDateTime's day is 09 not 01. How my program know that 09 is day not month. I can't use string.split() method because it's possible that my database setting will change from "mm-dd-yyyy" to "dd-mm-yyyy"thanks
I am having a file in which amount fields are given in a Packed Decimal format. Can anyone suggest me how I can read this data element from the file and convert it into SQL decimal datatype.
File is a fixed length. All the amount fields are given in Packed Decimal Format and rest of the fields are given in text format. How can i identify and convert only those packed decimals using SQL/.Net.
Example : a row in a file that has some packed decimals 158203508540188236252EUR20BZK0030 Å“& 20060715 0001010100010101
Hi - I have what seems like a simple problem and I cannot find an answer to it. I'm hoping someone here can help.
I want to divide 2 numbers but have the answer come back with no decimal places. I don't want to round up or down..just give me the whole number and drop the decimal places. For example:
Select units/60 as answer
And units = 280. I want the "answer" to be 4 and NOT 4.66.
DECLARE @MyPay decimal(5,9); SET @MyPay = 258.235543210; SELECT CAST(@MyPay AS decimal(5,2))
This is what the resultset is currently with the code above:
258.24
I would like to Not have the value round up. I would like to always show only the first two digits to the right of the decimal and not perform any rounding.
Hi Experts, I have an urgent needs. I want to store null for decimal type to sql server. But I do not know how to do that. I get data from user input. If the user did not enter anything in the textbox, then I want to store null to sql server. I list a piece od code below. I got error in the last line fItemObject.ChargeAmount = null;. if (!String.IsNullOrEmpty(txtDescription.Text)) myObject.LongDesc = txtLongDesc.Text; else myObject.LongDesc = null; if (!String.IsNullOrEmpty(txtAmount.Text)) myObject.Amount = Convert.ToDecimal(txtChargeAmount.Text); else myObject.ChargeAmount = null; // Then I submit the myobject to the sql server. Thank you very much in adavance!
PRINT cast(111 as decimal(38,35)) / 23 --> 4.82608695652173913043478260869565217
then here
DECLARE @Zähler decimal(38,35) , @Nenner decimal(38,35) SET @Zähler = 111.0 SET @Nenner = 23.0 PRINT cast(@Zähler as decimal(38,35)) / @Nenner --> 4.826086
Of course, in the upper part 23 is implicitly an integer, in the lower example it is declared as decimal. But what if I need to devide by 23.5? Why is dividing by an decimal reducing the results decimal positions?
Recently I have come across a requirement where i need to design a table.
There are some columns in table like below with DECIMAL Datatype:
BldgLength
BldgHeight
BldgWeight
Based on my knowledge, i know that values before Floating-Point will not be more than 4 digits.
Now as per MSDN,
Precision => 1 - 9 Storage bytes => 5
so i can create column as:
BldgLengthDECIMAL(6,2) DEFAULT 0
OR
BldgLengthDECIMAL(9,2) DEFAULT 0
Now while reading some articles, i came to know that when we do some kind of operation like SUM Or Avg, on above column then result might be larger than current data type.
So some folks suggested me that i should keep some extra space/digits considering above MATH functions, to avoid an Arithmetic Over Flow error.
So my question is what should be value of DataType for above column ?
The total quantity(sum(woitem.qtytarget) as total) result set is showing more than 6 numbers after the decimal point (example:442.2565485). How can I limit it to 2. (example:442.25)
select wo.num, sysuser.username,sum(woitem.qtytarget) as total from woitem join wo ON wo.id = woitem.woid Join moitem on moitem.id = woitem.moitemid Join mo ON mo.id = moitem.moid LEFT JOIN SYSUSER ON mo.userid = sysuser.id group by sysuser.username, num ORDER BY CAST( REPLACE( wo.num, ':', '.') as decimal(12, 3))