简体   繁体   English

错误指定的强制转换无效

[英]Error Specified cast is not valid

I have the below function 我有以下功能

SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
int h = (int)cmd.ExecuteScalar() + 1;
txtID.Text = h.ToString();
cn.Close();

How to fix this Error: 如何解决此错误:

Specified cast is not valid. 指定的演员表无效。

given your code I feel the easiest way to fix the logic is to edit the SQL to 给定您的代码,我认为修复逻辑的最简单方法是将SQL编辑为

select ISNULL(max(ID),0) from EP_PATTERNS

To better understand what this does you can run this SQL in SSMS: 为了更好地理解这是什么,您可以在SSMS中运行以下SQL:

DECLARE @table table (ID int);
SELECT MAX(ID) FROM @table;
SELECT ISNULL(MAX(ID), 0) FROM @table;

Whether table EP_PATTERNS contains any rows? EP_PATTERNS是否包含任何行? Otherwise you a trying to cast NULL to int and fails. 否则,您将尝试将NULLint并失败。

You code should looks like: 您的代码应类似于:

SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
var value = (int?)cmd.ExecuteScalar();
int maxId = value.HasValue ? value.Value + 1 : 0;  //Increase value or default it to zero
txtID.Text = maxId.ToString();
cn.Close();

Using coalesce you can achieve this: 使用coalesce可以实现以下目的:

con.Open();
cmd.Connection = con;
cmd.CommandText = "select coalesce(max(user_id),0)+1 from user_master";
int user_id = int.Parse(cmd.ExecuteScalar().ToString());
txt_user_id.Text = user_id.ToString();
con.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM