动态SQL语句
下面的代码运行到SqlDataReader reader = cmd.ExecuteReader( );有异常
string strConnection = "server=127.0.0.1;uid=sa;pwd=sa;database=DavidTest ";
using( SqlConnection con = new SqlConnection( strConnection ) )
{
con.Open( );
SqlCommand cmd = new SqlCommand( );
cmd.Connection = con;
cmd.CommandText = "Select Top @num * From t_UserInfo ";
cmd.Parameters.Add( "num ", SqlDbType.Int ).Value = 1;
SqlDataReader reader = cmd.ExecuteReader( );
while( reader.Read( ) )
{
Console.WriteLine(String.Format( "Name:{0}\tAge:{1}\tState:{2} ",reader[1],reader[2],reader[3]));
}
reader.Close();
}
异常是:第 1 行: '@num ' 附近有语法错误
------解决方案--------------------cmd.Parameters.Add( "@num ", SqlDbType.Int ).Value = 1;
------解决方案--------------------用try{} catch
把错误去出来!
------解决方案--------------------cmd.Parameters.Add( "@num ", SqlDbType.Int ).Value = 1;
@ ?
------解决方案--------------------应该就是这个原因
------解决方案--------------------这么明白的告诉你了,语法错误, "Select Top @num * From t_UserInfo "这句SQL不对。
------解决方案--------------------真是奇怪,难道你的sql前面还要execute? 试试吧
------解决方案--------------------cmd.CommandText = "Select Top @num * From t_UserInfo ";错误
查列名不需要带@,只需要列名