我正在自定义使用原始SQL和模型的旧式ASP.NET MVC应用程序。我要提交的数据具有两个小数位,例如4,615.38、11.51。当我尝试提交数据时遇到错误
将数据类型varchar转换为数字时出错
我需要有关如何正确定义表和存储过程的帮助。我应该在表定义或LEFT
函数中使用任何强制转换吗?
在TaxTableController.cs中,我有:
Models.TaxTable.Zimra zimra = new Models.TaxTable.Zimra();
zimra.TableName = Helpers.SanitiseInput(Convert.ToString(formcollection["TableName"]));
zimra.TierName = Helpers.SanitiseInput(Convert.ToString(formcollection["TierName"]));
zimra.MinSalary = Convert.ToDouble(formcollection["MinSalary"]);
zimra.MaxSalary = Convert.ToDouble(formcollection["MaxSalary"]);
zimra.CreatedOn = DateTime.Now;
zimra.CreatedBy = Convert.ToString(Session["UserId"]);
if (ModelState.IsValid)
{
using (SqlConnection conn = new SqlConnection(Helpers.DatabaseConnect))
{
SqlCommand cmd = new SqlCommand("SaveZimraTable", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TableName", zimra.TableName);
cmd.Parameters.AddWithValue("@TierName", zimra.TierName);
cmd.Parameters.AddWithValue("@MaxSalary", zimra.MaxSalary);
cmd.Parameters.AddWithValue("@MinSalary", zimra.MinSalary);
cmd.Parameters.AddWithValue("@CreatedBy", zimra.CreatedBy);
cmd.Parameters.AddWithValue("@CreatedOn", zimra.CreatedOn);
我的表定义如下(使用Script Table As--Create):
[Id] [int] IDENTITY(1,1) NOT NULL,
[MinSalary] [decimal](18, 2) NOT NULL,
[MaxSalary] [decimal](18, 2) NOT NULL,
[CreatedBy] [varchar](50) NULL,
[TableName] [varchar](50) NULL,
[TierName] [varchar](50) NOT NULL,
[CreatedOn] [datetime] NULL,
CONSTRAINT [PK__Zimra__3214EC07397C51AA] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
存储过程如下:
CREATE PROCEDURE [dbo].[SaveZimraTable]
@TableName varchar(50),
@TierName varchar(50),
@MinSalary decimal(18,2),
@MaxSalary decimal(18,2),
@CreatedBy varchar(50),
@CreatedOn datetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
INSERT INTO Zimra VALUES (@TableName,@TierName,@MinSalary,@MaxSalary,@CreatedBy,@CreatedOn)
END
GO
答案 0 :(得分:2)
始终在插入语句中指定列列表。否则,您必须为所有列(标识列除外)指定值,并且必须以正确的顺序进行操作-显然,语句中的情况并非如此。此外,如果更改表结构(通过添加列或切换列顺序),则可能会破坏语句。
INSERT INTO Zimra (TableName, TierName, MinSalary, MaxSalary, CreatedBy, CreatedOn)
VALUES (@TableName,@TierName,@MinSalary,@MaxSalary,@CreatedBy,@CreatedOn)
此外,如注释中所述,请勿使用AddWithValues
向您的命令对象添加参数-而是使用Add
:
cmd.Parameters.Add("@TableName", SqlDbType.VarChar).Value = zimra.TableName;
// do the same for all parameters.