System.Data.SqlClient.SqlException: Incorrect syntax near "=" - sql

I try am trying to build a function that populates a table when given the name of the table and what parameter to order it by.
I think I am just making a syntax error in my SQL command but I can't find it. Please help.
public DataTable populateTable(string tableName, string orderByParameter)
{
DataTable table = new DataTable();
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string cmdString = "SELECT * FROM (value = #tbl) ORDER BY (parameter = #obp) DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = cmdString;
cmd.Parameters.AddWithValue("#tbl", tableName);
cmd.Parameters.AddWithValue("#obp", orderByParameter);
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
try
{
GridView1.DataSource = table;
GridView1.DataBind();
return table;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
}

You can't have variables in table name or in 'order by' clause.
You could build the query dynamically as:
string cmdString = "SELECT * FROM [" + tableName + "] ORDER BY " + orderByParameter +" DESC";
With this you won't need to add the parameters #tbl and #obp to the command.
Note that this runs into SQL injection related vulnerabilities. So you shouldn't do this unless you are absolutely certain that the table with given name exists, and the orderByParameter is a valid expression.

Related

I wrote an SQL SELECT statement that returns the entire table data rather then just the results that match my search

I have the following code that runs on a button click:
protected void Button2_Click(object sender, EventArgs e)
{
String str = "SELECT * " +
"FROM ConcernTicket INNER JOIN Employee " +
"ON ConcernTicket.EmployeeReportedToID = Employee.EmployeeId " +
"WHERE (Employee.FirstName LIKE '%' + #search2 + '%')";
SqlCommand xp = new SqlCommand(str, vid);
xp.Parameters.Add("#search2", SqlDbType.NVarChar).Value =
TextBox1.Text;
vid.Open();
xp.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = xp;
DataSet ds = new DataSet();
da.Fill(ds, "Employee.FirstName");
GridView2.DataSource = ds;
GridView2.DataBind();
vid.Close();
}
The problem I am facing is that the search runs with no errors but instead of just returning the results where the FirstName variable matches, it displays all current Concern Tickets. I am assuming it is a fairly simple fix with the SELECT statement, but for some reason I have not been able to figure out what is going wrong. I just started working with sql so I apologize that I am having such a silly issue, any help would be appreciated, thanks!
Check that TextBox1.Text is not empty. If it is empty, the query will be:
WHERE (Employee.FirstName LIKE '%%')";
Also check that #search2 is being replaced properly. The + operator is not what you would expect in MySQL. Perhaps this is what you're looking for:
"WHERE (Employee.FirstName LIKE '%#search2%')";
Hope that helps
your problem is not the SQL query. In fact you use ExecuteNonQuery() to extract select result. ExecuteNonQuery() just returns a single integer.Please use a code like this and let me know if the problem persists.
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
adapter.SelectCommand = new SqlCommand("Your SQL Statement Here", connection);
adapter.Fill(ds);
connection.Close();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[1].ItemArray[1].ToString());
}
}

SQL Count from specific Column in Database

I want to get a SQL Count of the number of records that pertain to my bundnum column and display it into my textblock. Any suggestions?
SqlConnection conn = new SqlConnection("db connection");
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = 'values' ";
conn.Open();
int returnValue = (int)comm.ExecuteScalar();
txtNumber.Text = returnValue.ToString();
Using Google, I found this helpful link and after some modification:
Int32 newCount = 0;
string newValue = "something";
string sql =
"SELECT COUNT(*) FROM dbo.tablename WHERE bundnum = '#myValue'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#myValue", SqlDbType.VarChar);
cmd.Parameters["#myValue"].Value = newValue;
try
{
conn.Open();
newCount = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Select SCOPE_IDENTITY not executing after insert statement;

I try to get the id of the last inserted t ouristin the table as I put Selct SCOPE_IDENTITY; after the insert query.
The problem is that when I try to show the id of the inserted tourist in the label - just nothing happens. (only the insert query is executed);
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += "VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir);Select SCOPE_IDENTITY()";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir",tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir",tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir",tx888_2.Text);
int added = 0;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
if (added > 0)
{
lblproba.Text+=added.ToString();
}
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
}

"Invalid object name" error in adapter.Fill method

I'm trying to make a DataSet from all tables of the AdventureWorks2012 database. But I'm getting an "Invalid object name " error in the adapter.Fill method.
Any ideas?
private void openDBButton_Click(object sender, RoutedEventArgs e)
{
DataSet myDataSet = new DataSet();
SqlDataAdapter myDataAdapter;
SqlCommand myCommand;
string conStr = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + dbPath.Text +
";Integrated Security=true";
SqlConnection connection = new SqlConnection(conStr);
connection.Open();
DataTable tables = connection.GetSchema("Tables");
foreach (DataRow table in tables.Rows)
{
if (table["TABLE_TYPE"].ToString() != "BASE TABLE")
continue;
string tableName = table["TABLE_NAME"].ToString();
string sqlCmd = "SELECT * FROM " + "[" + tableName + "]";
//SqlDataAdapter adapt = new SqlDataAdapter(new SqlCommand(sqlCmd, connection));
//adapt.FillSchema(myDataSet, SchemaType.Mapped, tableName);
myCommand = new SqlCommand(sqlCmd, connection);
myDataAdapter = new SqlDataAdapter(myCommand);
myDataAdapter.Fill(myDataSet, tableName); // here i'm get in trouble :)
}
}

SqlCommand.ExecuteScalar - specify a particular data item

I have a Stored Procedure which returns 10 columns of data. Using cmd.ExecuteScalar() returns the value of the 1st column from the 1st record.
How can I change this so that I can return different columns, by specifying their alias/dataitem name?
I want to be able to do something like:
Dim FirstName as String = cmd.ExecuteScalar("FirstName")
You could create a method that calls ExecuteReader, and then uses GetOrdinal with your column name to then call GetString.
My VB is non-existent, but this is the C# for an extension method.
public static class SqlCommandExt
{
public static string ExecuteScalar(this SqlCommand cmd, string columnName)
{
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
return null;
var index = reader.GetOrdinal(columnName);
return reader.GetString(index);
}
}
}
You can not. Command.ExecuteScalar take no parameters ..
What you can do is to use a text command and modify its CommandText property value to include the column you need to get:
command.CommandText = "SELECT " + columnName + " FROM Table WHERE Key = " + ...
You could create an extension method to do this for you. C# equiv (which I imagine you could translate to a VB.NET extension rather easily):
public static T ExecuteScalar<T>(this SqlCommand cmd, String columnName)
{
using(var reader = cmd.ExecuteReader())
{
var item = default(T);
if(reader.Read())
{
item = (T)dataReader.GetValue(dataReader.GetOrdinal(columnName))
}
return item;
}
}
... and invoke it like so:
var firstName = cmd.ExecuteScalar<String>("FirstName");
You should try the below code also.
Private Sub YourFunctionName()
Using con As System.Data.SqlClient.SqlConnection = New SqlConnection("YourConnection string")
con.Open()
Using cmd As SqlCommand = New SqlCommand
Dim expression As String = "Parameter value"
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "Your Stored Procedure"
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression
cmd.Connection = con
Using dr As IDataReader = cmd.ExecuteReader()
If dr.Read() Then
Dim str As String = dr("YourColumnName").ToString()
End If
End Using
End Using
End Using
End Sub