c#中sql语句传参错误

来源:百度知道 编辑:UC知道 时间:2024/05/30 07:29:35
小弟初入门,不知道怎么错了,为什么我的@InsertDate不行啊,但是改成一个固定的日期就可以执行了,是怎么回事,该如何去改这个语句啊,?
string FontPart = DateTime.Now.ToString("yyyyMMdd");
SqlConnection conn = new SqlConnection(Connection.ConnString);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "select top 1 Id from tbBusiness where Id like @InsertDate+'___' order by Id DESC ";
comm.CommandType = CommandType.Text;
comm.Parameters.Add("@InsertDate",SqlDbType.NVarChar,12);
comm.Parameters["@InsertDate"].Value = FontPart;
conn.Open();

SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetString(0));

}

因为你的like用到参数所以需要用动态sql才可以,即 exec(你的代码)
comm.CommandText = "select top 1 Id from tbBusiness where Id like @InsertDate+'___' order by Id DESC ";
改成comm.CommandText = "exec(select top 1 Id from tbBusiness where Id like @InsertDate+''___''order by Id DESC) ";

一定要按照程序来做。

明白了不?

参数的顺序。

程序写的乱78糟

comm.CommandText = "select top 1 Id from tbBusiness where Id like @InsertDate+'___' order by Id DESC ";

like 语句 要加引号的
like ‘.......’
你的就是like ‘@InsertDate’

当sqlcommand转化为sql语句的时候 包含的@insertdate并没有被初始化,当然要出错了。
"select top 1 Id from tbBusiness where Id like " +FontPart.ToString() + "+'___' order by Id DESC ";

不过'___'是什么意思,我就没看明白了,你的程序我也没看懂是什么意思, 应该加些注释.

先在sql server里执行看看,确定数据库有符合的数据。

like 后面要加引号.
"select top 1 Id from tbBusiness where Id like '@InsertDate" + "___' ord