"必须声明标量变量"的问题

hengsf2008 2010-06-18 09:56:41
     conn.Open();

SqlCommand cmd1 = new SqlCommand("select count(*) from GLXT where BH = @BH", conn);
int count = Convert.ToInt32(cmd1.ExecuteScalar());

if (count == 0)
{
string sql = "insert into GLXT (BH,XB,NL) values (@BH,@XB,@NL)";
cmd = new SqlCommand(sql, conn);
}
else
{
string sql = "update GLXT set XB = @XB,NL = @NL where BH = @BH";
cmd = new SqlCommand(sql, conn);
}

SqlParameter[] parameters = new SqlParameter[3];
parameters[0] = new SqlParameter();
parameters[0].ParameterName = "@BH";
parameters[0].SqlDbType = SqlDbType.VarChar;

parameters[1] = new SqlParameter();
parameters[1].ParameterName = "@XB";
parameters[1].SqlDbType = SqlDbType.VarChar;

parameters[2] = new SqlParameter();
parameters[2].ParameterName = "@NL";
parameters[2].SqlDbType = SqlDbType.VarChar;

for (int i = 0; i < parameters.Length; i++)
{
cmd.Parameters.Add(parameters[i]);
}


提示:必须声明标量变量 "@BH"。
...全文
667 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
poloyzhang 2010-06-18
  • 打赏
  • 举报
回复
这种问题是没有申请局部变量, 当在sql server 中的话要用
declare @BH nvarchar( 50) 申明一下这个是个局部变量.
你编程中一上来就用这个变量.当然会出错.

程序中要用的话就要像4 楼的.
cmd1.Parameters.Add("@BH",SqlDbType.VarChar,20).Value='XXXXXXX';
hengsf2008 2010-06-18
  • 打赏
  • 举报
回复
哦,谢谢各位,是我的疏忽。。。
Trance 2010-06-18
  • 打赏
  • 举报
回复
这是Java的语法吗?

这个不是sql server的问题,应该是你语言中参数传递问题。。
Liyingyue_FFS 2010-06-18
  • 打赏
  • 举报
回复
                if (count == 0)
{
string sql = "insert into GLXT (BH,XB,NL) values (@BH,@XB,@NL)";
cmd = new SqlCommand(sql, conn);
}
else
{
string sql = "update GLXT set XB = @XB,NL = @NL where BH = @BH";
cmd = new SqlCommand(sql, conn);
}

单就这样的调用在运行SQL的时候是没有变量定义的,建议把变量的值直接在程序里面就拼在SQLSTR里面,然后再运行SQL,或者写成存储过程调用
永生天地 2010-06-18
  • 打赏
  • 举报
回复
这里没传参数,改为如下

SqlCommand cmd1 = new SqlCommand("select count(*) from GLXT where BH = @BH", conn);
cmd1.Parameters.Add("@BH",SqlDbType.VarChar,20).Value='XXXXXXX';
int count = Convert.ToInt32(cmd1.ExecuteScalar());
冷箫轻笛 2010-06-18
  • 打赏
  • 举报
回复
测试过了,跟参数位置无关。
鸟儿说的很对
chuifengde 2010-06-18
  • 打赏
  • 举报
回复
SqlCommand cmd1 = new SqlCommand("select count(*) from GLXT where BH = @BH", conn);
int count = Convert.ToInt32(cmd1.ExecuteScalar());

这个里面带参数@BH,怎么能执行呢?

冷箫轻笛 2010-06-18
  • 打赏
  • 举报
回复
我感觉参数定义应该放在前面吧?
没测试过

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧