日期:2014-05-17 浏览次数:20636 次
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; }
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; }
------解决方案--------------------
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)";
表变量作为参数要么这样写。