当前位置: 代码迷 >> Sql Server >> SqlParameter 带参数执行SQL语句的有关问题
  详细解决方案

SqlParameter 带参数执行SQL语句的有关问题

热度:557   发布时间:2016-04-25 01:13:43.0
SqlParameter 带参数执行SQL语句的问题
C# code
            SqlParameter[] pars = new SqlParameter[1];                     pars[0] = new SqlParameter("@TableName", SqlDbType.NVarChar, 80);                     pars[0].Value = tablename;                     //pars[1] = new SqlParameter("@Condition", SqlDbType.NVarChar, 800);                     //pars[1].Value = Condition;                     string cmdText = "select Count(1) from @TableName";                     SqlCommand cmd = new SqlCommand(cmdText, conn);                     conn.Open();                     if (pars != null) cmd.Parameters.AddRange(pars);                     if ((int)cmd.ExecuteScalar() > 0)                     {                         return true;                     }                     else                     {                         return false;                     }


为什么这样写不能执行,TableName也已经定义了.

错误提示:
必须声明表变量 "@TableName"。




 

------解决方案--------------------
C# code
            SqlParameter[] pars = new SqlParameter[1];                     pars[0] = new SqlParameter("@TableName", SqlDbType.NVarChar, 80);                     pars[0].Value = tablename;                     //pars[1] = new SqlParameter("@Condition", SqlDbType.NVarChar, 800);                     //pars[1].Value = Condition;                     string cmdText = "select Count(1) from @TableName";                     pars[0] = new SqlParameter("@TableName", SqlDbType.NVarChar, 80);                     pars[0].Value = tablename;                     SqlCommand cmd = new SqlCommand(cmdText, conn);                     conn.Open();                     if (pars != null) cmd.Parameters.AddRange(pars);                     if ((int)cmd.ExecuteScalar() > 0)                     {                         return true;                     }                     else                     {                         return false;                     }
------解决方案--------------------
C# code
class Program    {                public Program()        {            string tableName = "Employees";            SqlConnection conn = new System.Data.SqlClient.SqlConnection("server=.;integrated security=sspi;database=northwind");            SqlCommand cmd = new System.Data.SqlClient.SqlCommand();            cmd.Connection = conn;            cmd.CommandText = String.Format("SELECT COUNT(1) FROM {0}", tableName);            conn.Open();            Console.WriteLine(cmd.ExecuteScalar().ToString());            conn.Close();            Console.ReadLine();        }        static void Main(string[] args)        {            Program p = new Program();            Console.ReadLine();        }    }
------解决方案--------------------
表名不能作为参数传进去,数据库会认为是零时表名,用2楼方法。
------解决方案--------------------
对,如ssp所说
我认为你使用的仅仅是一个错误的方法
------解决方案--------------------
string cmdText = "exec('select Count(1) from '+@TableName)";

表变量作为参数要么这样写。