【发布时间】:2011-10-17 01:08:50
【问题描述】:
我很难弄清楚我将在 C# 中使用哪种数据类型将数据输入到我的数据库中包含小数 (5,2) 的表中。当我尝试使用 C# 十进制数据类型时,它说将数字转换为十进制时出错。当我尝试字符串时,它说它无法将 nvarchar 转换为十进制。当我尝试浮动时......同样的事情发生了,除了借口是“真正的”数据类型。 double 也失败了。
我有一个存储过程,可以将数据输入到我的表中,但是在我运行存储过程中的数据类型并将其转换为实际的十进制之前,有没有其他方法可以转换 ac# 数据类型以适应我的小数(5,2)字段?
private void btnAddClientComputer_Click(object sender, EventArgs e)
{
SQLCommands comm = new SQLCommands();
try
{
comm.AddClientComputer(int.Parse(cbCustomerID.Text), cbAction.Text, decimal.Parse(tbCost.Text));
}
catch (FormatException)
{
MessageBox.Show("The cost you have entered is invalid. Please ensure the cost is above 0, and is an actual number", "Invalid Input at Cost", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
...
public void AddClientComputer(int CustomerID, string Action, decimal Cost)
{
try
{
comm = new SqlCommand("UspAddClientComputer", conn); // Stored Procedure - see sql file
comm.Parameters.AddWithValue("@CustomerID", CustomerID);
comm.Parameters.AddWithValue("@Action", Action);
comm.Parameters.AddWithValue("@Cost", Cost);
comm.CommandType = CommandType.StoredProcedure;
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
}
...
CREATE TABLE ClientComputers
(ClientComputerID int Identity(1,1) primary key clustered
,CustomerID int
,Action varchar(7) check (Action = 'Upgrade' OR Action = 'Store')
,Cost decimal(5,2) check (Cost > 0)
,Constraint FKCustomerComputer FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
Go
...
CREATE PROCEDURE uspAddClientComputer @CustomerID int, @Action varchar(7), @Cost decimal(5,2)
AS
BEGIN TRY
BEGIN TRANSACTION TrnAddClientComputer;
INSERT INTO [TCTdb].[dbo].[ClientComputers]
([CustomerID]
,[Action]
,[Cost])
VALUES
(@CustomerID
,@Action
,@Cost)
COMMIT TRANSACTION TrnAddClientComputer;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION TrnAddClientComputer;
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
RAISERROR (@ErrorMessage,
@ErrorSeverity,
@ErrorState
);
END CATCH
GO
【问题讨论】:
-
.NET 的
decimal将是合乎逻辑且最合适的选择...您能否向我们展示一些导致您遇到此错误的代码?? -
当然。给我一点时间来编辑我的帖子
-
您是否也在使用十进制(5,2)作为存储过程参数?
-
好吧,在编辑我的帖子后,我明白了:D
-
只是想知道:你有
DECIMAL(5,2)- 你希望这种类型能够保持什么范围的值?您是否有可能期望小数点前 5 位和小数点后 2 位?那将是不正确 - dec(5,2) 表示:5 位 total,其中 2 位在小数点之后 - 所以你将自己限制在最大值的999.99。这到底是不是问题的核心??
标签: c# tsql types sqldatatypes