问题
alt text http://img24.imageshack.us/img24/3365/sqlnuts.jpg
well heres the code
public void select_table_names()
{//start
/* display all tables*/
string commandString = null;
SqlConnection conn = null;
SqlCommand command = null;
SqlDataReader reader = null;
ArrayList list = new ArrayList();
try
{
// commandString = "SELECT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES ";// @table ";
//string columns;
//string tables;
//columns = "TABLE_SCHEMA";
//tables = "INFORMATION_SCHEMA.TABLES";
commandString = "SELECT @pthis FROM @tables";
//note when the @tables is replaced by info..schema, still the result is like in figure two"
//commandString = "SELECT "+columns+" FROM "+tables;
conn = new SqlConnection(Class1.connection);
command = new SqlCommand(commandString, conn);
// Add the parameters for the SelectCommand.
SqlParameter table = new SqlParameter();
command.Parameters.Add("@pthis", SqlDbType.NVarChar, 100);
command.Parameters.Add("@tables", SqlDbType.NVarChar, 100);
//Add values to these parameters
command.Parameters["@tables"].Value = "INFORMATION_SCHEMA.TABLES";
command.Parameters["@pthis"].Value = "TABLE_SCHEMA";
conn.Open();
reader = command.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
// DropDownList1.DataSource = reader;
// DropDownList1.DataTextField = "TABLE_NAME";
// DropDownList1.DataValueField = "TABLE_NAME";
// DropDownList1.DataBind();
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
}//try ends here.
catch (SqlException ex)
{
try
{
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
}
catch (Exception az)
{
Response.Write(az.Message);
}
Class1 object1 = new Class1();
object1.errorMessages = new System.Text.StringBuilder();
for (int i = 0; i < ex.Errors.Count; i++)
{
object1.errorMessages.Append("\n135 \n" + "Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
Response.Write(object1.errorMessages.ToString());
}//sql catch ends here
catch (Exception all)
{
Label1.Text = "153 all\n" + all.ToString();
try
{
reader.Close();
reader.Dispose();
conn.Close();
conn.Dispose();
}
catch (Exception zx)
{
Label5.Text = "connection 192 " + zx.Message;
}
Response.Write(all.Message.ToString());
}//catch all ends
}//select_table_names
回答1:
SQL Server will definately not allow the use of a variable as a table name. As for your column name variable, it will return the number of results that the table has, but it will output TABLE_SCHEMA.
回答2:
I'm not to familiar with MS-SQL, but I don't think that parameter markers like this
SELECT @pthis FROM @tables
work.
Parameters are normally be used instead of literal values, not instead of identifiers.
来源:https://stackoverflow.com/questions/3092121/sql-going-nuts-does-not-accept-parameters